hexsha
stringlengths
40
40
size
int64
2
1.05M
content
stringlengths
2
1.05M
avg_line_length
float64
1.33
100
max_line_length
int64
1
1k
alphanum_fraction
float64
0.25
1
48eb0f15610e7866fbb85ddeb57004b616a8f391
52,433
//! MovieClip prototype use crate::avm1::activation::Activation; use crate::avm1::error::Error; use crate::avm1::globals::display_object::{self, AVM_DEPTH_BIAS, AVM_MAX_DEPTH}; use crate::avm1::globals::matrix::gradient_object_to_matrix; use crate::avm1::property_decl::{define_properties_on, Declaration}; use crate::avm1::{self, Object, ScriptObject, TObject, Value}; use crate::avm_error; use crate::avm_warn; use crate::backend::{navigator::NavigationMethod, render}; use crate::display_object::{ Bitmap, DisplayObject, EditText, MovieClip, TDisplayObject, TDisplayObjectContainer, }; use crate::ecma_conversions::f64_to_wrapping_i32; use crate::prelude::*; use crate::shape_utils::DrawCommand; use crate::string::AvmString; use crate::vminterface::Instantiator; use gc_arena::MutationContext; use std::borrow::Cow; use swf::{ FillStyle, Fixed8, Gradient, GradientInterpolation, GradientRecord, GradientSpread, LineCapStyle, LineJoinStyle, LineStyle, Twips, }; macro_rules! mc_method { ( $fn:expr ) => { |activation, this, args| { if let Some(display_object) = this.as_display_object() { if let Some(movie_clip) = display_object.as_movie_clip() { return $fn(movie_clip, activation, args); } } Ok(Value::Undefined) } }; } macro_rules! mc_getter { ( $get:expr ) => { |activation, this, _args| { if let Some(display_object) = this.as_display_object() { if let Some(movie_clip) = display_object.as_movie_clip() { return $get(movie_clip, activation); } } Ok(Value::Undefined) } }; } macro_rules! mc_setter { ( $set:expr ) => { |activation, this, args| { if let Some(display_object) = this.as_display_object() { if let Some(movie_clip) = display_object.as_movie_clip() { let value = args.get(0).unwrap_or(&Value::Undefined).clone(); $set(movie_clip, activation, value)?; } } Ok(Value::Undefined) } }; } const PROTO_DECLS: &[Declaration] = declare_properties! { "attachMovie" => method(mc_method!(attach_movie); DONT_ENUM | DONT_DELETE | READ_ONLY); "createEmptyMovieClip" => method(mc_method!(create_empty_movie_clip); DONT_ENUM | DONT_DELETE | READ_ONLY); "createTextField" => method(mc_method!(create_text_field); DONT_ENUM | DONT_DELETE | READ_ONLY); "duplicateMovieClip" => method(mc_method!(duplicate_movie_clip); DONT_ENUM | DONT_DELETE | READ_ONLY); "getBounds" => method(mc_method!(get_bounds); DONT_ENUM | DONT_DELETE | READ_ONLY); "getBytesLoaded" => method(mc_method!(get_bytes_loaded); DONT_ENUM | DONT_DELETE | READ_ONLY); "getBytesTotal" => method(mc_method!(get_bytes_total); DONT_ENUM | DONT_DELETE | READ_ONLY); "getInstanceAtDepth" => method(mc_method!(get_instance_at_depth); DONT_ENUM | DONT_DELETE | READ_ONLY); "getNextHighestDepth" => method(mc_method!(get_next_highest_depth); DONT_ENUM | DONT_DELETE | READ_ONLY); "getRect" => method(mc_method!(get_rect); DONT_ENUM | DONT_DELETE | READ_ONLY); "getURL" => method(mc_method!(get_url); DONT_ENUM | DONT_DELETE | READ_ONLY); "globalToLocal" => method(mc_method!(global_to_local); DONT_ENUM | DONT_DELETE | READ_ONLY); "gotoAndPlay" => method(mc_method!(goto_and_play); DONT_ENUM | DONT_DELETE | READ_ONLY); "gotoAndStop" => method(mc_method!(goto_and_stop); DONT_ENUM | DONT_DELETE | READ_ONLY); "hitTest" => method(mc_method!(hit_test); DONT_ENUM | DONT_DELETE | READ_ONLY); "loadMovie" => method(mc_method!(load_movie); DONT_ENUM | DONT_DELETE | READ_ONLY); "loadVariables" => method(mc_method!(load_variables); DONT_ENUM | DONT_DELETE | READ_ONLY); "localToGlobal" => method(mc_method!(local_to_global); DONT_ENUM | DONT_DELETE | READ_ONLY); "nextFrame" => method(mc_method!(next_frame); DONT_ENUM | DONT_DELETE | READ_ONLY); "play" => method(mc_method!(play); DONT_ENUM | DONT_DELETE | READ_ONLY); "prevFrame" => method(mc_method!(prev_frame); DONT_ENUM | DONT_DELETE | READ_ONLY); "setMask" => method(mc_method!(set_mask); DONT_ENUM | DONT_DELETE | READ_ONLY); "startDrag" => method(mc_method!(start_drag); DONT_ENUM | DONT_DELETE | READ_ONLY); "stop" => method(mc_method!(stop); DONT_ENUM | DONT_DELETE | READ_ONLY); "stopDrag" => method(mc_method!(stop_drag); DONT_ENUM | DONT_DELETE | READ_ONLY); "swapDepths" => method(mc_method!(swap_depths); DONT_ENUM | DONT_DELETE | READ_ONLY); "unloadMovie" => method(mc_method!(unload_movie); DONT_ENUM | DONT_DELETE | READ_ONLY); "beginFill" => method(mc_method!(begin_fill); DONT_ENUM | DONT_DELETE | READ_ONLY); "beginBitmapFill" => method(mc_method!(begin_bitmap_fill); DONT_ENUM | DONT_DELETE | READ_ONLY); "beginGradientFill" => method(mc_method!(begin_gradient_fill); DONT_ENUM | DONT_DELETE | READ_ONLY); "moveTo" => method(mc_method!(move_to); DONT_ENUM | DONT_DELETE | READ_ONLY); "lineTo" => method(mc_method!(line_to); DONT_ENUM | DONT_DELETE | READ_ONLY); "curveTo" => method(mc_method!(curve_to); DONT_ENUM | DONT_DELETE | READ_ONLY); "endFill" => method(mc_method!(end_fill); DONT_ENUM | DONT_DELETE | READ_ONLY); "lineStyle" => method(mc_method!(line_style); DONT_ENUM | DONT_DELETE | READ_ONLY); "clear" => method(mc_method!(clear); DONT_ENUM | DONT_DELETE | READ_ONLY); "attachBitmap" => method(mc_method!(attach_bitmap); DONT_ENUM | DONT_DELETE | READ_ONLY); "removeMovieClip" => method(remove_movie_clip; DONT_ENUM | DONT_DELETE | READ_ONLY); "transform" => property(mc_getter!(transform), mc_setter!(set_transform); DONT_DELETE | DONT_ENUM); "enabled" => property(mc_getter!(enabled), mc_setter!(set_enabled); DONT_DELETE | DONT_ENUM); "focusEnabled" => property(mc_getter!(focus_enabled), mc_setter!(set_focus_enabled); DONT_DELETE | DONT_ENUM); "_lockroot" => property(mc_getter!(lock_root), mc_setter!(set_lock_root); DONT_DELETE | DONT_ENUM); "useHandCursor" => property(mc_getter!(use_hand_cursor), mc_setter!(set_use_hand_cursor); DONT_DELETE | DONT_ENUM); }; /// Implements `MovieClip` pub fn constructor<'gc>( _activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.into()) } #[allow(clippy::comparison_chain)] pub fn hit_test<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if args.len() > 1 { let x = args.get(0).unwrap().coerce_to_f64(activation)?; let y = args.get(1).unwrap().coerce_to_f64(activation)?; let shape = args .get(2) .map(|v| v.as_bool(activation.swf_version())) .unwrap_or(false); if x.is_finite() && y.is_finite() { // The docs say the point is in "Stage coordinates", but actually they are in root coordinates. // root can be moved via _root._x etc., so we actually have to transform from root to world space. let point = movie_clip .avm1_root(&activation.context)? .local_to_global((Twips::from_pixels(x), Twips::from_pixels(y))); let ret = if shape { movie_clip.hit_test_shape( &mut activation.context, point, HitTestOptions::AVM_HIT_TEST, ) } else { movie_clip.hit_test_bounds(point) }; return Ok(ret.into()); } } else if args.len() == 1 { let other = activation.resolve_target_display_object( movie_clip.into(), *args.get(0).unwrap(), false, )?; if let Some(other) = other { return Ok(movie_clip.hit_test_object(other).into()); } } Ok(false.into()) } pub fn create_proto<'gc>( gc_context: MutationContext<'gc, '_>, proto: Object<'gc>, fn_proto: Object<'gc>, ) -> Object<'gc> { let object = ScriptObject::object(gc_context, Some(proto)); display_object::define_display_object_proto(gc_context, object, fn_proto); define_properties_on(PROTO_DECLS, gc_context, object, fn_proto); object.into() } fn attach_bitmap<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Some(bitmap) = args.get(0) { if let Some(bitmap_data) = bitmap .coerce_to_object(activation) .as_bitmap_data_object() .map(|bd| bd.bitmap_data()) { if let Some(depth) = args.get(1) { let depth = depth .coerce_to_i32(activation)? .wrapping_add(AVM_DEPTH_BIAS); let bitmap_handle = bitmap_data .write(activation.context.gc_context) .bitmap_handle(activation.context.renderer); // TODO: Implement pixel snapping let _pixel_snapping = args .get(2) .unwrap_or(&Value::Undefined) .as_bool(activation.swf_version()); let smoothing = args .get(3) .unwrap_or(&Value::Undefined) .as_bool(activation.swf_version()); if let Some(bitmap_handle) = bitmap_handle { //TODO: do attached BitmapDatas have character ids? let display_object = Bitmap::new_with_bitmap_data( &mut activation.context, 0, Some(bitmap_handle), bitmap_data.read().width() as u16, bitmap_data.read().height() as u16, Some(bitmap_data), smoothing, ); movie_clip.replace_at_depth( &mut activation.context, display_object.into(), depth, ); display_object.post_instantiation( &mut activation.context, display_object.into(), None, Instantiator::Avm1, true, ); } } } } Ok(Value::Undefined) } fn line_style<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Some(width) = args.get(0) { let width = Twips::from_pixels(width.coerce_to_f64(activation)?.min(255.0).max(0.0)); let color = if let Some(rgb) = args.get(1) { let rgb = rgb.coerce_to_u32(activation)?; let alpha = if let Some(alpha) = args.get(2) { alpha.coerce_to_f64(activation)?.min(100.0).max(0.0) } else { 100.0 } as f32 / 100.0 * 255.0; Color::from_rgb(rgb, alpha as u8) } else { Color::from_rgb(0, 255) }; let is_pixel_hinted = args .get(3) .map_or(false, |v| v.as_bool(activation.swf_version())); let (allow_scale_x, allow_scale_y) = match args .get(4) .and_then(|v| v.coerce_to_string(activation).ok()) .as_deref() { Some("normal") => (true, true), Some("vertical") => (true, false), Some("horizontal") => (false, true), _ => (false, false), }; let cap_style = match args .get(5) .and_then(|v| v.coerce_to_string(activation).ok()) .as_deref() { Some("square") => LineCapStyle::Square, Some("none") => LineCapStyle::None, _ => LineCapStyle::Round, }; let join_style = match args .get(6) .and_then(|v| v.coerce_to_string(activation).ok()) .as_deref() { Some("miter") => { if let Some(limit) = args.get(7) { let limit = limit.coerce_to_f64(activation)?.max(0.0).min(255.0); LineJoinStyle::Miter(Fixed8::from_f64(limit)) } else { LineJoinStyle::Miter(Fixed8::from_f32(3.0)) } } Some("bevel") => LineJoinStyle::Bevel, _ => LineJoinStyle::Round, }; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_line_style(Some(LineStyle { width, color, start_cap: cap_style, end_cap: cap_style, join_style, fill_style: None, allow_scale_x, allow_scale_y, is_pixel_hinted, allow_close: false, })); } else { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_line_style(None); } Ok(Value::Undefined) } fn begin_fill<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Some(rgb) = args.get(0) { let rgb = rgb.coerce_to_u32(activation)?; let alpha = if let Some(alpha) = args.get(1) { alpha.coerce_to_f64(activation)?.min(100.0).max(0.0) } else { 100.0 } as f32 / 100.0 * 255.0; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(Some(FillStyle::Color(Color::from_rgb(rgb, alpha as u8)))); } else { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(None); } Ok(Value::Undefined) } fn begin_bitmap_fill<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Some(bitmap_data) = args .get(0) .and_then(|val| val.coerce_to_object(activation).as_bitmap_data_object()) { // Register the bitmap data with the drawing. let bitmap_data = bitmap_data.bitmap_data(); let mut bitmap_data = bitmap_data.write(activation.context.gc_context); let handle = if let Some(handle) = bitmap_data.bitmap_handle(activation.context.renderer) { handle } else { return Ok(Value::Undefined); }; let bitmap = render::BitmapInfo { handle, width: bitmap_data.width() as u16, height: bitmap_data.height() as u16, }; let id = movie_clip .as_drawing(activation.context.gc_context) .unwrap() .add_bitmap(bitmap); let mut matrix = avm1::globals::matrix::object_to_matrix_or_default( args.get(1) .unwrap_or(&Value::Undefined) .coerce_to_object(activation), activation, )?; // Flash matrix is in pixels. Scale from pixels to twips. const PIXELS_TO_TWIPS: Matrix = Matrix { a: 20.0, b: 0.0, c: 0.0, d: 20.0, tx: Twips::ZERO, ty: Twips::ZERO, }; matrix *= PIXELS_TO_TWIPS; // `repeating` defaults to true, `smoothed` to false. // `smoothed` parameter may not be listed in some documentation. let is_repeating = args .get(2) .unwrap_or(&true.into()) .as_bool(activation.swf_version()); let is_smoothed = args .get(3) .unwrap_or(&false.into()) .as_bool(activation.swf_version()); movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(Some(FillStyle::Bitmap { id, matrix: matrix.into(), is_smoothed, is_repeating, })); } else { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(None); } Ok(Value::Undefined) } fn begin_gradient_fill<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let (Some(method), Some(colors), Some(alphas), Some(ratios), Some(matrix)) = ( args.get(0), args.get(1), args.get(2), args.get(3), args.get(4), ) { let method = method.coerce_to_string(activation)?; let colors_object = colors.coerce_to_object(activation); let colors_length = colors_object.length(activation)?; let alphas_object = alphas.coerce_to_object(activation); let alphas_length = alphas_object.length(activation)?; let ratios_object = ratios.coerce_to_object(activation); let ratios_length = ratios_object.length(activation)?; let matrix_object = matrix.coerce_to_object(activation); if colors_length != alphas_length || colors_length != ratios_length { avm_warn!( activation, "beginGradientFill() received different sized arrays for colors, alphas and ratios" ); return Ok(Value::Undefined); } let records: Result<Vec<_>, Error<'gc>> = (0..colors_length) .map(|i| { let ratio = ratios_object .get_element(activation, i) .coerce_to_f64(activation)? .clamp(0.0, 255.0) as u8; let rgb = colors_object .get_element(activation, i) .coerce_to_u32(activation)?; let alpha = alphas_object .get_element(activation, i) .coerce_to_f64(activation)? .clamp(0.0, 100.0); Ok(GradientRecord { ratio, color: Color::from_rgb(rgb, (alpha / 100.0 * 255.0) as u8), }) }) .collect(); let records = records?; let matrix = gradient_object_to_matrix(matrix_object, activation)?; let spread = match args .get(5) .and_then(|v| v.coerce_to_string(activation).ok()) .as_deref() { Some("reflect") => GradientSpread::Reflect, Some("repeat") => GradientSpread::Repeat, _ => GradientSpread::Pad, }; let interpolation = match args .get(6) .and_then(|v| v.coerce_to_string(activation).ok()) .as_deref() { Some("linearRGB") => GradientInterpolation::LinearRgb, _ => GradientInterpolation::Rgb, }; let gradient = Gradient { matrix: matrix.into(), spread, interpolation, records, }; let style = match method.as_ref() { "linear" => FillStyle::LinearGradient(gradient), "radial" => { if let Some(focal_point) = args.get(7) { FillStyle::FocalGradient { gradient, focal_point: Fixed8::from_f64(focal_point.coerce_to_f64(activation)?), } } else { FillStyle::RadialGradient(gradient) } } other => { avm_warn!( activation, "beginGradientFill() received invalid fill type {:?}", other ); return Ok(Value::Undefined); } }; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(Some(style)); } else { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(None); } Ok(Value::Undefined) } fn move_to<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let (Some(x), Some(y)) = (args.get(0), args.get(1)) { let x = x.coerce_to_f64(activation)?; let y = y.coerce_to_f64(activation)?; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .draw_command(DrawCommand::MoveTo { x: Twips::from_pixels(x), y: Twips::from_pixels(y), }); } Ok(Value::Undefined) } fn line_to<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let (Some(x), Some(y)) = (args.get(0), args.get(1)) { let x = x.coerce_to_f64(activation)?; let y = y.coerce_to_f64(activation)?; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .draw_command(DrawCommand::LineTo { x: Twips::from_pixels(x), y: Twips::from_pixels(y), }); } Ok(Value::Undefined) } fn curve_to<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let (Some(x1), Some(y1), Some(x2), Some(y2)) = (args.get(0), args.get(1), args.get(2), args.get(3)) { let x1 = x1.coerce_to_f64(activation)?; let y1 = y1.coerce_to_f64(activation)?; let x2 = x2.coerce_to_f64(activation)?; let y2 = y2.coerce_to_f64(activation)?; movie_clip .as_drawing(activation.context.gc_context) .unwrap() .draw_command(DrawCommand::CurveTo { x1: Twips::from_pixels(x1), y1: Twips::from_pixels(y1), x2: Twips::from_pixels(x2), y2: Twips::from_pixels(y2), }); } Ok(Value::Undefined) } fn end_fill<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .set_fill_style(None); Ok(Value::Undefined) } fn clear<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip .as_drawing(activation.context.gc_context) .unwrap() .clear(); Ok(Value::Undefined) } fn attach_movie<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let (export_name, new_instance_name, depth) = match &args.get(0..3) { Some([export_name, new_instance_name, depth]) => ( export_name.coerce_to_string(activation)?, new_instance_name.coerce_to_string(activation)?, depth .coerce_to_i32(activation)? .wrapping_add(AVM_DEPTH_BIAS), ), _ => { avm_error!(activation, "MovieClip.attachMovie: Too few parameters"); return Ok(Value::Undefined); } }; let init_object = args.get(3); // TODO: What is the derivation of this max value? It shows up a few times in the AVM... // 2^31 - 16777220 if depth < 0 || depth > AVM_MAX_DEPTH { return Ok(Value::Undefined); } if let Ok(new_clip) = activation .context .library .library_for_movie(movie_clip.movie().unwrap()) .ok_or_else(|| "Movie is missing!".into()) .and_then(|l| l.instantiate_by_export_name(&export_name, activation.context.gc_context)) { // Set name and attach to parent. new_clip.set_name(activation.context.gc_context, new_instance_name); movie_clip.replace_at_depth(&mut activation.context, new_clip, depth); let init_object = if let Some(Value::Object(init_object)) = init_object { Some(init_object.to_owned()) } else { None }; new_clip.post_instantiation( &mut activation.context, new_clip, init_object, Instantiator::Avm1, true, ); Ok(new_clip.object().coerce_to_object(activation).into()) } else { avm_warn!(activation, "Unable to attach '{}'", export_name); Ok(Value::Undefined) } } fn create_empty_movie_clip<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let (new_instance_name, depth) = match &args.get(0..2) { Some([new_instance_name, depth]) => ( new_instance_name.coerce_to_string(activation)?, depth .coerce_to_i32(activation)? .wrapping_add(AVM_DEPTH_BIAS), ), _ => { avm_error!( activation, "MovieClip.createEmptyMovieClip: Too few parameters" ); return Ok(Value::Undefined); } }; // Create empty movie clip. let swf_movie = movie_clip .movie() .or_else(|| activation.base_clip().movie()) .unwrap(); let new_clip = MovieClip::new(swf_movie, activation.context.gc_context); // Set name and attach to parent. new_clip.set_name(activation.context.gc_context, new_instance_name); movie_clip.replace_at_depth(&mut activation.context, new_clip.into(), depth); new_clip.post_instantiation( &mut activation.context, new_clip.into(), None, Instantiator::Avm1, true, ); Ok(new_clip.object()) } fn create_text_field<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let movie = activation.base_clip().movie().unwrap(); let instance_name = args.get(0).cloned().unwrap_or(Value::Undefined); let depth = args .get(1) .cloned() .unwrap_or(Value::Undefined) .coerce_to_f64(activation)?; let x = args .get(2) .cloned() .unwrap_or(Value::Undefined) .coerce_to_f64(activation)?; let y = args .get(3) .cloned() .unwrap_or(Value::Undefined) .coerce_to_f64(activation)?; let width = args .get(4) .cloned() .unwrap_or(Value::Undefined) .coerce_to_f64(activation)?; let height = args .get(5) .cloned() .unwrap_or(Value::Undefined) .coerce_to_f64(activation)?; let text_field: DisplayObject<'gc> = EditText::new(&mut activation.context, movie, x, y, width, height).into(); text_field.set_name( activation.context.gc_context, instance_name.coerce_to_string(activation)?, ); movie_clip.replace_at_depth( &mut activation.context, text_field, (depth as Depth).wrapping_add(AVM_DEPTH_BIAS), ); text_field.post_instantiation( &mut activation.context, text_field, None, Instantiator::Avm1, false, ); if activation.swf_version() >= 8 { //SWF8+ returns the `TextField` instance here Ok(text_field.object()) } else { Ok(Value::Undefined) } } fn duplicate_movie_clip<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { // duplicateMovieClip method uses biased depth compared to CloneSprite duplicate_movie_clip_with_bias(movie_clip, activation, args, AVM_DEPTH_BIAS) } pub fn duplicate_movie_clip_with_bias<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], depth_bias: i32, ) -> Result<Value<'gc>, Error<'gc>> { let (new_instance_name, depth) = match &args.get(0..2) { Some([new_instance_name, depth]) => ( new_instance_name.coerce_to_string(activation)?, depth.coerce_to_i32(activation)?.wrapping_add(depth_bias), ), _ => { avm_error!( activation, "MovieClip.duplicateMovieClip: Too few parameters" ); return Ok(Value::Undefined); } }; let init_object = args.get(2); // Can't duplicate the root! let parent = if let Some(parent) = movie_clip.avm1_parent().and_then(|o| o.as_movie_clip()) { parent } else { return Ok(Value::Undefined); }; // TODO: What is the derivation of this max value? It shows up a few times in the AVM... // 2^31 - 16777220 if depth < 0 || depth > AVM_MAX_DEPTH { return Ok(Value::Undefined); } let id = movie_clip.id(); let movie = parent .movie() .or_else(|| activation.base_clip().movie()) .unwrap_or_else(|| activation.context.swf.clone()); let new_clip = if movie_clip.id() != 0 { // Clip from SWF; instantiate a new copy. activation .context .library .library_for_movie(movie) .ok_or_else(|| "Movie is missing!".into()) .and_then(|l| l.instantiate_by_id(id, activation.context.gc_context)) } else { // Dynamically created clip; create a new empty movie clip. Ok(MovieClip::new(movie, activation.context.gc_context).into()) }; if let Ok(new_clip) = new_clip { // Set name and attach to parent. new_clip.set_name(activation.context.gc_context, new_instance_name); parent.replace_at_depth(&mut activation.context, new_clip, depth); // Copy display properties from previous clip to new clip. new_clip.set_matrix(activation.context.gc_context, &*movie_clip.matrix()); new_clip.set_color_transform( activation.context.gc_context, &*movie_clip.color_transform(), ); new_clip.as_movie_clip().unwrap().set_clip_event_handlers( activation.context.gc_context, movie_clip.clip_actions().to_vec(), ); *new_clip.as_drawing(activation.context.gc_context).unwrap() = movie_clip .as_drawing(activation.context.gc_context) .unwrap() .clone(); // TODO: Any other properties we should copy...? // Definitely not ScriptObject properties. let init_object = init_object.map(|v| v.coerce_to_object(activation)); new_clip.post_instantiation( &mut activation.context, new_clip, init_object, Instantiator::Avm1, true, ); Ok(new_clip.object().coerce_to_object(activation).into()) } else { avm_warn!( activation, "Unable to duplicate clip '{}'", movie_clip.name() ); Ok(Value::Undefined) } } fn get_bytes_loaded<'gc>( movie_clip: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let bytes_loaded = if movie_clip.is_root() { movie_clip .movie() .map(|mv| mv.uncompressed_len()) .unwrap_or_default() } else { movie_clip.tag_stream_len() as u32 }; Ok(bytes_loaded.into()) } fn get_bytes_total<'gc>( movie_clip: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { // For a loaded SWF, returns the uncompressed size of the SWF. // Otherwise, returns the size of the tag list in the clip's DefineSprite tag. let bytes_total = if movie_clip.is_root() { movie_clip .movie() .map(|mv| mv.uncompressed_len()) .unwrap_or_default() } else { movie_clip.tag_stream_len() as u32 }; Ok(bytes_total.into()) } fn get_instance_at_depth<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if activation.swf_version() >= 7 { let depth = if let Some(depth) = args.get(0) { depth .coerce_to_i32(activation)? .wrapping_add(AVM_DEPTH_BIAS) } else { avm_error!( activation, "MovieClip.get_instance_at_depth: Too few parameters" ); return Ok(Value::Undefined); }; match movie_clip.child_by_depth(depth) { Some(child) => { // If the child doesn't have a corresponding AVM object, return mc itself. // NOTE: this behavior was guessed from observing behavior for Text and Graphic; // I didn't test other variants like Bitmap, MorphSpahe, Video // or objects that weren't fully initialized yet. match child.object() { Value::Undefined => Ok(movie_clip.object()), obj => Ok(obj), } } None => Ok(Value::Undefined), } } else { Ok(Value::Undefined) } } fn get_next_highest_depth<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if activation.swf_version() >= 7 { let depth = std::cmp::max( movie_clip .highest_depth(Depth::MAX) .unwrap_or(0) .wrapping_sub(AVM_DEPTH_BIAS - 1), 0, ); Ok(depth.into()) } else { Ok(Value::Undefined) } } fn goto_and_play<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { goto_frame(movie_clip, activation, args, false, 0) } fn goto_and_stop<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { goto_frame(movie_clip, activation, args, true, 0) } pub fn goto_frame<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], stop: bool, scene_offset: u16, ) -> Result<Value<'gc>, Error<'gc>> { let mut call_frame = None; match args.get(0).cloned().unwrap_or(Value::Undefined) { // A direct goto only runs if n is an integer Value::Number(n) if n.fract() == 0.0 => { // Frame # // Gotoing <= 0 has no effect. // Gotoing greater than _totalframes jumps to the last frame. // Wraps around as an i32. // TODO: -1 +1 here to match Flash's behavior. // We probably want to change our frame representation to 0-based. // Scene offset is only used by GotoFrame2 global opcode. call_frame = Some((movie_clip, f64_to_wrapping_i32(n))); } val => { // Coerce to string and search for a frame label. // This can direct other clips than the one this method was called on! let frame_path = val.coerce_to_string(activation)?; if let Some((clip, frame)) = activation.resolve_variable_path(movie_clip.into(), &frame_path)? { if let Some(clip) = clip.as_display_object().and_then(|o| o.as_movie_clip()) { if let Ok(frame) = frame.parse().map(f64_to_wrapping_i32) { // First try to parse as a frame number. call_frame = Some((clip, frame)); } else if let Some(frame) = clip.frame_label_to_number(frame) { // Otherwise, it's a frame label. call_frame = Some((clip, frame as i32)); } } } } } if let Some((clip, frame)) = call_frame { let frame = frame.wrapping_sub(1); let frame = frame.wrapping_add(i32::from(scene_offset)); let frame = frame.saturating_add(1); if frame > 0 { clip.goto_frame(&mut activation.context, frame as u16, stop); } } Ok(Value::Undefined) } fn next_frame<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip.next_frame(&mut activation.context); Ok(Value::Undefined) } fn play<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip.play(&mut activation.context); Ok(Value::Undefined) } fn prev_frame<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip.prev_frame(&mut activation.context); Ok(Value::Undefined) } fn remove_movie_clip<'gc>( activation: &mut Activation<'_, 'gc, '_>, this: Object<'gc>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { // `removeMovieClip` can remove all types of display object, // e.g. `MovieClip.prototype.removeMovieClip.apply(textField);` if let Some(this) = this.as_display_object() { crate::avm1::globals::display_object::remove_display_object(this, activation); } Ok(Value::Undefined) } fn set_mask<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let mask = args .get(0) .unwrap_or(&Value::Undefined) .coerce_to_object(activation) .as_display_object(); let mc = DisplayObject::MovieClip(movie_clip); let context = &mut activation.context; mc.set_clip_depth(context.gc_context, 0); mc.set_masker(context.gc_context, mask, true); if let Some(m) = mask { m.set_maskee(context.gc_context, Some(mc), true); } Ok(Value::Undefined) } fn start_drag<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { crate::avm1::start_drag(movie_clip.into(), activation, args); Ok(Value::Undefined) } fn stop<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { movie_clip.stop(&mut activation.context); Ok(Value::Undefined) } fn stop_drag<'gc>( _movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { // It doesn't matter which clip we call this on; it simply stops any active drag. *activation.context.drag_object = None; Ok(Value::Undefined) } fn swap_depths<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let arg = args.get(0).cloned().unwrap_or(Value::Undefined); if movie_clip.removed() { return Ok(Value::Undefined); } let mut parent = if let Some(parent) = movie_clip.avm1_parent().and_then(|o| o.as_movie_clip()) { parent } else { return Ok(Value::Undefined); }; let mut depth = None; if let Value::Number(n) = arg { depth = Some(crate::ecma_conversions::f64_to_wrapping_i32(n).wrapping_add(AVM_DEPTH_BIAS)); } else if let Some(target) = activation.resolve_target_display_object(movie_clip.into(), arg, false)? { if let Some(target_parent) = target.avm1_parent() { if DisplayObject::ptr_eq(target_parent, parent.into()) && !target.removed() { depth = Some(target.depth()) } else { avm_warn!( activation, "MovieClip.swapDepths: Objects do not have the same parent" ); } } } else { avm_warn!(activation, "MovieClip.swapDepths: Invalid target"); }; if let Some(depth) = depth { if depth < 0 || depth > AVM_MAX_DEPTH { // Depth out of range; no action. return Ok(Value::Undefined); } if depth != movie_clip.depth() { parent.swap_at_depth(&mut activation.context, movie_clip.into(), depth); movie_clip.set_transformed_by_script(activation.context.gc_context, true); } } Ok(Value::Undefined) } fn local_to_global<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Value::Object(point) = args.get(0).unwrap_or(&Value::Undefined) { // localToGlobal does no coercion; it fails if the properties are not numbers. // It does not search the prototype chain and ignores virtual properties. if let (Value::Number(x), Value::Number(y)) = ( point .get_local_stored("x", activation) .unwrap_or(Value::Undefined), point .get_local_stored("y", activation) .unwrap_or(Value::Undefined), ) { let x = Twips::from_pixels(x); let y = Twips::from_pixels(y); let (out_x, out_y) = movie_clip.local_to_global((x, y)); point.set("x", out_x.to_pixels().into(), activation)?; point.set("y", out_y.to_pixels().into(), activation)?; } else { avm_warn!( activation, "MovieClip.localToGlobal: Invalid x and y properties" ); } } else { avm_warn!( activation, "MovieClip.localToGlobal: Missing point parameter" ); } Ok(Value::Undefined) } fn get_bounds<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let target = match args.get(0) { Some(Value::String(s)) if s.is_empty() => None, Some(Value::Object(o)) if o.as_display_object().is_some() => o.as_display_object(), Some(val) => { let path = val.coerce_to_string(activation)?; activation.resolve_target_display_object( movie_clip.into(), AvmString::new(activation.context.gc_context, path.to_string()).into(), false, )? } None => Some(movie_clip.into()), }; if let Some(target) = target { let bounds = movie_clip.bounds(); let out_bounds = if DisplayObject::ptr_eq(movie_clip.into(), target) { // Getting the clips bounds in its own coordinate space; no AABB transform needed. bounds } else { // Transform AABB to target space. // Calculate the matrix to transform into the target coordinate space, and transform the above AABB. // Note that this doesn't produce as tight of an AABB as if we had used `bounds_with_transform` with // the final matrix, but this matches Flash's behavior. let to_global_matrix = movie_clip.local_to_global_matrix(); let to_target_matrix = target.global_to_local_matrix(); let bounds_transform = to_target_matrix * to_global_matrix; bounds.transform(&bounds_transform) }; let out = ScriptObject::object( activation.context.gc_context, Some(activation.context.avm1.prototypes.object), ); out.set("xMin", out_bounds.x_min.to_pixels().into(), activation)?; out.set("yMin", out_bounds.y_min.to_pixels().into(), activation)?; out.set("xMax", out_bounds.x_max.to_pixels().into(), activation)?; out.set("yMax", out_bounds.y_max.to_pixels().into(), activation)?; Ok(out.into()) } else { Ok(Value::Undefined) } } fn get_rect<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { // TODO: This should get the bounds ignoring strokes. Always equal to or smaller than getBounds. // Just defer to getBounds for now. Will have to store edge_bounds vs. shape_bounds in Graphic. get_bounds(movie_clip, activation, args) } #[allow(unused_must_use)] //can't use errors yet pub fn get_url<'gc>( _movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { use crate::avm1::fscommand; //TODO: Error behavior if no arguments are present if let Some(url_val) = args.get(0) { let url = url_val.coerce_to_string(activation)?; if let Some(fscommand) = fscommand::parse(&url) { let fsargs_val = args.get(1).cloned().unwrap_or(Value::Undefined); let fsargs = fsargs_val.coerce_to_string(activation)?; fscommand::handle(fscommand, &fsargs, activation); return Ok(Value::Undefined); } let window = if let Some(window) = args.get(1) { Some(window.coerce_to_string(activation)?.to_string()) } else { None }; let method = match args.get(2) { Some(Value::String(s)) if *s == "GET" => Some(NavigationMethod::Get), Some(Value::String(s)) if *s == "POST" => Some(NavigationMethod::Post), _ => None, }; let vars_method = method.map(|m| (m, activation.locals_into_form_values())); activation .context .navigator .navigate_to_url(url.to_string(), window, vars_method); } Ok(Value::Undefined) } fn global_to_local<'gc>( movie_clip: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { if let Value::Object(point) = args.get(0).unwrap_or(&Value::Undefined) { // globalToLocal does no coercion; it fails if the properties are not numbers. // It does not search the prototype chain and ignores virtual properties. if let (Value::Number(x), Value::Number(y)) = ( point .get_local_stored("x", activation) .unwrap_or(Value::Undefined), point .get_local_stored("y", activation) .unwrap_or(Value::Undefined), ) { let x = Twips::from_pixels(x); let y = Twips::from_pixels(y); let (out_x, out_y) = movie_clip.global_to_local((x, y)); point.set("x", out_x.to_pixels().into(), activation)?; point.set("y", out_y.to_pixels().into(), activation)?; } else { avm_warn!( activation, "MovieClip.globalToLocal: Invalid x and y properties" ); } } else { avm_warn!( activation, "MovieClip.globalToLocal: Missing point parameter" ); } Ok(Value::Undefined) } fn load_movie<'gc>( target: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let url_val = args.get(0).cloned().unwrap_or(Value::Undefined); let url = url_val.coerce_to_string(activation)?; let method = args.get(1).cloned().unwrap_or(Value::Undefined); let method = NavigationMethod::from_method_str(&method.coerce_to_string(activation)?); let (url, opts) = activation.locals_into_request_options(Cow::Borrowed(&url), method); let fetch = activation.context.navigator.fetch(&url, opts); let process = activation.context.load_manager.load_movie_into_clip( activation.context.player.clone().unwrap(), DisplayObject::MovieClip(target), fetch, url.to_string(), None, None, ); activation.context.navigator.spawn_future(process); Ok(Value::Undefined) } fn load_variables<'gc>( target: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { let url_val = args.get(0).cloned().unwrap_or(Value::Undefined); let url = url_val.coerce_to_string(activation)?; let method = args.get(1).cloned().unwrap_or(Value::Undefined); let method = NavigationMethod::from_method_str(&method.coerce_to_string(activation)?); let (url, opts) = activation.locals_into_request_options(Cow::Borrowed(&url), method); let fetch = activation.context.navigator.fetch(&url, opts); let target = target.object().coerce_to_object(activation); let process = activation.context.load_manager.load_form_into_object( activation.context.player.clone().unwrap(), target, fetch, ); activation.context.navigator.spawn_future(process); Ok(Value::Undefined) } fn unload_movie<'gc>( mut target: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, _args: &[Value<'gc>], ) -> Result<Value<'gc>, Error<'gc>> { target.unload(&mut activation.context); target.replace_with_movie(activation.context.gc_context, None); Ok(Value::Undefined) } fn transform<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error<'gc>> { let constructor = activation.context.avm1.prototypes.transform_constructor; let cloned = constructor.construct(activation, &[this.object()])?; Ok(cloned) } fn set_transform<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, value: Value<'gc>, ) -> Result<(), Error<'gc>> { let transform = value.coerce_to_object(activation); crate::avm1::globals::transform::apply_to_display_object(activation, transform, this.into())?; Ok(()) } fn enabled<'gc>( this: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.enabled().into()) } fn set_enabled<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, value: Value<'gc>, ) -> Result<(), Error<'gc>> { let enabled = value.as_bool(activation.swf_version()); this.set_enabled(&mut activation.context, enabled); Ok(()) } fn focus_enabled<'gc>( this: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.is_focusable().into()) } fn set_focus_enabled<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, value: Value<'gc>, ) -> Result<(), Error<'gc>> { this.set_focusable( value.as_bool(activation.swf_version()), &mut activation.context, ); Ok(()) } fn lock_root<'gc>( this: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.lock_root().into()) } fn set_lock_root<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, value: Value<'gc>, ) -> Result<(), Error<'gc>> { let lock_root = value.as_bool(activation.swf_version()); this.set_lock_root(activation.context.gc_context, lock_root); Ok(()) } fn use_hand_cursor<'gc>( this: MovieClip<'gc>, _activation: &mut Activation<'_, 'gc, '_>, ) -> Result<Value<'gc>, Error<'gc>> { Ok(this.use_hand_cursor().into()) } fn set_use_hand_cursor<'gc>( this: MovieClip<'gc>, activation: &mut Activation<'_, 'gc, '_>, value: Value<'gc>, ) -> Result<(), Error<'gc>> { let use_hand_cursor = value.as_bool(activation.swf_version()); this.set_use_hand_cursor(&mut activation.context, use_hand_cursor); Ok(()) }
35.166331
119
0.574867
385db83cc7660c96a3ec46524b4842be0f777395
7,069
//! # quicksilver //! ![Quicksilver Logo](https://raw.github.com/ryanisaacg/quicksilver/master/logo.svg?sanitize=true) //! //! [![Build Status](https://travis-ci.org/ryanisaacg/quicksilver.svg)](https://travis-ci.org/ryanisaacg/quicksilver) //! [![Crates.io](https://img.shields.io/crates/v/quicksilver.svg)](https://crates.io/crates/quicksilver) //! [![Docs Status](https://docs.rs/quicksilver/badge.svg)](https://docs.rs/quicksilver) //! [![dependency status](https://deps.rs/repo/github/ryanisaacg/quicksilver/status.svg)](https://deps.rs/repo/github/ryanisaacg/quicksilver) //! [![Gitter chat](https://badges.gitter.im/quicksilver-rs/Lobby.svg)](https://gitter.im/quicksilver-rs/Lobby?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) //! //! A 2D game framework written in pure Rust, for both the Web and Desktop //! //! ## A quick example //! //! Create a rust project and add this line to your `Cargo.toml` file under `[dependencies]`: //! ```text //! quicksilver = "*" //! ``` //! Then replace `src/main.rs` with the following (the contents of quicksilver's //! `examples/draw-geometry.rs`): //! //! ```no_run //! // Draw some multi-colored geometry to the screen //! extern crate quicksilver; //! //! use quicksilver::{ //! Result, //! geom::{Circle, Line, Rectangle, Transform, Triangle, Vector}, //! graphics::{Background::Col, Color}, //! lifecycle::{Settings, State, Window, run}, //! }; //! //! struct DrawGeometry; //! //! impl State for DrawGeometry { //! fn new() -> Result<DrawGeometry> { //! Ok(DrawGeometry) //! } //! //! fn draw(&mut self, window: &mut Window) -> Result<()> { //! window.clear(Color::WHITE)?; //! window.draw(&Rectangle::new((100, 100), (32, 32)), Col(Color::BLUE)); //! window.draw_ex(&Rectangle::new((400, 300), (32, 32)), Col(Color::BLUE), Transform::rotate(45), 10); //! window.draw(&Circle::new((400, 300), 100), Col(Color::GREEN)); //! window.draw_ex( //! &Line::new((50, 80),(600, 450)).with_thickness(2.0), //! Col(Color::RED), //! Transform::IDENTITY, //! 5 //! ); //! window.draw_ex( //! &Triangle::new((500, 50), (450, 100), (650, 150)), //! Col(Color::RED), //! Transform::rotate(45) * Transform::scale((0.5, 0.5)), //! 0 //! ); //! Ok(()) //! } //! } //! //! fn main() { //! run::<DrawGeometry>("Draw Geometry", Vector::new(800, 600), Settings::default()); //! } //! ``` //! //! Run this with `cargo run` or, if you have the wasm32 toolchain installed, you can build for the //! web (instructions below). //! //! ## Learning Quicksilver //! //! A good way to get started with Quicksilver is to //! [read and run the examples](https://github.com/ryanisaacg/quicksilver/tree/master/examples) //! and go through the tutorial modules [on docs.rs](https://docs.rs/quicksilver). If you have any //! questions, feel free to hop onto Gitter or open an issue. //! //! ## Building and Deploying a Quicksilver application //! //! Quicksilver should always compile and run on the latest stable version of Rust, for both web and //! desktop. //! //! Make sure to put all your assets in a top-level folder of your crate called `static/`. *All* //! Quicksilver file loading-APIs will expect paths that originate in the static folder, so //! `static/image.png` should be referenced as `image.png`. //! //! ### Linux dependencies //! //! On Windows and Mac, all you'll need to build Quicksilver is a recent stable version of `rustc` //! and `cargo`. A few of Quicksilver's dependencies require Linux packages to build, namely //! `libudev`, `zlib`, and `alsa`. To install these on Ubuntu or Debian, run the command //! `sudo apt install libudev-dev zlib1g-dev alsa libasound2-dev`. //! //! ### Deploying for desktop //! //! If you're deploying for desktop platforms, build in release mode (`cargo build --release`) //! and copy the executable file produced (found at "target/release/") and any assets you used //! (image files, etc.) and create an archive (on Windows a zip file, on Unix a tar file). You //! should be able to distribute this archive with no problems; if there are any, please open an //! issue. //! //! ### Deploying for the web //! //! If you're deploying for the web, first make sure you've //! [installed the cargo web tool](https://github.com/koute/cargo-web). Then use `cargo web deploy` //! to build your application for distribution (located at `target/deploy`). //! //! If you want to test your application locally, use `cargo web start` and open your favorite //! browser to the port it provides. //! //! ## Optional Features //! //! Quicksilver by default tries to provide all features a 2D application may need, but not all //! applications need these features. //! //! The optional features available are //! collision support (via [ncollide2d](https://github.com/sebcrozet/ncollide)), //! font support (via [rusttype](https://github.com/redox-os/rusttype)), //! gamepad support (via [gilrs](https://gitlab.com/gilrs-project/gilrs)), //! saving (via [serde_json](https://github.com/serde-rs/json)), //! complex shape / svg rendering (via [lyon](https://github.com/nical/lyon)), //! and sounds (via [rodio](https://github.com/tomaka/rodio)). //! //! Each are enabled by default, but you can //! [specify which features](https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#choosing-features) //! you actually want to use. //! //! ## Supported Platforms //! //! The engine is supported on Windows, macOS, Linux, and the web via WebAssembly. //! The web is only supported via the `wasm32-unknown-unknown` Rust target, not through emscripten. //! It might work with emscripten but this is not an ongoing guarantee. //! //! Mobile support would be a future possibility, but likely only through external contributions. #![doc(html_root_url = "https://docs.rs/quicksilver/0.3.19/quicksilver")] #![deny( bare_trait_objects, missing_docs, unused_extern_crates, unused_import_braces, unused_qualifications )] #[macro_use] extern crate serde_derive; #[cfg(target_arch = "wasm32")] #[macro_use] extern crate stdweb; mod backend; mod error; mod file; pub mod geom; pub mod graphics; pub mod input; pub mod lifecycle; pub mod prelude; #[cfg(feature = "saving")] pub mod saving; #[cfg(feature = "sounds")] pub mod sound; pub use crate::error::QuicksilverError as Error; pub use crate::file::load_file; #[cfg(feature = "lyon")] pub use lyon; pub mod tutorials; /// A Result that returns either success or a Quicksilver Error pub type Result<T> = ::std::result::Result<T, Error>; /// Types that represents a "future" computation, used to load assets pub use futures::Future; /// Helpers that allow chaining computations together in a single Future /// /// This allows one Asset object that contains all of the various resources /// an application needs to load. pub use futures::future as combinators;
39.937853
185
0.668553
d6827666eebb26ae3a5674279e210dec5fa22668
607
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(quad_precision_float)] static x: f128 = 1.0 + 2.0; fn foo(a: f128) -> f128 { a } pub fn main() { let y = x; foo(y); }
28.904762
68
0.69687
edfad2f1a99e47646e0b229c0de309407d54ebd6
949
use crate::core::{RpcRequest, RpcResponse}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct GetInflationRateRequest {} impl GetInflationRateRequest { pub fn new() -> Self { Self {} } } impl Into<serde_json::Value> for GetInflationRateRequest { fn into(self) -> serde_json::Value { serde_json::Value::Null } } impl Into<RpcRequest> for GetInflationRateRequest { fn into(self) -> RpcRequest { let mut request = RpcRequest::new("getInflationRate"); let params = self.into(); request.params(params).clone() } } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct GetInflationRateResponse { total: f64, validator: f64, foundation: f64, epoch: f64, } impl From<RpcResponse> for GetInflationRateResponse { fn from(response: RpcResponse) -> Self { serde_json::from_value(response.result).unwrap() } }
23.146341
62
0.667018
56acc86b795b0396a15426925b4d0624c97d2720
6,825
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use super::*; use crate::execution_step::air::call::call_result_setter::set_result_from_value; use crate::execution_step::CatchableError; use crate::execution_step::RSecurityTetraplet; use air_interpreter_data::CallResult; use air_interpreter_data::Sender; use air_interpreter_interface::CallServiceResult; use air_parser::ast::CallOutputValue; use air_trace_handler::TraceHandler; #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) struct StateDescriptor { should_execute: bool, prev_state: Option<CallResult>, } /// This function looks at the existing call state, validates it, /// and returns Ok(true) if the call should be executed further. pub(super) fn handle_prev_state<'i>( tetraplet: &RSecurityTetraplet, output: &CallOutputValue<'i>, prev_result: CallResult, trace_pos: usize, exec_ctx: &mut ExecutionCtx<'i>, trace_ctx: &mut TraceHandler, ) -> ExecutionResult<StateDescriptor> { use CallResult::*; match &prev_result { // this call was failed on one of the previous executions, // here it's needed to bubble this special error up CallServiceFailed(ret_code, err_msg) => { exec_ctx.subtree_complete = false; let ret_code = *ret_code; let err_msg = err_msg.clone(); trace_ctx.meet_call_end(prev_result); Err(CatchableError::LocalServiceError(ret_code, err_msg).into()) } RequestSentBy(Sender::PeerIdWithCallId { peer_id, call_id }) if peer_id.as_str() == exec_ctx.current_peer_id.as_str() => { // call results are identified by call_id that is saved in data match exec_ctx.call_results.remove(call_id) { Some(call_result) => { update_state_with_service_result(tetraplet, output, call_result, exec_ctx, trace_ctx)?; Ok(StateDescriptor::executed()) } // result hasn't been prepared yet None => { exec_ctx.subtree_complete = false; Ok(StateDescriptor::not_ready(prev_result)) } } } RequestSentBy(..) => { // check whether current node can execute this call let is_current_peer = tetraplet.borrow().peer_pk.as_str() == exec_ctx.current_peer_id.as_str(); if is_current_peer { return Ok(StateDescriptor::can_execute_now(prev_result)); } exec_ctx.subtree_complete = false; Ok(StateDescriptor::cant_execute_now(prev_result)) } // this instruction's been already executed Executed(value) => { set_result_from_value(value.clone(), tetraplet.clone(), trace_pos, output, exec_ctx)?; trace_ctx.meet_call_end(prev_result); Ok(StateDescriptor::executed()) } } } use super::call_result_setter::*; use crate::execution_step::ValueAggregate; use crate::JValue; fn update_state_with_service_result<'i>( tetraplet: &RSecurityTetraplet, output: &CallOutputValue<'i>, service_result: CallServiceResult, exec_ctx: &mut ExecutionCtx<'i>, trace_ctx: &mut TraceHandler, ) -> ExecutionResult<()> { // check that service call succeeded let service_result = handle_service_error(service_result, trace_ctx)?; // try to get service result from call service result let result = try_to_service_result(service_result, trace_ctx)?; let trace_pos = trace_ctx.trace_pos(); let executed_result = ValueAggregate::new(result, tetraplet.clone(), trace_pos); let new_call_result = set_local_result(executed_result, output, exec_ctx)?; trace_ctx.meet_call_end(new_call_result); Ok(()) } fn handle_service_error( service_result: CallServiceResult, trace_ctx: &mut TraceHandler, ) -> ExecutionResult<CallServiceResult> { use air_interpreter_interface::CALL_SERVICE_SUCCESS; use CallResult::CallServiceFailed; if service_result.ret_code == CALL_SERVICE_SUCCESS { return Ok(service_result); } let error_message = Rc::new(service_result.result); let error = CatchableError::LocalServiceError(service_result.ret_code, error_message.clone()); trace_ctx.meet_call_end(CallServiceFailed(service_result.ret_code, error_message)); Err(error.into()) } fn try_to_service_result( service_result: CallServiceResult, trace_ctx: &mut TraceHandler, ) -> ExecutionResult<Rc<JValue>> { use CallResult::CallServiceFailed; match serde_json::from_str(&service_result.result) { Ok(result) => Ok(Rc::new(result)), Err(e) => { let error_msg = format!( "call_service result '{0}' can't be serialized or deserialized with an error: {1}", service_result.result, e ); let error_msg = Rc::new(error_msg); let error = CallServiceFailed(i32::MAX, error_msg.clone()); trace_ctx.meet_call_end(error); Err(CatchableError::LocalServiceError(i32::MAX, error_msg).into()) } } } impl StateDescriptor { pub(crate) fn executed() -> Self { Self { should_execute: false, prev_state: None, } } pub(crate) fn not_ready(prev_state: CallResult) -> Self { Self { should_execute: false, prev_state: Some(prev_state), } } pub(crate) fn can_execute_now(prev_state: CallResult) -> Self { Self { should_execute: true, prev_state: Some(prev_state), } } pub(crate) fn cant_execute_now(prev_state: CallResult) -> Self { Self { should_execute: false, prev_state: Some(prev_state), } } pub(crate) fn no_previous_state() -> Self { Self { should_execute: true, prev_state: None, } } pub(crate) fn should_execute(&self) -> bool { self.should_execute } pub(crate) fn maybe_set_prev_state(self, trace_ctx: &mut TraceHandler) { if let Some(call_result) = self.prev_state { trace_ctx.meet_call_end(call_result); } } }
33.292683
107
0.65011
cc420b6bba75535f598f581e277a558809bb3e36
4,959
use crate::entry::Topic; use crate::net::NTSocket; use crate::server::ServerMessage; use async_std::sync::Sender; use async_std::task; use futures::prelude::*; use futures::stream::{SplitSink, SplitStream}; use log::*; use proto::prelude::directory::{Announce, Unannounce}; use proto::prelude::subscription::{Subscribe, Unsubscribe}; use proto::prelude::{NTMessage, NTValue}; use std::collections::HashMap; #[derive(Clone, Debug)] pub struct Subscription { pub prefixes: Vec<String>, pub immediate: bool, pub periodic: f64, pub logging: bool, } #[derive(PartialEq, Clone, Debug)] pub struct TopicSnapshot { pub name: String, pub value: NTValue, pub timestamp: u64, } pub struct ConnectedClient { net_tx: SplitSink<NTSocket, NTMessage>, pub subs: HashMap<u32, Subscription>, pub sub_loop_channels: HashMap<u32, Sender<()>>, pub pub_ids: HashMap<String, i32>, pub pubs: Vec<String>, pub queued_updates: Vec<TopicSnapshot>, next_pub_id: i32, } /// A loop over the read-half of a connected peer /// /// This loop continuously reads from the stream, forwarding applicable messages and reporting errors where applicable /// /// When the stream is closed it notifies the server with [`ServerMessage::ClientDisconnected`] and is terminated. /// /// [`ServerMessage::ClientDisconnected`]: ../server/enum.ServerMessage.html#variant.ClientDisconnected async fn client_loop( mut rx: SplitStream<NTSocket>, tx: Sender<ServerMessage>, cid: u32, ) -> anyhow::Result<()> { while let Some(packet) = rx.next().await { match packet { Ok(msg) => match msg { NTMessage::Text(msg) => tx.send(ServerMessage::ControlMessage(msg, cid)).await, NTMessage::Binary(msgs) => tx.send(ServerMessage::ValuePublish(msgs, cid)).await, NTMessage::Close => { tx.send(ServerMessage::ClientDisconnected(cid)).await; return Ok(()); } }, Err(e) => error!("Encountered error decoding frame from client: {}", e), } } log::info!("Client loop for CID {} terminated", cid); tx.send(ServerMessage::ClientDisconnected(cid)).await; Ok(()) } impl ConnectedClient { pub fn new(sock: NTSocket, server_tx: Sender<ServerMessage>, cid: u32) -> ConnectedClient { let (net_tx, net_rx) = sock.split(); task::spawn(client_loop(net_rx, server_tx, cid)); ConnectedClient { net_tx, subs: HashMap::new(), sub_loop_channels: HashMap::new(), pub_ids: HashMap::new(), queued_updates: Vec::new(), next_pub_id: 1, pubs: Vec::new(), } } pub fn subscribed_to(&self, name: &str) -> bool { self.subs .values() .any(|sub| sub.prefixes.iter().any(|prefix| name.starts_with(prefix))) } pub fn subscription(&self, name: &str) -> Option<&Subscription> { self.subs .values() .find(|sub| sub.prefixes.iter().any(|prefix| name.starts_with(prefix))) } pub fn announce(&mut self, entry: &Topic) -> Announce { let id = self.next_pub_id; self.next_pub_id += 1; self.pub_ids.insert(entry.name.clone(), id); Announce { name: entry.name.clone(), id, _type: entry.entry_type(), flags: entry.flags.clone(), } } pub fn unannounce(&mut self, entry: &Topic) -> Unannounce { let id = self.pub_ids.remove(&entry.name).unwrap(); Unannounce { name: entry.name.clone(), id, } } pub fn id_to_name(&self, id: i32) -> Option<&String> { self.pub_ids .iter() .find(|(_, pub_id)| **pub_id == id) .map(|(name, _)| name) } pub fn lookup_id(&self, name: &str) -> Option<i32> { self.pub_ids.get(name).map(|id| *id) } pub fn subscribe(&mut self, packet: Subscribe) -> Subscription { let mut sub = Subscription { prefixes: packet.prefixes, immediate: false, periodic: 0.1, logging: false, }; if let Some(opts) = packet.options { sub.immediate = opts.immediate; sub.logging = opts.logging; sub.periodic = opts.periodic; } self.subs.insert(packet.subuid, sub.clone()); sub } pub fn subscribe_channel(&mut self, subuid: u32, ch: Sender<()>) { self.sub_loop_channels.insert(subuid, ch); } pub async fn unsubscribe(&mut self, packet: Unsubscribe) { self.subs.remove(&packet.subuid); if let Some(ch) = self.sub_loop_channels.remove(&packet.subuid) { ch.send(()).await; } } pub async fn send_message(&mut self, msg: NTMessage) { let _ = self.net_tx.send(msg).await; } }
30.237805
118
0.587618
227339646b4dcd931415ba5017def60d5c47bcfd
2,265
// This file is part of cc-queue. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/cc-queue/master/COPYRIGHT. No part of predicator, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2017 The developers of cc-queue. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/cc-queue/master/COPYRIGHT. #[derive(Debug)] #[repr(C)] struct SynchNode<T> { next: AtomicPtr<SynchNode<T>>, // TODO: Make 64-byte cache-line aligned data: *mut (), status: AtomicU32, // TODO: Make 64-byte cache-line aligned } impl<T> Drop for SynchNode<T> { #[inline(always)] fn drop(&mut self) { let next = self.acquire_next(); if next.is_not_null() { unsafe { drop_in_place(next) }; Self::free_after_drop(unsafe { NonNull::new_unchecked(next) }) } } } impl<T> SynchNode<T> { #[inline(always)] fn free_after_drop(this: NonNull<Self>) { HeapAllocator.free_cache_line_size(this) } #[inline(always)] unsafe fn ccsynch_init_node() -> NonNull<Self> { let mut node = HeapAllocator.align_malloc_cache_line_size(); { let node: &mut Self = node.as_mut(); write(&mut node.next, AtomicPtr::new(null_mut())); // Not strictly required as will be overwritten always. write(&mut node.data, null_mut()); write(&mut node.status, AtomicU32::new(Status::READY as u32)); } node } // Result can be null #[inline(always)] fn acquire_next(&self) -> *mut SynchNode<T> { self.next.load(Acquire) } #[inline(always)] fn release_next(&mut self, next: NonNull<SynchNode<T>>) { self.next.store(next.as_ptr(), Release) } #[inline(always)] fn acquire_status(&self) -> Status { unsafe { transmute(self.status.load(Acquire)) } } #[inline(always)] fn release_status_done(&mut self) { self.release_status(Status::DONE); } #[inline(always)] fn release_status_ready(&mut self) { self.release_status(Status::READY); } #[inline(always)] fn release_status(&mut self, status: Status) { self.status.store(status as u32, Release); } }
25.166667
381
0.700662
ff73d7178ce757bbc63c565ffb4373654d6d6b40
6,617
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. use std::fs::File; use std::io::{BufWriter, Write}; use datafusion::prelude::ExecutionConfig; use log::info; use crate::app::datafusion::context::{Context, QueryResults}; use crate::app::editor::Editor; use crate::app::error::Result; use crate::app::handlers::key_event_handler; use crate::cli::args::Args; use crate::events::Key; const DATAFUSION_RC: &str = ".datafusion/.datafusionrc"; pub struct Tabs { pub titles: Vec<&'static str>, pub index: usize, } #[derive(Debug, Copy, Eq, PartialEq, Clone)] pub enum TabItem { Editor, QueryHistory, Context, Logs, } impl Default for TabItem { fn default() -> TabItem { TabItem::Editor } } impl TabItem { pub(crate) fn all_values() -> Vec<TabItem> { vec![ TabItem::Editor, TabItem::QueryHistory, TabItem::Context, TabItem::Logs, ] } pub(crate) fn list_index(&self) -> usize { return TabItem::all_values() .iter() .position(|x| x == self) .unwrap(); } pub(crate) fn title_with_key(&self) -> String { return format!("{} [{}]", self.title(), self.list_index() + 1); } pub(crate) fn title(&self) -> &'static str { match self { TabItem::Editor => "SQL Editor", TabItem::QueryHistory => "Query History", TabItem::Context => "Context", TabItem::Logs => "Logs", } } } impl TryFrom<char> for TabItem { type Error = String; fn try_from(value: char) -> std::result::Result<Self, Self::Error> { match value { '1' => Ok(TabItem::Editor), '2' => Ok(TabItem::QueryHistory), '3' => Ok(TabItem::Context), '4' => Ok(TabItem::Logs), i => Err(format!( "Invalid tab index: {}, valid range is [1..={}]", i, 4 )), } } } impl From<TabItem> for usize { fn from(item: TabItem) -> Self { match item { TabItem::Editor => 1, TabItem::QueryHistory => 2, TabItem::Context => 3, TabItem::Logs => 4, } } } #[derive(Debug, Copy, Clone)] pub enum InputMode { Normal, Editing, Rc, } impl Default for InputMode { fn default() -> InputMode { InputMode::Normal } } /// Status that determines whether app should continue or exit #[derive(PartialEq)] pub enum AppReturn { Continue, Exit, } /// App holds the state of the application pub struct App { /// Application tabs pub tab_item: TabItem, /// Current input mode pub input_mode: InputMode, /// SQL Editor and it's state pub editor: Editor, /// DataFusion `ExecutionContext` pub context: Context, /// Results from DataFusion query pub query_results: Option<QueryResults>, } impl App { pub async fn new(args: Args) -> App { let execution_config = ExecutionConfig::new().with_information_schema(true); let mut ctx: Context = match (args.host, args.port) { (Some(ref h), Some(p)) => Context::new_remote(h, p).unwrap(), _ => Context::new_local(&execution_config).await, }; let files = args.file; let rc = App::get_rc_files(args.rc); if !files.is_empty() { ctx.exec_files(files).await } else if !rc.is_empty() { info!("Executing '~/.datafusion/.datafusionrc' file"); ctx.exec_files(rc).await } App { tab_item: Default::default(), input_mode: Default::default(), editor: Editor::default(), context: ctx, query_results: None, } } fn get_rc_files(rc: Option<Vec<String>>) -> Vec<String> { match rc { Some(file) => file, None => { let mut files = Vec::new(); let home = dirs::home_dir(); if let Some(p) = home { let home_rc = p.join(DATAFUSION_RC); if home_rc.exists() { files.push(home_rc.into_os_string().into_string().unwrap()); } } files } } } pub async fn reload_rc(&mut self) { let rc = App::get_rc_files(None); self.context.exec_files(rc).await; info!("Reloaded .datafusionrc"); } pub fn write_rc(&self) -> Result<()> { let text = self.editor.input.combine_lines(); let rc = App::get_rc_files(None); let file = File::create(rc[0].clone())?; let mut writer = BufWriter::new(file); writer.write_all(text.as_bytes())?; Ok(()) } pub async fn key_handler(&mut self, key: Key) -> AppReturn { key_event_handler(self, key).await.unwrap() } pub fn update_on_tick(&mut self) -> AppReturn { AppReturn::Continue } } #[cfg(test)] mod test { use super::*; #[test] fn test_tab_item_from_char() { assert!(TabItem::try_from('0').is_err()); assert_eq!(TabItem::Editor, TabItem::try_from('1').unwrap()); assert_eq!(TabItem::QueryHistory, TabItem::try_from('2').unwrap()); assert_eq!(TabItem::Context, TabItem::try_from('3').unwrap()); assert_eq!(TabItem::Logs, TabItem::try_from('4').unwrap()); assert!(TabItem::try_from('5').is_err()); } #[test] fn test_tab_item_to_usize() { (0_usize..TabItem::all_values().len()).for_each(|i| { assert_eq!( TabItem::all_values()[i], TabItem::try_from(format!("{}", i + 1).chars().next().unwrap()).unwrap() ); assert_eq!(TabItem::all_values()[i].list_index(), i); }); } }
27.686192
88
0.564153
7af1e5a8cc924f77a3f29fdddd8bdd424f8ec079
20,906
//! Support for symbolication using the `gimli` crate on crates.io //! //! This implementation is largely a work in progress and is off by default for //! all platforms, but it's hoped to be developed over time! Long-term this is //! intended to wholesale replace the `libbacktrace.rs` implementation. use self::gimli::read::EndianSlice; use self::gimli::LittleEndian as Endian; use crate::symbolize::dladdr; use crate::symbolize::ResolveWhat; use crate::types::BytesOrWideString; use crate::SymbolName; use addr2line::gimli; use core::convert::TryFrom; use core::mem; use core::u32; use findshlibs::{self, Segment, SharedLibrary}; use libc::c_void; use memmap::Mmap; use std::env; use std::fs::File; use std::path::{Path, PathBuf}; use std::prelude::v1::*; const MAPPINGS_CACHE_SIZE: usize = 4; struct Context<'a> { dwarf: addr2line::Context<EndianSlice<'a, Endian>>, object: Object<'a>, } struct Mapping { // 'static lifetime is a lie to hack around lack of support for self-referential structs. cx: Context<'static>, _map: Mmap, } fn cx<'data>(object: Object<'data>) -> Option<Context<'data>> { fn load_section<'data, S>(obj: &Object<'data>) -> S where S: gimli::Section<gimli::EndianSlice<'data, Endian>>, { let data = obj.section(S::section_name()).unwrap_or(&[]); S::from(EndianSlice::new(data, Endian)) } let dwarf = addr2line::Context::from_sections( load_section(&object), load_section(&object), load_section(&object), load_section(&object), load_section(&object), load_section(&object), load_section(&object), load_section(&object), load_section(&object), gimli::EndianSlice::new(&[], Endian), ) .ok()?; Some(Context { dwarf, object }) } fn assert_lifetimes<'a>(_: &'a Mmap, _: &Context<'a>) {} macro_rules! mk { (Mapping { $map:expr, $inner:expr }) => {{ assert_lifetimes(&$map, &$inner); Mapping { // Convert to 'static lifetimes since the symbols should // only borrow `map` and we're preserving `map` below. cx: unsafe { mem::transmute::<Context<'_>, Context<'static>>($inner) }, _map: $map, } }}; } fn mmap(path: &Path) -> Option<Mmap> { let file = File::open(path).ok()?; // TODO: not completely safe, see https://github.com/danburkert/memmap-rs/issues/25 unsafe { Mmap::map(&file).ok() } } cfg_if::cfg_if! { if #[cfg(windows)] { use std::cmp; use goblin::pe::{self, PE}; use goblin::strtab::Strtab; struct Object<'a> { pe: PE<'a>, data: &'a [u8], symbols: Vec<(usize, pe::symbol::Symbol)>, strtab: Strtab<'a>, } impl<'a> Object<'a> { fn parse(data: &'a [u8]) -> Option<Object<'a>> { let pe = PE::parse(data).ok()?; let syms = pe.header.coff_header.symbols(data).ok()?; let strtab = pe.header.coff_header.strings(data).ok()?; // Collect all the symbols into a local vector which is sorted // by address and contains enough data to learn about the symbol // name. Note that we only look at function symbols and also // note that the sections are 1-indexed because the zero section // is special (apparently). let mut symbols = Vec::new(); for (_, _, sym) in syms.iter() { if sym.derived_type() != pe::symbol::IMAGE_SYM_DTYPE_FUNCTION || sym.section_number == 0 { continue; } let addr = usize::try_from(sym.value).ok()?; let section = pe.sections.get(usize::try_from(sym.section_number).ok()? - 1)?; let va = usize::try_from(section.virtual_address).ok()?; symbols.push((addr + va + pe.image_base, sym)); } symbols.sort_unstable_by_key(|x| x.0); Some(Object { pe, data, symbols, strtab }) } fn section(&self, name: &str) -> Option<&'a [u8]> { let section = self.pe .sections .iter() .find(|section| section.name().ok() == Some(name)); section .and_then(|section| { let offset = section.pointer_to_raw_data as usize; let size = cmp::min(section.virtual_size, section.size_of_raw_data) as usize; self.data.get(offset..).and_then(|data| data.get(..size)) }) } fn search_symtab<'b>(&'b self, addr: u64) -> Option<&'b [u8]> { // Note that unlike other formats COFF doesn't embed the size of // each symbol. As a last ditch effort search for the *closest* // symbol to a particular address and return that one. This gets // really wonky once symbols start getting removed because the // symbols returned here can be totally incorrect, but we have // no idea of knowing how to detect that. let addr = usize::try_from(addr).ok()?; let i = match self.symbols.binary_search_by_key(&addr, |p| p.0) { Ok(i) => i, // typically `addr` isn't in the array, but `i` is where // we'd insert it, so the previous position must be the // greatest less than `addr` Err(i) => i.checked_sub(1)?, }; Some(self.symbols[i].1.name(&self.strtab).ok()?.as_bytes()) } } } else if #[cfg(target_os = "macos")] { use goblin::mach::MachO; struct Object<'a> { macho: MachO<'a>, dwarf: Option<usize>, } impl<'a> Object<'a> { fn parse(macho: MachO<'a>) -> Option<Object<'a>> { if !macho.little_endian { return None; } let dwarf = macho .segments .iter() .enumerate() .find(|(_, segment)| segment.name().ok() == Some("__DWARF")) .map(|p| p.0); Some(Object { macho, dwarf }) } fn section(&self, name: &str) -> Option<&'a [u8]> { let dwarf = self.dwarf?; let dwarf = &self.macho.segments[dwarf]; dwarf .into_iter() .filter_map(|s| s.ok()) .find(|(section, _data)| { let section_name = match section.name() { Ok(s) => s, Err(_) => return false, }; &section_name[..] == name || { section_name.starts_with("__") && name.starts_with(".") && &section_name[2..] == &name[1..] } }) .map(|p| p.1) } fn search_symtab<'b>(&'b self, _addr: u64) -> Option<&'b [u8]> { // So far it seems that we don't need to implement this. Maybe // `dladdr` on OSX has us covered? Maybe there's not much in the // symbol table? In any case our relevant tests are passing // without this being implemented, so let's skip it for now. None } } } else { use goblin::elf::Elf; struct Object<'a> { elf: Elf<'a>, data: &'a [u8], } impl<'a> Object<'a> { fn parse(data: &'a [u8]) -> Option<Object<'a>> { let elf = Elf::parse(data).ok()?; if !elf.little_endian { return None; } Some(Object { elf, data }) } fn section(&self, name: &str) -> Option<&'a [u8]> { let section = self.elf.section_headers.iter().find(|section| { match self.elf.shdr_strtab.get(section.sh_name) { Some(Ok(section_name)) => section_name == name, _ => false, } }); section .and_then(|section| { self.data.get(section.sh_offset as usize..) .and_then(|data| data.get(..section.sh_size as usize)) }) } fn search_symtab<'b>(&'b self, addr: u64) -> Option<&'b [u8]> { let sym = self.elf.syms.iter() .find(|sym| sym.st_value <= addr && addr <= sym.st_value + sym.st_size)?; Some(self.elf.strtab.get(sym.st_name)?.ok()?.as_bytes()) } } } } impl Mapping { #[cfg(not(target_os = "macos"))] fn new(path: &Path) -> Option<Mapping> { let map = mmap(path)?; let cx = cx(Object::parse(&map)?)?; Some(mk!(Mapping { map, cx })) } // The loading path for OSX is is so different we just have a completely // different implementation of the function here. On OSX we need to go // probing the filesystem for a bunch of files. #[cfg(target_os = "macos")] fn new(path: &Path) -> Option<Mapping> { // First up we need to load the unique UUID which is stored in the macho // header of the file we're reading, specified at `path`. let map = mmap(path)?; let macho = MachO::parse(&map, 0).ok()?; let uuid = find_uuid(&macho)?; // Next we need to look for a `*.dSYM` file. For now we just probe the // containing directory and look around for something that matches // `*.dSYM`. Once it's found we root through the dwarf resources that it // contains and try to find a macho file which has a matching UUID as // the one of our own file. If we find a match that's the dwarf file we // want to return. let parent = path.parent()?; for entry in parent.read_dir().ok()? { let entry = entry.ok()?; let filename = match entry.file_name().into_string() { Ok(name) => name, Err(_) => continue, }; if !filename.ends_with(".dSYM") { continue; } let candidates = entry.path().join("Contents/Resources/DWARF"); if let Some(mapping) = load_dsym(&candidates, &uuid) { return Some(mapping); } } // Looks like nothing matched our UUID, so let's at least return our own // file. This should have the symbol table for at least some // symbolication purposes. let inner = cx(Object::parse(macho)?)?; return Some(mk!(Mapping { map, inner })); fn load_dsym(dir: &Path, uuid: &[u8; 16]) -> Option<Mapping> { for entry in dir.read_dir().ok()? { let entry = entry.ok()?; let map = mmap(&entry.path())?; let macho = MachO::parse(&map, 0).ok()?; let entry_uuid = find_uuid(&macho)?; if entry_uuid != uuid { continue; } if let Some(cx) = Object::parse(macho).and_then(cx) { return Some(mk!(Mapping { map, cx })); } } None } fn find_uuid<'a>(object: &'a MachO) -> Option<&'a [u8; 16]> { use goblin::mach::load_command::CommandVariant; object .load_commands .iter() .filter_map(|cmd| match &cmd.command { CommandVariant::Uuid(u) => Some(&u.uuid), _ => None, }) .next() } } // Ensure the 'static lifetimes don't leak. fn rent<F>(&self, mut f: F) where F: FnMut(&Context<'_>), { f(&self.cx) } } type Cache = Vec<(PathBuf, Mapping)>; // unsafe because this is required to be externally synchronized unsafe fn with_cache(f: impl FnOnce(&mut Cache)) { // A very small, very simple LRU cache for debug info mappings. // // The hit rate should be very high, since the typical stack doesn't cross // between many shared libraries. // // The `addr2line::Context` structures are pretty expensive to create. Its // cost is expected to be amortized by subsequent `locate` queries, which // leverage the structures built when constructing `addr2line::Context`s to // get nice speedups. If we didn't have this cache, that amortization would // never happen, and symbolicating backtraces would be ssssllllooooowwww. static mut MAPPINGS_CACHE: Option<Cache> = None; f(MAPPINGS_CACHE.get_or_insert_with(|| Vec::with_capacity(MAPPINGS_CACHE_SIZE))) } // unsafe because this is required to be externally synchronized pub unsafe fn clear_symbol_cache() { with_cache(|cache| cache.clear()); } unsafe fn with_mapping_for_path<F>(path: PathBuf, f: F) where F: FnMut(&Context<'_>), { with_cache(|cache| { let idx = cache.iter().position(|&(ref p, _)| p == &path); // Invariant: after this conditional completes without early returning // from an error, the cache entry for this path is at index 0. if let Some(idx) = idx { // When the mapping is already in the cache, move it to the front. if idx != 0 { let entry = cache.remove(idx); cache.insert(0, entry); } } else { // When the mapping is not in the cache, create a new mapping, // insert it into the front of the cache, and evict the oldest cache // entry if necessary. let mapping = match Mapping::new(&path) { None => return, Some(m) => m, }; if cache.len() == MAPPINGS_CACHE_SIZE { cache.pop(); } cache.insert(0, (path, mapping)); } cache[0].1.rent(f); }); } pub unsafe fn resolve(what: ResolveWhat, cb: &mut FnMut(&super::Symbol)) { let addr = what.address_or_ip(); let mut cb = DladdrFallback { cb, addr, called: false, }; // First, find the file containing the segment that the given AVMA (after // relocation) address falls within. Use the containing segment to compute // the SVMA (before relocation) address. // // Note that the OS APIs that `SharedLibrary::each` is implemented with hold // a lock for the duration of the `each` call, so we want to keep this // section as short as possible to avoid contention with other threads // capturing backtraces. // // Also note that for now `findshlibs` is unimplemented on Windows, so we // just unhelpfully assume that the address is an SVMA. Surprisingly it // seems to at least somewhat work on Wine on Linux though... let (addr, path) = if cfg!(windows) { let addr = findshlibs::Svma(addr as *mut u8 as *const u8); (addr, String::new()) } else { let addr = findshlibs::Avma(addr as *mut u8 as *const u8); let mut so_info = None; findshlibs::TargetSharedLibrary::each(|so| { use findshlibs::IterationControl::*; for segment in so.segments() { if segment.contains_avma(so, addr) { let addr = so.avma_to_svma(addr); let path = so.name().to_string_lossy(); so_info = Some((addr, path.to_string())); return Break; } } Continue }); match so_info { None => return, Some((a, p)) => (a, p), } }; // Second, fixup the path. Empty path means that this address falls within // the main executable, not a shared library. let path = if path.is_empty() { match env::current_exe() { Err(_) => return, Ok(p) => p, } } else { PathBuf::from(path) }; // Finally, get a cached mapping or create a new mapping for this file, and // evaluate the DWARF info to find the file/line/name for this address. with_mapping_for_path(path, |cx| { let mut called = false; if let Ok(mut frames) = cx.dwarf.find_frames(addr.0 as u64) { while let Ok(Some(mut frame)) = frames.next() { let function = frame.function.take(); let name = function.as_ref().and_then(|f| f.raw_name().ok()); let name = name.as_ref().map(|n| n.as_bytes()); called = true; cb.call(Symbol::Frame { addr: addr.0 as *mut c_void, frame, name, }); } } if !called { if let Some(name) = cx.object.search_symtab(addr.0 as u64) { cb.call(Symbol::Symtab { addr: addr.0 as *mut c_void, name, }); } } }); drop(cb); } struct DladdrFallback<'a, 'b> { addr: *mut c_void, called: bool, cb: &'a mut (FnMut(&super::Symbol) + 'b), } impl DladdrFallback<'_, '_> { fn call(&mut self, sym: Symbol) { self.called = true; // Extend the lifetime of `sym` to `'static` since we are unfortunately // required to here, but it's ony ever going out as a reference so no // reference to it should be persisted beyond this frame anyway. let sym = unsafe { mem::transmute::<Symbol, Symbol<'static>>(sym) }; (self.cb)(&super::Symbol { inner: sym }); } } impl Drop for DladdrFallback<'_, '_> { fn drop(&mut self) { if self.called { return; } unsafe { dladdr::resolve(self.addr, &mut |sym| { (self.cb)(&super::Symbol { inner: Symbol::Dladdr(sym), }) }); } } } pub enum Symbol<'a> { /// We were able to locate frame information for this symbol, and /// `addr2line`'s frame internally has all the nitty gritty details. Frame { addr: *mut c_void, frame: addr2line::Frame<EndianSlice<'a, Endian>>, name: Option<&'a [u8]>, }, /// Couldn't find debug information, but we found it in the symbol table of /// the elf executable. Symtab { addr: *mut c_void, name: &'a [u8] }, /// We weren't able to find anything in the original file, so we had to fall /// back to using `dladdr` which had a hit. Dladdr(dladdr::Symbol<'a>), } impl Symbol<'_> { pub fn name(&self) -> Option<SymbolName> { match self { Symbol::Dladdr(s) => s.name(), Symbol::Frame { name, .. } => { let name = name.as_ref()?; Some(SymbolName::new(name)) } Symbol::Symtab { name, .. } => Some(SymbolName::new(name)), } } pub fn addr(&self) -> Option<*mut c_void> { match self { Symbol::Dladdr(s) => s.addr(), Symbol::Frame { addr, .. } => Some(*addr), Symbol::Symtab { .. } => None, } } pub fn filename_raw(&self) -> Option<BytesOrWideString> { match self { Symbol::Dladdr(s) => return s.filename_raw(), Symbol::Frame { frame, .. } => { let location = frame.location.as_ref()?; let file = location.file.as_ref()?; Some(BytesOrWideString::Bytes(file.as_bytes())) } Symbol::Symtab { .. } => None, } } pub fn filename(&self) -> Option<&Path> { match self { Symbol::Dladdr(s) => return s.filename(), Symbol::Frame { frame, .. } => { let location = frame.location.as_ref()?; let file = location.file.as_ref()?; Some(Path::new(file)) } Symbol::Symtab { .. } => None, } } pub fn lineno(&self) -> Option<u32> { match self { Symbol::Dladdr(s) => return s.lineno(), Symbol::Frame { frame, .. } => { let location = frame.location.as_ref()?; location.line.and_then(|l| u32::try_from(l).ok()) } Symbol::Symtab { .. } => None, } } }
35.859348
101
0.511576
11202abe480e9fbba24a8a05ee33742e19d5aad1
13,181
#[doc = "Register `GPIO_QSPI_SCLK` reader"] pub struct R(crate::R<GPIO_QSPI_SCLK_SPEC>); impl core::ops::Deref for R { type Target = crate::R<GPIO_QSPI_SCLK_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<GPIO_QSPI_SCLK_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<GPIO_QSPI_SCLK_SPEC>) -> Self { R(reader) } } #[doc = "Register `GPIO_QSPI_SCLK` writer"] pub struct W(crate::W<GPIO_QSPI_SCLK_SPEC>); impl core::ops::Deref for W { type Target = crate::W<GPIO_QSPI_SCLK_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_QSPI_SCLK_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<GPIO_QSPI_SCLK_SPEC>) -> Self { W(writer) } } #[doc = "Field `OD` reader - Output disable. Has priority over output enable from peripherals"] pub struct OD_R(crate::FieldReader<bool, bool>); impl OD_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { OD_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for OD_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `OD` writer - Output disable. Has priority over output enable from peripherals"] pub struct OD_W<'a> { w: &'a mut W, } impl<'a> OD_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 `IE` reader - Input enable"] pub struct IE_R(crate::FieldReader<bool, bool>); impl IE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { IE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for IE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `IE` writer - Input enable"] pub struct IE_W<'a> { w: &'a mut W, } impl<'a> 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 << 6)) | ((value as u32 & 0x01) << 6); self.w } } #[doc = "Drive strength. Value on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum DRIVE_A { #[doc = "0: `0`"] _2MA = 0, #[doc = "1: `1`"] _4MA = 1, #[doc = "2: `10`"] _8MA = 2, #[doc = "3: `11`"] _12MA = 3, } impl From<DRIVE_A> for u8 { #[inline(always)] fn from(variant: DRIVE_A) -> Self { variant as _ } } #[doc = "Field `DRIVE` reader - Drive strength."] pub struct DRIVE_R(crate::FieldReader<u8, DRIVE_A>); impl DRIVE_R { #[inline(always)] pub(crate) fn new(bits: u8) -> Self { DRIVE_R(crate::FieldReader::new(bits)) } #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DRIVE_A { match self.bits { 0 => DRIVE_A::_2MA, 1 => DRIVE_A::_4MA, 2 => DRIVE_A::_8MA, 3 => DRIVE_A::_12MA, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_2MA`"] #[inline(always)] pub fn is_2m_a(&self) -> bool { **self == DRIVE_A::_2MA } #[doc = "Checks if the value of the field is `_4MA`"] #[inline(always)] pub fn is_4m_a(&self) -> bool { **self == DRIVE_A::_4MA } #[doc = "Checks if the value of the field is `_8MA`"] #[inline(always)] pub fn is_8m_a(&self) -> bool { **self == DRIVE_A::_8MA } #[doc = "Checks if the value of the field is `_12MA`"] #[inline(always)] pub fn is_12m_a(&self) -> bool { **self == DRIVE_A::_12MA } } impl core::ops::Deref for DRIVE_R { type Target = crate::FieldReader<u8, DRIVE_A>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `DRIVE` writer - Drive strength."] pub struct DRIVE_W<'a> { w: &'a mut W, } impl<'a> DRIVE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DRIVE_A) -> &'a mut W { self.bits(variant.into()) } #[doc = "`0`"] #[inline(always)] pub fn _2m_a(self) -> &'a mut W { self.variant(DRIVE_A::_2MA) } #[doc = "`1`"] #[inline(always)] pub fn _4m_a(self) -> &'a mut W { self.variant(DRIVE_A::_4MA) } #[doc = "`10`"] #[inline(always)] pub fn _8m_a(self) -> &'a mut W { self.variant(DRIVE_A::_8MA) } #[doc = "`11`"] #[inline(always)] pub fn _12m_a(self) -> &'a mut W { self.variant(DRIVE_A::_12MA) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 4)) | ((value as u32 & 0x03) << 4); self.w } } #[doc = "Field `PUE` reader - Pull up enable"] pub struct PUE_R(crate::FieldReader<bool, bool>); impl PUE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { PUE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PUE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PUE` writer - Pull up enable"] pub struct PUE_W<'a> { w: &'a mut W, } impl<'a> PUE_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 `PDE` reader - Pull down enable"] pub struct PDE_R(crate::FieldReader<bool, bool>); impl PDE_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { PDE_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PDE_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PDE` writer - Pull down enable"] pub struct PDE_W<'a> { w: &'a mut W, } impl<'a> PDE_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 `SCHMITT` reader - Enable schmitt trigger"] pub struct SCHMITT_R(crate::FieldReader<bool, bool>); impl SCHMITT_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { SCHMITT_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SCHMITT_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SCHMITT` writer - Enable schmitt trigger"] pub struct SCHMITT_W<'a> { w: &'a mut W, } impl<'a> SCHMITT_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 `SLEWFAST` reader - Slew rate control. 1 = Fast, 0 = Slow"] pub struct SLEWFAST_R(crate::FieldReader<bool, bool>); impl SLEWFAST_R { #[inline(always)] pub(crate) fn new(bits: bool) -> Self { SLEWFAST_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for SLEWFAST_R { type Target = crate::FieldReader<bool, bool>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `SLEWFAST` writer - Slew rate control. 1 = Fast, 0 = Slow"] pub struct SLEWFAST_W<'a> { w: &'a mut W, } impl<'a> SLEWFAST_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 } } impl R { #[doc = "Bit 7 - Output disable. Has priority over output enable from peripherals"] #[inline(always)] pub fn od(&self) -> OD_R { OD_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - Input enable"] #[inline(always)] pub fn ie(&self) -> IE_R { IE_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bits 4:5 - Drive strength."] #[inline(always)] pub fn drive(&self) -> DRIVE_R { DRIVE_R::new(((self.bits >> 4) & 0x03) as u8) } #[doc = "Bit 3 - Pull up enable"] #[inline(always)] pub fn pue(&self) -> PUE_R { PUE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Pull down enable"] #[inline(always)] pub fn pde(&self) -> PDE_R { PDE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Enable schmitt trigger"] #[inline(always)] pub fn schmitt(&self) -> SCHMITT_R { SCHMITT_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Slew rate control. 1 = Fast, 0 = Slow"] #[inline(always)] pub fn slewfast(&self) -> SLEWFAST_R { SLEWFAST_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 7 - Output disable. Has priority over output enable from peripherals"] #[inline(always)] pub fn od(&mut self) -> OD_W { OD_W { w: self } } #[doc = "Bit 6 - Input enable"] #[inline(always)] pub fn ie(&mut self) -> IE_W { IE_W { w: self } } #[doc = "Bits 4:5 - Drive strength."] #[inline(always)] pub fn drive(&mut self) -> DRIVE_W { DRIVE_W { w: self } } #[doc = "Bit 3 - Pull up enable"] #[inline(always)] pub fn pue(&mut self) -> PUE_W { PUE_W { w: self } } #[doc = "Bit 2 - Pull down enable"] #[inline(always)] pub fn pde(&mut self) -> PDE_W { PDE_W { w: self } } #[doc = "Bit 1 - Enable schmitt trigger"] #[inline(always)] pub fn schmitt(&mut self) -> SCHMITT_W { SCHMITT_W { w: self } } #[doc = "Bit 0 - Slew rate control. 1 = Fast, 0 = Slow"] #[inline(always)] pub fn slewfast(&mut self) -> SLEWFAST_W { SLEWFAST_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 = "Pad control register This 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). For information about available fields see [gpio_qspi_sclk](index.html) module"] pub struct GPIO_QSPI_SCLK_SPEC; impl crate::RegisterSpec for GPIO_QSPI_SCLK_SPEC { type Ux = u32; } #[doc = "`read()` method returns [gpio_qspi_sclk::R](R) reader structure"] impl crate::Readable for GPIO_QSPI_SCLK_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [gpio_qspi_sclk::W](W) writer structure"] impl crate::Writable for GPIO_QSPI_SCLK_SPEC { type Writer = W; } #[doc = "`reset()` method sets GPIO_QSPI_SCLK to value 0x56"] impl crate::Resettable for GPIO_QSPI_SCLK_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x56 } }
28.224839
300
0.554131
d7e7caf6609d5afa960ed00940264a85e2a9751f
1,220
fn sort_custom(strings: &mut Vec<&str>) { use std::cmp::Ordering; strings.sort_by(|a, b| { if a.len() > b.len() { return Ordering::Less; } if a.len() < b.len() { return Ordering::Greater; } a.cmp(b) }); } fn main() { let mut strings = vec![ "Here", "are", "some", "sample", "strings", "to", "be", "sorted", ]; sort_custom(&mut strings); println!("{:?}", strings); } #[cfg(test)] mod tests { use super::sort_custom; #[test] fn test_descending_in_length() { let mut strings = vec!["a", "aa", "aaa", "aaaa", "aaaaa"]; sort_custom(&mut strings); assert_eq!(strings, ["aaaaa", "aaaa", "aaa", "aa", "a"]); } #[test] fn test_ascending_lexicographically() { let mut strings = vec!["baaaa", "abaaa", "aabaa", "aaaba", "aaaab"]; sort_custom(&mut strings); assert_eq!(strings, ["aaaab", "aaaba", "aabaa", "abaaa", "baaaa"]); } #[test] fn test_mixture() { let mut strings = vec!["a", "A", "ba", "aa", "AA", "aAa", "aaa"]; sort_custom(&mut strings); assert_eq!(strings, ["aAa", "aaa", "AA", "aa", "ba", "A", "a"]); } }
27.727273
76
0.495902
f5a30eabe0ce981687b47215be7df3e8f01636a7
325
#[doc = "Reader of register _0_COUNT"] pub type R = crate::R<u32, super::_0_COUNT>; #[doc = "Reader of field `COUNT`"] pub type COUNT_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Counter Value"] #[inline(always)] pub fn count(&self) -> COUNT_R { COUNT_R::new((self.bits & 0xffff) as u16) } }
27.083333
49
0.593846
690879624058b4ac3a0667baec6a403889bbe683
18,985
/// The expansion from a test function to the appropriate test struct for libtest /// Ideally, this code would be in libtest but for efficiency and error messages it lives here. use crate::util::{check_builtin_macro_attribute, warn_on_duplicate_attribute}; use rustc_ast as ast; use rustc_ast::attr; use rustc_ast::ptr::P; use rustc_ast_pretty::pprust; use rustc_errors::Applicability; use rustc_expand::base::*; use rustc_session::Session; use rustc_span::symbol::{sym, Ident, Symbol}; use rustc_span::Span; use std::iter; // #[test_case] is used by custom test authors to mark tests // When building for test, it needs to make the item public and gensym the name // Otherwise, we'll omit the item. This behavior means that any item annotated // with #[test_case] is never addressable. // // We mark item with an inert attribute "rustc_test_marker" which the test generation // logic will pick up on. pub fn expand_test_case( ecx: &mut ExtCtxt<'_>, attr_sp: Span, meta_item: &ast::MetaItem, anno_item: Annotatable, ) -> Vec<Annotatable> { check_builtin_macro_attribute(ecx, meta_item, sym::test_case); warn_on_duplicate_attribute(&ecx, &anno_item, sym::test_case); if !ecx.ecfg.should_test { return vec![]; } let sp = ecx.with_def_site_ctxt(attr_sp); let mut item = anno_item.expect_item(); item = item.map(|mut item| { item.vis = ast::Visibility { span: item.vis.span, kind: ast::VisibilityKind::Public, tokens: None, }; item.ident.span = item.ident.span.with_ctxt(sp.ctxt()); item.attrs.push(ecx.attribute(ecx.meta_word(sp, sym::rustc_test_marker))); item }); return vec![Annotatable::Item(item)]; } pub fn expand_test( cx: &mut ExtCtxt<'_>, attr_sp: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> Vec<Annotatable> { check_builtin_macro_attribute(cx, meta_item, sym::test); warn_on_duplicate_attribute(&cx, &item, sym::test); expand_test_or_bench(cx, attr_sp, item, false) } pub fn expand_bench( cx: &mut ExtCtxt<'_>, attr_sp: Span, meta_item: &ast::MetaItem, item: Annotatable, ) -> Vec<Annotatable> { check_builtin_macro_attribute(cx, meta_item, sym::bench); warn_on_duplicate_attribute(&cx, &item, sym::bench); expand_test_or_bench(cx, attr_sp, item, true) } pub fn expand_test_or_bench( cx: &mut ExtCtxt<'_>, attr_sp: Span, item: Annotatable, is_bench: bool, ) -> Vec<Annotatable> { // If we're not in test configuration, remove the annotated item if !cx.ecfg.should_test { return vec![]; } let (item, is_stmt) = match item { Annotatable::Item(i) => (i, false), Annotatable::Stmt(stmt) if matches!(stmt.kind, ast::StmtKind::Item(_)) => { // FIXME: Use an 'if let' guard once they are implemented if let ast::StmtKind::Item(i) = stmt.into_inner().kind { (i, true) } else { unreachable!() } } other => { cx.struct_span_err( other.span(), "`#[test]` attribute is only allowed on non associated functions", ) .emit(); return vec![other]; } }; // Note: non-associated fn items are already handled by `expand_test_or_bench` if !matches!(item.kind, ast::ItemKind::Fn(_)) { cx.sess .parse_sess .span_diagnostic .struct_span_err( attr_sp, "the `#[test]` attribute may only be used on a non-associated function", ) .note("the `#[test]` macro causes a a function to be run on a test and has no effect on non-functions") .span_label(item.span, format!("expected a non-associated function, found {} {}", item.kind.article(), item.kind.descr())) .span_suggestion(attr_sp, "replace with conditional compilation to make the item only exist when tests are being run", String::from("#[cfg(test)]"), Applicability::MaybeIncorrect) .emit(); return vec![Annotatable::Item(item)]; } // has_*_signature will report any errors in the type so compilation // will fail. We shouldn't try to expand in this case because the errors // would be spurious. if (!is_bench && !has_test_signature(cx, &item)) || (is_bench && !has_bench_signature(cx, &item)) { return vec![Annotatable::Item(item)]; } let (sp, attr_sp) = (cx.with_def_site_ctxt(item.span), cx.with_def_site_ctxt(attr_sp)); let test_id = Ident::new(sym::test, attr_sp); // creates test::$name let test_path = |name| cx.path(sp, vec![test_id, Ident::from_str_and_span(name, sp)]); // creates test::ShouldPanic::$name let should_panic_path = |name| { cx.path( sp, vec![ test_id, Ident::from_str_and_span("ShouldPanic", sp), Ident::from_str_and_span(name, sp), ], ) }; // creates test::TestType::$name let test_type_path = |name| { cx.path( sp, vec![ test_id, Ident::from_str_and_span("TestType", sp), Ident::from_str_and_span(name, sp), ], ) }; // creates $name: $expr let field = |name, expr| cx.field_imm(sp, Ident::from_str_and_span(name, sp), expr); let test_fn = if is_bench { // A simple ident for a lambda let b = Ident::from_str_and_span("b", attr_sp); cx.expr_call( sp, cx.expr_path(test_path("StaticBenchFn")), vec![ // |b| self::test::assert_test_result( cx.lambda1( sp, cx.expr_call( sp, cx.expr_path(test_path("assert_test_result")), vec![ // super::$test_fn(b) cx.expr_call( sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![cx.expr_ident(sp, b)], ), ], ), b, ), // ) ], ) } else { cx.expr_call( sp, cx.expr_path(test_path("StaticTestFn")), vec![ // || { cx.lambda0( sp, // test::assert_test_result( cx.expr_call( sp, cx.expr_path(test_path("assert_test_result")), vec![ // $test_fn() cx.expr_call(sp, cx.expr_path(cx.path(sp, vec![item.ident])), vec![]), // ) ], ), // } ), // ) ], ) }; let mut test_const = cx.item( sp, Ident::new(item.ident.name, sp), vec![ // #[cfg(test)] cx.attribute(attr::mk_list_item( Ident::new(sym::cfg, attr_sp), vec![attr::mk_nested_word_item(Ident::new(sym::test, attr_sp))], )), // #[rustc_test_marker] cx.attribute(cx.meta_word(attr_sp, sym::rustc_test_marker)), ], // const $ident: test::TestDescAndFn = ast::ItemKind::Const( ast::Defaultness::Final, cx.ty(sp, ast::TyKind::Path(None, test_path("TestDescAndFn"))), // test::TestDescAndFn { Some( cx.expr_struct( sp, test_path("TestDescAndFn"), vec![ // desc: test::TestDesc { field( "desc", cx.expr_struct( sp, test_path("TestDesc"), vec![ // name: "path::to::test" field( "name", cx.expr_call( sp, cx.expr_path(test_path("StaticTestName")), vec![cx.expr_str( sp, Symbol::intern(&item_path( // skip the name of the root module &cx.current_expansion.module.mod_path[1..], &item.ident, )), )], ), ), // ignore: true | false field( "ignore", cx.expr_bool(sp, should_ignore(&cx.sess, &item)), ), // compile_fail: true | false field("compile_fail", cx.expr_bool(sp, false)), // no_run: true | false field("no_run", cx.expr_bool(sp, false)), // should_panic: ... field( "should_panic", match should_panic(cx, &item) { // test::ShouldPanic::No ShouldPanic::No => { cx.expr_path(should_panic_path("No")) } // test::ShouldPanic::Yes ShouldPanic::Yes(None) => { cx.expr_path(should_panic_path("Yes")) } // test::ShouldPanic::YesWithMessage("...") ShouldPanic::Yes(Some(sym)) => cx.expr_call( sp, cx.expr_path(should_panic_path("YesWithMessage")), vec![cx.expr_str(sp, sym)], ), }, ), // test_type: ... field( "test_type", match test_type(cx) { // test::TestType::UnitTest TestType::UnitTest => { cx.expr_path(test_type_path("UnitTest")) } // test::TestType::IntegrationTest TestType::IntegrationTest => { cx.expr_path(test_type_path("IntegrationTest")) } // test::TestPath::Unknown TestType::Unknown => { cx.expr_path(test_type_path("Unknown")) } }, ), // }, ], ), ), // testfn: test::StaticTestFn(...) | test::StaticBenchFn(...) field("testfn", test_fn), // } ], ), // } ), ), ); test_const = test_const.map(|mut tc| { tc.vis.kind = ast::VisibilityKind::Public; tc }); // extern crate test let test_extern = cx.item(sp, test_id, vec![], ast::ItemKind::ExternCrate(None)); tracing::debug!("synthetic test item:\n{}\n", pprust::item_to_string(&test_const)); if is_stmt { vec![ // Access to libtest under a hygienic name Annotatable::Stmt(P(cx.stmt_item(sp, test_extern))), // The generated test case Annotatable::Stmt(P(cx.stmt_item(sp, test_const))), // The original item Annotatable::Stmt(P(cx.stmt_item(sp, item))), ] } else { vec![ // Access to libtest under a hygienic name Annotatable::Item(test_extern), // The generated test case Annotatable::Item(test_const), // The original item Annotatable::Item(item), ] } } fn item_path(mod_path: &[Ident], item_ident: &Ident) -> String { mod_path .iter() .chain(iter::once(item_ident)) .map(|x| x.to_string()) .collect::<Vec<String>>() .join("::") } enum ShouldPanic { No, Yes(Option<Symbol>), } fn should_ignore(sess: &Session, i: &ast::Item) -> bool { sess.contains_name(&i.attrs, sym::ignore) } fn should_panic(cx: &ExtCtxt<'_>, i: &ast::Item) -> ShouldPanic { match cx.sess.find_by_name(&i.attrs, sym::should_panic) { Some(attr) => { let sd = &cx.sess.parse_sess.span_diagnostic; match attr.meta_item_list() { // Handle #[should_panic(expected = "foo")] Some(list) => { let msg = list .iter() .find(|mi| mi.has_name(sym::expected)) .and_then(|mi| mi.meta_item()) .and_then(|mi| mi.value_str()); if list.len() != 1 || msg.is_none() { sd.struct_span_warn( attr.span, "argument must be of the form: \ `expected = \"error message\"`", ) .note( "errors in this attribute were erroneously \ allowed and will become a hard error in a \ future release", ) .emit(); ShouldPanic::Yes(None) } else { ShouldPanic::Yes(msg) } } // Handle #[should_panic] and #[should_panic = "expected"] None => ShouldPanic::Yes(attr.value_str()), } } None => ShouldPanic::No, } } enum TestType { UnitTest, IntegrationTest, Unknown, } /// Attempts to determine the type of test. /// Since doctests are created without macro expanding, only possible variants here /// are `UnitTest`, `IntegrationTest` or `Unknown`. fn test_type(cx: &ExtCtxt<'_>) -> TestType { // Root path from context contains the topmost sources directory of the crate. // I.e., for `project` with sources in `src` and tests in `tests` folders // (no matter how many nested folders lie inside), // there will be two different root paths: `/project/src` and `/project/tests`. let crate_path = cx.root_path.as_path(); if crate_path.ends_with("src") { // `/src` folder contains unit-tests. TestType::UnitTest } else if crate_path.ends_with("tests") { // `/tests` folder contains integration tests. TestType::IntegrationTest } else { // Crate layout doesn't match expected one, test type is unknown. TestType::Unknown } } fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool { let has_should_panic_attr = cx.sess.contains_name(&i.attrs, sym::should_panic); let sd = &cx.sess.parse_sess.span_diagnostic; if let ast::ItemKind::Fn(box ast::Fn { ref sig, ref generics, .. }) = i.kind { if let ast::Unsafe::Yes(span) = sig.header.unsafety { sd.struct_span_err(i.span, "unsafe functions cannot be used for tests") .span_label(span, "`unsafe` because of this") .emit(); return false; } if let ast::Async::Yes { span, .. } = sig.header.asyncness { sd.struct_span_err(i.span, "async functions cannot be used for tests") .span_label(span, "`async` because of this") .emit(); return false; } // If the termination trait is active, the compiler will check that the output // type implements the `Termination` trait as `libtest` enforces that. let has_output = match sig.decl.output { ast::FnRetTy::Default(..) => false, ast::FnRetTy::Ty(ref t) if t.kind.is_unit() => false, _ => true, }; if !sig.decl.inputs.is_empty() { sd.span_err(i.span, "functions used as tests can not have any arguments"); return false; } match (has_output, has_should_panic_attr) { (true, true) => { sd.span_err(i.span, "functions using `#[should_panic]` must return `()`"); false } (true, false) => { if !generics.params.is_empty() { sd.span_err(i.span, "functions used as tests must have signature fn() -> ()"); false } else { true } } (false, _) => true, } } else { // should be unreachable because `is_test_fn_item` should catch all non-fn items false } } fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool { let has_sig = if let ast::ItemKind::Fn(box ast::Fn { ref sig, .. }) = i.kind { // N.B., inadequate check, but we're running // well before resolve, can't get too deep. sig.decl.inputs.len() == 1 } else { false }; if !has_sig { cx.sess.parse_sess.span_diagnostic.span_err( i.span, "functions used as benches must have \ signature `fn(&mut Bencher) -> impl Termination`", ); } has_sig }
37.743539
191
0.45399
33d4bc43088dac54895f840f5e0dddfb99a285ce
532
use crate::LocalVecImpl; impl<T: Clone, const N: usize> Clone for LocalVecImpl<T, N> { fn clone(&self) -> Self { let mut cloned = Self::new(); for i in 0..self.len() { cloned.push(self[i].clone()); } debug_assert_eq!(cloned.len(), self.len()); cloned } } #[cfg(test)] mod tests { use super::*; #[test] fn test_clone() { let vec = LocalVecImpl::<_, 3>::from_array([1, 2, 3]); let cloned = vec.clone(); assert_eq!(vec, cloned); } }
22.166667
62
0.516917
c177078f769081faa6308262b5d7b35a52ccd194
5,247
//! Server side use std::{ io::{self, ErrorKind}, time::Duration, }; use futures::future::{select_all, FutureExt}; use log::{debug, error, trace, warn}; use tokio::{runtime::Handle, time}; use crate::{ config::Config, context::{Context, ServerState, SharedContext, SharedServerState}, plugin::{PluginMode, Plugins}, relay::{ flow::{MultiServerFlowStatistic, SharedMultiServerFlowStatistic}, manager::ManagerDatagram, tcprelay::server::run as run_tcp, udprelay::server::run as run_udp, utils::set_nofile, }, }; /// Runs Relay server on server side. #[inline] pub async fn run(config: Config, rt: Handle) -> io::Result<()> { // Create a context containing a DNS resolver and server running state flag. let server_state = ServerState::new_shared(&config, rt).await; // Create statistics for multiple servers // // This is for statistic purpose for [Manage Multiple Users](https://github.com/shadowsocks/shadowsocks/wiki/Manage-Multiple-Users) APIs let flow_stat = MultiServerFlowStatistic::new_shared(&config); run_with(config, flow_stat, server_state).await } pub(crate) async fn run_with( mut config: Config, flow_stat: SharedMultiServerFlowStatistic, server_stat: SharedServerState, ) -> io::Result<()> { trace!("initializing server with {:?}", config); assert!(config.config_type.is_server()); if let Some(nofile) = config.nofile { debug!("setting RLIMIT_NOFILE to {}", nofile); if let Err(err) = set_nofile(nofile) { match err.kind() { ErrorKind::PermissionDenied => { warn!("insufficient permission to change `nofile`, try to restart as root user"); } ErrorKind::InvalidInput => { warn!("invalid `nofile` value {}, decrease it and try again", nofile); } _ => { error!("failed to set RLIMIT_NOFILE with value {}, error: {}", nofile, err); } } return Err(err); } } let mode = config.mode; let mut vf = Vec::new(); let context = if mode.enable_tcp() { if config.has_server_plugins() { let plugins = Plugins::launch_plugins(&mut config, PluginMode::Client)?; vf.push(plugins.into_future().boxed()); } let context = Context::new_shared(config, server_stat); let tcp_fut = run_tcp(context.clone(), flow_stat.clone()); vf.push(tcp_fut.boxed()); context } else { Context::new_shared(config, server_stat) }; if mode.enable_udp() { // Run UDP relay before starting plugins // Because plugins doesn't support UDP relay let udp_fut = run_udp(context.clone(), flow_stat.clone()); vf.push(udp_fut.boxed()); } // If specified manager-address, reports transmission statistic to it // // Dont do that if server is created by manager if context.config().manager_addr.is_some() { let report_fut = manager_report_task(context.clone(), flow_stat); vf.push(report_fut.boxed()); } let (res, ..) = select_all(vf.into_iter()).await; error!("one of servers exited unexpectly, result: {:?}", res); // Tells all detached tasks to exit context.set_server_stopped(); Err(io::Error::new(io::ErrorKind::Other, "server exited unexpectly")) } async fn manager_report_task(context: SharedContext, flow_stat: SharedMultiServerFlowStatistic) -> io::Result<()> { let manager_addr = context.config().manager_addr.as_ref().unwrap(); let mut socket = ManagerDatagram::bind_for(manager_addr).await?; while context.server_running() { // For each servers, send "stat" command to manager // // This is for compatible with managers that replies on "stat" command // Ref: https://github.com/shadowsocks/shadowsocks/wiki/Manage-Multiple-Users // // If you are using manager in this project, this is not required. for svr_cfg in &context.config().server { let port = svr_cfg.addr().port(); if let Some(ref fstat) = flow_stat.get(port) { let stat = format!("stat: {{\"{}\":{}}}", port, fstat.trans_stat()); match socket.send_to_manager(stat.as_bytes(), &*context, &manager_addr).await { Ok(..) => { trace!( "sent {} for server \"{}\" to manger \"{}\"", stat, svr_cfg.addr(), manager_addr ); } Err(err) => { error!( "failed to send {} for server \"{}\" to manager \"{}\", error: {}", stat, svr_cfg.addr(), manager_addr, err ); } } } } // Report every 10 seconds time::delay_for(Duration::from_secs(10)).await; } Ok(()) }
33.851613
140
0.56013
91d6e8c19d46f13f8a66d2375dc320d3129e1d64
97,697
use super::{callbacks::Callbacks, Bucket}; use assert_impl::assert_impl; use log::warn; use qiniu_apis::{ http::ResponseErrorKind as HttpResponseErrorKind, http_client::{ApiResult, RegionsProvider, RegionsProviderEndpoints, Response, ResponseError, SyncResponseBody}, storage::get_objects::{ ListedObjectEntry, QueryParams, ResponseBody as GetObjectsV1ResponseBody, SyncRequestBuilder as GetObjectsV1SyncRequestBuilder, }, storage::get_objects_v2::SyncRequestBuilder as GetObjectsV2SyncRequestBuilder, }; use serde::{Deserialize, Serialize}; use smart_default::SmartDefault; use std::{ collections::VecDeque, fmt::{self, Debug}, io::{BufRead, BufReader, Lines}, }; use tap::prelude::*; #[cfg(feature = "async")] use {futures::io::BufReader as AsyncBufReader, qiniu_apis::http_client::AsyncResponseBody}; type RefRegionProviderEndpoints<'a> = RegionsProviderEndpoints<&'a dyn RegionsProvider>; #[derive(Debug, Clone)] struct ListParams<'a> { bucket: &'a Bucket, prefix: Option<&'a str>, limit: Limit, marker: Marker<'a>, need_parts: bool, } #[derive(Debug, Clone)] enum Marker<'a> { Original(Option<&'a str>), Subsequent(Option<String>), } impl<'a> Marker<'a> { fn new(marker: Option<&'a str>) -> Self { Self::Original(marker) } fn empty(&self) -> bool { matches!(self.as_ref().map(|s| s.is_empty()), Some(true) | None) } fn as_ref(&self) -> Option<&str> { match self { Self::Original(marker) => marker.as_deref(), Self::Subsequent(marker) => marker.as_deref(), } } fn set(&mut self, marker: Option<&str>) { *self = Self::Subsequent(marker.map(|s| s.to_owned())); } fn is_original(&self) -> bool { matches!(self, Self::Original(..)) } } #[derive(Copy, Debug, Clone)] struct Limit { limit: Option<usize>, max: Option<usize>, } impl Limit { fn new(limit: Option<usize>, version: ListVersion) -> Self { Self { limit, max: version.page_limit(), } } fn as_ref(&self) -> Option<usize> { match (self.limit, self.max) { (Some(limit), Some(max)) => Some(limit.min(max)), (Some(limit), None) => Some(limit), (None, Some(max)) => Some(max), (None, None) => None, } } fn exhausted(&self) -> bool { matches!(self.limit, Some(0)) } fn saturating_decrease(&mut self, sub: usize) { if let Some(limit) = self.limit.as_mut() { *limit = limit.saturating_sub(sub); } } } impl<'a> ListParams<'a> { fn to_query_params(&self) -> QueryParams<'a> { let mut query_params = QueryParams::default().set_bucket_as_str(self.bucket.name().as_str()); if let Some(marker) = self.marker.as_ref() { query_params = query_params.set_marker_as_str(marker.to_owned()); } if let Some(limit) = self.limit.as_ref() { query_params = query_params.set_limit_as_usize(limit); } if let Some(prefix) = self.prefix { query_params = query_params.set_prefix_as_str(prefix); } if self.need_parts { query_params = query_params.set_need_parts_as_bool(true); } query_params } fn have_done(&self) -> bool { self.limit.exhausted() || !self.marker.is_original() && self.marker.empty() } } /// 对象列举迭代器 /// /// 实现 [`std::iter::Iterator`] 接口, /// 在迭代过程中阻塞发起 API 列举对象信息。 /// /// 可以通过 [`crate::ListBuilder::iter`] 方法获取该迭代器。 #[must_use] pub struct ListIter<'a> { params: ListParams<'a>, version: SyncListVersionWithStep, callbacks: Callbacks<'a>, } impl Debug for ListIter<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ListIter") .field("params", &self.params) .field("version", &self.version) .finish() } } /// 列举 API 版本 /// /// 目前支持 V1 和 V2,默认为 V2 #[derive(Copy, Clone, Debug, SmartDefault)] #[non_exhaustive] pub enum ListVersion { /// 列举 API V1 V1, /// 列举 API V2 #[default] V2, } impl ListVersion { fn page_limit(self) -> Option<usize> { const V1_PAGE_SIZE_MAX: usize = 1000; match self { Self::V1 => Some(V1_PAGE_SIZE_MAX), Self::V2 => None, } } } #[derive(Debug)] enum SyncListVersionWithStep { V1(SyncListV1Step), V2(SyncListV2Step), } impl From<ListVersion> for SyncListVersionWithStep { fn from(version: ListVersion) -> Self { match version { ListVersion::V1 => Self::V1(Default::default()), ListVersion::V2 => Self::V2(Default::default()), } } } #[derive(Clone, Debug, SmartDefault)] pub(super) enum SyncListV1Step { #[default] Buffer { buffer: VecDeque<ListedObjectEntry>, }, Done, } #[derive(Debug, SmartDefault)] pub(super) enum SyncListV2Step { #[default] Start, Lines { lines: Lines<BufReader<SyncResponseBody>>, }, Done, } #[derive(Clone, Debug, Serialize, Deserialize)] struct ListedObjectEntryV2 { item: Option<ListedObjectEntry>, marker: Option<String>, } impl<'a> ListIter<'a> { pub(super) fn new( bucket: &'a Bucket, limit: Option<usize>, prefix: Option<&'a str>, marker: Option<&'a str>, need_parts: bool, version: ListVersion, callbacks: Callbacks<'a>, ) -> Self { Self { callbacks, version: version.into(), params: ListParams { bucket, prefix, need_parts, limit: Limit::new(limit, version), marker: Marker::new(marker), }, } } #[allow(dead_code)] fn assert() { assert_impl!(Send: Self); // assert_impl!(Sync: Self); } } impl Iterator for ListIter<'_> { type Item = ApiResult<ListedObjectEntry>; #[inline] fn next(&mut self) -> Option<Self::Item> { return match &mut self.version { SyncListVersionWithStep::V1(step) => v1_next(&mut self.params, &mut self.callbacks, step), SyncListVersionWithStep::V2(step) => v2_next(&mut self.params, &mut self.callbacks, step), }; fn v1_next( params: &mut ListParams<'_>, callbacks: &mut Callbacks<'_>, step: &mut SyncListV1Step, ) -> Option<ApiResult<ListedObjectEntry>> { match step { SyncListV1Step::Buffer { buffer } => { if let Some(object) = buffer.pop_front() { Some(Ok(object)) } else { match v1_next_page(params, callbacks, buffer) { Ok(true) => { *step = SyncListV1Step::Done; None } Ok(false) => buffer.pop_front().map(Ok), Err(err) => { *step = SyncListV1Step::Done; Some(Err(err)) } } } } SyncListV1Step::Done => None, } } fn v1_next_page( params: &mut ListParams<'_>, callbacks: &mut Callbacks<'_>, buffer: &mut VecDeque<ListedObjectEntry>, ) -> ApiResult<bool> { let mut have_done = false; if params.have_done() { have_done = true; } else { let request = v1_make_request(params)?; let response_result = v1_call_request(request, callbacks); v1_handle_response(response_result?.into_body(), params, buffer); } Ok(have_done) } fn v1_make_request<'a>( params: &mut ListParams<'a>, ) -> ApiResult<GetObjectsV1SyncRequestBuilder<'a, RefRegionProviderEndpoints<'a>>> { let mut request = params .bucket .objects_manager() .client() .storage() .get_objects() .new_request( RegionsProviderEndpoints::new(params.bucket.region_provider()?), params.bucket.objects_manager().credential(), ); request.query_pairs(params.to_query_params()); Ok(request) } fn v1_call_request( mut request: GetObjectsV1SyncRequestBuilder<'_, RefRegionProviderEndpoints>, callbacks: &mut Callbacks<'_>, ) -> ApiResult<Response<GetObjectsV1ResponseBody>> { if callbacks.before_request(request.parts_mut()).is_cancelled() { return Err(make_user_cancelled_error("Cancelled by before_request() callback")); } let mut response_result = request.call(); if callbacks.after_response(&mut response_result).is_cancelled() { return Err(make_user_cancelled_error("Cancelled by after_response() callback")); } response_result } fn v1_handle_response( body: GetObjectsV1ResponseBody, params: &mut ListParams<'_>, buffer: &mut VecDeque<ListedObjectEntry>, ) { params.marker.set(body.get_marker_as_str()); let listed_object_entries = body.get_items().to_listed_object_entry_vec(); params.limit.saturating_decrease(listed_object_entries.len()); *buffer = listed_object_entries.into(); } fn v2_next( params: &mut ListParams<'_>, callbacks: &mut Callbacks<'_>, step: &mut SyncListV2Step, ) -> Option<ApiResult<ListedObjectEntry>> { match step { SyncListV2Step::Start => match v2_call(params, callbacks) { Ok(Some(mut lines)) => v2_read_entry_from_lines(params, &mut lines).tap_some(|result| { if result.is_ok() { *step = SyncListV2Step::Lines { lines }; } else { *step = SyncListV2Step::Done; } }), Ok(None) => { *step = SyncListV2Step::Done; None } Err(err) => { *step = SyncListV2Step::Done; Some(Err(err)) } }, SyncListV2Step::Lines { lines } => match v2_read_entry_from_lines(params, lines) { Some(Ok(entry)) => Some(Ok(entry)), Some(Err(err)) => { warn!("Read Error from ListV2 Response Body: {}", err); *step = SyncListV2Step::Start; v2_next(params, callbacks, step) } None => { *step = SyncListV2Step::Start; v2_next(params, callbacks, step) } }, SyncListV2Step::Done => None, } } fn v2_read_entry_from_lines( params: &mut ListParams<'_>, lines: &mut Lines<BufReader<SyncResponseBody>>, ) -> Option<ApiResult<ListedObjectEntry>> { if params.limit.exhausted() { return None; } loop { match lines.next() { Some(Ok(line)) if line.is_empty() => { continue; } Some(Ok(line)) => match serde_json::from_str::<ListedObjectEntryV2>(&line) { Ok(parsed) => { params.marker.set(parsed.marker.as_deref()); if let Some(item) = parsed.item { params.limit.saturating_decrease(1); return Some(Ok(item)); } else { continue; } } Err(err) => { return Some(Err(err.into())); } }, Some(Err(err)) => { return Some(Err(err.into())); } None => { return None; } } } } fn v2_call( params: &mut ListParams<'_>, callbacks: &mut Callbacks<'_>, ) -> ApiResult<Option<Lines<BufReader<SyncResponseBody>>>> { if params.have_done() { return Ok(None); } let request = v2_make_request(params)?; let response_result = v2_call_request(request, callbacks); Ok(Some(BufReader::new(response_result?.into_body()).lines())) } fn v2_make_request<'a>( params: &mut ListParams<'a>, ) -> ApiResult<GetObjectsV2SyncRequestBuilder<'a, RefRegionProviderEndpoints<'a>>> { let mut request = params .bucket .objects_manager() .client() .storage() .get_objects_v2() .new_request( RegionsProviderEndpoints::new(params.bucket.region_provider()?), params.bucket.objects_manager().credential(), ); request.query_pairs(params.to_query_params()); Ok(request) } fn v2_call_request( mut request: GetObjectsV2SyncRequestBuilder<'_, RefRegionProviderEndpoints>, callbacks: &mut Callbacks<'_>, ) -> ApiResult<Response<SyncResponseBody>> { if callbacks.before_request(request.parts_mut()).is_cancelled() { return Err(make_user_cancelled_error("Cancelled by before_request() callback")); } let mut response_result = request.call(); if callbacks.after_response(&mut response_result).is_cancelled() { return Err(make_user_cancelled_error("Cancelled by after_response() callback")); } response_result } } } #[cfg(feature = "async")] mod async_list_stream { use super::*; use futures::{ future::BoxFuture, io::Lines as AsyncLines, ready, stream::BoxStream, AsyncBufReadExt, FutureExt, Stream, StreamExt, }; use std::{ fmt::{self, Debug}, io::Result as IOResult, pin::Pin, task::{Context, Poll}, }; enum AsyncListVersionWithStep<'a> { V1(AsyncListV1Step<'a>), V2(AsyncListV2Step<'a>), } impl From<ListVersion> for AsyncListVersionWithStep<'_> { fn from(version: ListVersion) -> Self { match version { ListVersion::V1 => Self::V1(Default::default()), ListVersion::V2 => Self::V2(Default::default()), } } } #[derive(SmartDefault)] enum AsyncListV1Step<'a> { #[default] FromBuffer { buffer: VecDeque<ListedObjectEntry>, }, WaitForResponse { task: BoxFuture<'a, ApiResult<Response<GetObjectsV1ResponseBody>>>, }, WaitForRegionProvider { task: BoxFuture<'a, IOResult<&'a dyn RegionsProvider>>, }, Done, } impl Debug for AsyncListV1Step<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::FromBuffer { buffer } => f.debug_tuple("FromBuffer").field(buffer).finish(), Self::WaitForResponse { .. } => f.debug_tuple("WaitForResponse").finish(), Self::WaitForRegionProvider { .. } => f.debug_tuple("WaitForRegionProvider").finish(), Self::Done => f.debug_tuple("Done").finish(), } } } type ListedObjectEntryResultStream<'a> = BoxStream<'a, ApiResult<ListedObjectEntry>>; /// 对象列举流 /// /// 实现 [`futures::stream::Stream`] 接口, /// 在迭代过程中异步发起 API 列举对象信息 /// /// 可以通过 [`crate::ListBuilder::stream`] 方法获取该迭代器。 #[must_use] #[cfg_attr(feature = "docs", doc(cfg(feature = "async")))] pub struct ListStream<'a>(ListedObjectEntryResultStream<'a>); impl<'a> ListStream<'a> { pub(in super::super) fn new( bucket: &'a Bucket, limit: Option<usize>, prefix: Option<&'a str>, marker: Option<&'a str>, need_parts: bool, version: ListVersion, callbacks: Callbacks<'a>, ) -> Self { Self(match version { ListVersion::V1 => v1_next(bucket, limit, prefix, marker, need_parts, callbacks), ListVersion::V2 => v2_next(bucket, limit, prefix, marker, need_parts, callbacks), }) } #[allow(dead_code)] fn assert() { assert_impl!(Send: Self); // assert_impl!(Sync: Self); } } impl Stream for ListStream<'_> { type Item = ApiResult<ListedObjectEntry>; #[inline] fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { self.0.poll_next_unpin(cx) } } impl Debug for ListStream<'_> { #[inline] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("ListStream").finish() } } #[derive(Debug)] struct ListV1Stream<'a> { params: ListParams<'a>, callbacks: Callbacks<'a>, current_step: AsyncListV1Step<'a>, } fn v1_next<'a>( bucket: &'a Bucket, limit: Option<usize>, prefix: Option<&'a str>, marker: Option<&'a str>, need_parts: bool, callbacks: Callbacks<'a>, ) -> ListedObjectEntryResultStream<'a> { let params = ListParams { bucket, prefix, need_parts, limit: Limit::new(limit, ListVersion::V1), marker: Marker::new(marker), }; ListV1Stream { params, callbacks, current_step: Default::default(), } .boxed() } impl Stream for ListV1Stream<'_> { type Item = ApiResult<ListedObjectEntry>; #[inline] fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.current_step { AsyncListV1Step::FromBuffer { .. } => self.read_from_buffer(cx), AsyncListV1Step::WaitForResponse { .. } => self.wait_for_response(cx), AsyncListV1Step::WaitForRegionProvider { .. } => self.wait_for_region(cx), AsyncListV1Step::Done => Poll::Ready(None), } } } impl ListV1Stream<'_> { fn read_from_buffer(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV1Step::FromBuffer { buffer } = &mut self.current_step { if let Some(object) = buffer.pop_front() { Poll::Ready(Some(Ok(object))) } else { if self.params.have_done() { self.current_step = AsyncListV1Step::Done; } else { let bucket = self.params.bucket; self.current_step = AsyncListV1Step::WaitForRegionProvider { task: Box::pin(async move { bucket.async_region_provider().await }), }; } self.poll_next(cx) } } else { unreachable!() } } fn wait_for_region(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV1Step::WaitForRegionProvider { task } = &mut self.current_step { match ready!(task.poll_unpin(cx)) { Ok(region_provider) => { let credential = self.params.bucket.objects_manager().credential(); let mut request = self .params .bucket .objects_manager() .client() .storage() .get_objects() .new_async_request(RegionsProviderEndpoints::new(region_provider), credential); request.query_pairs(self.params.to_query_params()); if self.callbacks.before_request(request.parts_mut()).is_cancelled() { self.current_step = AsyncListV1Step::Done; return Poll::Ready(Some(Err(make_user_cancelled_error( "Cancelled by before_request() callback", )))); } self.current_step = AsyncListV1Step::WaitForResponse { task: Box::pin(async move { request.call().await }), }; self.poll_next(cx) } Err(err) => { self.current_step = AsyncListV1Step::Done; Poll::Ready(Some(Err(err.into()))) } } } else { unreachable!() } } fn wait_for_response(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV1Step::WaitForResponse { task } = &mut self.current_step { let mut response_result = ready!(task.poll_unpin(cx)); if self.callbacks.after_response(&mut response_result).is_cancelled() { self.current_step = AsyncListV1Step::Done; return Poll::Ready(Some(Err(make_user_cancelled_error( "Cancelled by after_response() callback", )))); } match response_result { Ok(response) => { let body = response.into_body(); let listed_object_entries = body.get_items().to_listed_object_entry_vec(); self.params.marker.set(body.get_marker_as_str()); self.params.limit.saturating_decrease(listed_object_entries.len()); self.current_step = AsyncListV1Step::FromBuffer { buffer: listed_object_entries.into(), }; self.poll_next(cx) } Err(err) => { self.current_step = AsyncListV1Step::Done; Poll::Ready(Some(Err(err))) } } } else { unreachable!() } } } #[derive(SmartDefault)] enum AsyncListV2Step<'a> { #[default] Start, WaitForRegionProvider { task: BoxFuture<'a, IOResult<&'a dyn RegionsProvider>>, }, WaitForResponse { task: BoxFuture<'a, ApiResult<Response<AsyncResponseBody>>>, }, WaitForEntries { lines: AsyncLines<AsyncBufReader<AsyncResponseBody>>, }, Done, } struct ListV2Stream<'a> { params: ListParams<'a>, callbacks: Callbacks<'a>, current_step: AsyncListV2Step<'a>, } #[allow(clippy::too_many_arguments)] fn v2_next<'a>( bucket: &'a Bucket, limit: Option<usize>, prefix: Option<&'a str>, marker: Option<&'a str>, need_parts: bool, callbacks: Callbacks<'a>, ) -> ListedObjectEntryResultStream<'a> { let params = ListParams { bucket, prefix, need_parts, limit: Limit::new(limit, ListVersion::V2), marker: Marker::new(marker), }; ListV2Stream { params, callbacks, current_step: Default::default(), } .boxed() } impl Stream for ListV2Stream<'_> { type Item = ApiResult<ListedObjectEntry>; #[inline] fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.current_step { AsyncListV2Step::Start { .. } => self.start(cx), AsyncListV2Step::WaitForResponse { .. } => self.wait_for_response(cx), AsyncListV2Step::WaitForRegionProvider { .. } => self.wait_for_region(cx), AsyncListV2Step::WaitForEntries { .. } => self.wait_for_entries(cx), AsyncListV2Step::Done => Poll::Ready(None), } } } impl ListV2Stream<'_> { fn start(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV2Step::Start { .. } = &mut self.current_step { if self.params.have_done() { self.current_step = AsyncListV2Step::Done; } else { let bucket = self.params.bucket; self.current_step = AsyncListV2Step::WaitForRegionProvider { task: Box::pin(async move { bucket.async_region_provider().await }), }; } self.poll_next(cx) } else { unreachable!() } } fn wait_for_region(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV2Step::WaitForRegionProvider { task } = &mut self.current_step { match ready!(task.poll_unpin(cx)) { Ok(region_provider) => { let credential = self.params.bucket.objects_manager().credential(); let mut request = self .params .bucket .objects_manager() .client() .storage() .get_objects_v2() .new_async_request(RegionsProviderEndpoints::new(region_provider), credential); request.query_pairs(self.params.to_query_params()); if self.callbacks.before_request(request.parts_mut()).is_cancelled() { self.current_step = AsyncListV2Step::Done; return Poll::Ready(Some(Err(make_user_cancelled_error( "Cancelled by after_response() callback", )))); } self.current_step = AsyncListV2Step::WaitForResponse { task: Box::pin(async move { request.call().await }), }; self.poll_next(cx) } Err(err) => { self.current_step = AsyncListV2Step::Done; Poll::Ready(Some(Err(err.into()))) } } } else { unreachable!() } } fn wait_for_response(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV2Step::WaitForResponse { task } = &mut self.current_step { let mut response_result = ready!(task.poll_unpin(cx)); if self.callbacks.after_response(&mut response_result).is_cancelled() { self.current_step = AsyncListV2Step::Done; return Poll::Ready(Some(Err(make_user_cancelled_error( "Cancelled by after_response() error", )))); } match response_result { Ok(response) => { self.current_step = AsyncListV2Step::WaitForEntries { lines: AsyncBufReader::new(response.into_body()).lines(), }; self.poll_next(cx) } Err(err) => { self.current_step = AsyncListV2Step::Done; Poll::Ready(Some(Err(err))) } } } else { unreachable!() } } fn wait_for_entries(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<<Self as Stream>::Item>> { if let AsyncListV2Step::WaitForEntries { lines } = &mut self.current_step { match ready!(lines.poll_next_unpin(cx)) { Some(Ok(line)) if line.is_empty() => self.wait_for_entries(cx), Some(Ok(line)) => match serde_json::from_str::<ListedObjectEntryV2>(&line) { Ok(parsed) => { self.params.marker.set(parsed.marker.as_deref()); if let Some(item) = parsed.item { self.params.limit.saturating_decrease(1); Poll::Ready(Some(Ok(item))) } else { self.wait_for_entries(cx) } } Err(err) => { self.current_step = AsyncListV2Step::Done; Poll::Ready(Some(Err(err.into()))) } }, Some(Err(err)) => { self.current_step = AsyncListV2Step::Done; Poll::Ready(Some(Err(err.into()))) } None => { self.current_step = AsyncListV2Step::Start; self.poll_next(cx) } } } else { unreachable!() } } } } fn make_user_cancelled_error(message: &str) -> ResponseError { ResponseError::new(HttpResponseErrorKind::UserCanceled.into(), message) } #[cfg(feature = "async")] pub use async_list_stream::*; #[cfg(test)] mod tests { use super::{super::ObjectsManager, *}; use qiniu_apis::{ credential::Credential, http::{HeaderValue, HttpCaller, StatusCode, SyncRequest, SyncResponse, SyncResponseResult}, http_client::{ BucketName, CallbackResult, DirectChooser, HttpClient, NeverRetrier, Region, ResponseErrorKind, NO_BACKOFF, }, }; use serde_json::{json, to_string as json_to_string, to_vec as json_to_vec}; use std::{ sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, time::{SystemTime, UNIX_EPOCH}, }; #[cfg(feature = "async")] use { futures::{future::BoxFuture, StreamExt, TryStreamExt}, qiniu_apis::http::{AsyncRequest, AsyncResponse, AsyncResponseResult}, }; #[test] fn test_sync_list_v1() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1000")); SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "", "items": [{ "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }, { "key": "fakeobj4", "put_time": generate_put_time(), "hash": "fakeobj4hash", "fsize": 4usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let mut counter = 0usize; for (i, entry) in get_bucket(FakeHttpCaller::default()) .list() .version(ListVersion::V1) .iter() .enumerate() { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 4usize); Ok(()) } #[test] fn test_sync_list_v1_with_error() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let (code, body) = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); ( StatusCode::OK, SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1000")); ( StatusCode::from_u16(599).unwrap(), SyncResponseBody::from_bytes( json_to_vec(&json!({ "error": "Test Error" })) .unwrap(), ), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(code) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let before_request_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_ok_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_error_callback_counter = Arc::new(AtomicUsize::new(0)); let bucket = get_bucket(FakeHttpCaller::default()); let mut iter = bucket .list() .version(ListVersion::V1) .before_request_callback({ let before_request_callback_counter = before_request_callback_counter.to_owned(); move |_| { before_request_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_ok_callback({ let after_response_ok_callback_counter = after_response_ok_callback_counter.to_owned(); move |_| { after_response_ok_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_error_callback({ let after_response_error_callback_counter = after_response_error_callback_counter.to_owned(); move |_| { after_response_error_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .iter(); let mut entry = iter.next().unwrap()?; assert_eq!(entry.get_key_as_str(), "fakeobj1"); assert_eq!(entry.get_hash_as_str(), "fakeobj1hash"); assert_eq!(entry.get_size_as_u64(), 1u64); entry = iter.next().unwrap()?; assert_eq!(entry.get_key_as_str(), "fakeobj2"); assert_eq!(entry.get_hash_as_str(), "fakeobj2hash"); assert_eq!(entry.get_size_as_u64(), 2u64); let err = iter.next().unwrap().unwrap_err(); assert_eq!( err.kind(), ResponseErrorKind::StatusCodeError(StatusCode::from_u16(599)?) ); assert!(iter.next().is_none()); assert_eq!(before_request_callback_counter.load(Ordering::Relaxed), 2usize); assert_eq!(after_response_ok_callback_counter.load(Ordering::Relaxed), 1usize); assert_eq!(after_response_error_callback_counter.load(Ordering::Relaxed), 1usize); Ok(()) } #[test] fn test_sync_list_v1_with_prefix_and_limitation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=3&prefix=fakeobj")); SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1&prefix=fakeobj")); SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "", "items": [{ "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let mut counter = 0usize; for (i, entry) in get_bucket(FakeHttpCaller::default()) .list() .version(ListVersion::V1) .prefix("fakeobj") .limit(3) .iter() .enumerate() { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 3usize); Ok(()) } #[test] fn test_sync_list_v1_with_cancellation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); SyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let counter = AtomicUsize::new(0); for (i, entry) in get_bucket(FakeHttpCaller::default()) .list() .version(ListVersion::V1) .before_request_callback(|_| { if counter.load(Ordering::Relaxed) > 0 { CallbackResult::Cancel } else { CallbackResult::Continue } }) .iter() .enumerate() { if counter.fetch_add(1, Ordering::Relaxed) < 2 { let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } else { let err = entry.unwrap_err(); assert!(matches!( err.kind(), ResponseErrorKind::HttpError(HttpResponseErrorKind::UserCanceled { .. }) )); break; } } assert_eq!(counter.into_inner(), 3usize); Ok(()) } #[test] fn test_sync_list_v2() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); SyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarkerobj2")); SyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj3", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj4", "put_time": generate_put_time(), "hash": "fakeobj4hash", "fsize": 4usize, "mime_type": "text/plain", }, "marker": "", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let mut counter = 0usize; for (i, entry) in get_bucket(FakeHttpCaller::default()) .list() .version(ListVersion::V2) .iter() .enumerate() { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 4usize); Ok(()) } #[test] fn test_sync_list_v2_with_error() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let (code, body) = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); ( StatusCode::OK, SyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ), ) } 1 => { assert!(request .url() .to_string() .ends_with("/v2/list?bucket=fakebucketname&marker=fakemarkerobj2")); ( StatusCode::from_u16(599).unwrap(), SyncResponseBody::from_bytes( json_to_vec(&json!({ "error": "Test Error" })) .unwrap(), ), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(code) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let before_request_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_ok_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_error_callback_counter = Arc::new(AtomicUsize::new(0)); let bucket = get_bucket(FakeHttpCaller::default()); let mut iter = bucket .list() .version(ListVersion::V2) .before_request_callback({ let before_request_callback_counter = before_request_callback_counter.to_owned(); move |_| { before_request_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_ok_callback({ let after_response_ok_callback_counter = after_response_ok_callback_counter.to_owned(); move |_| { after_response_ok_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_error_callback({ let after_response_error_callback_counter = after_response_error_callback_counter.to_owned(); move |_| { after_response_error_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .iter(); let mut entry = iter.next().unwrap()?; assert_eq!(entry.get_key_as_str(), "fakeobj1"); assert_eq!(entry.get_hash_as_str(), "fakeobj1hash"); assert_eq!(entry.get_size_as_u64(), 1u64); entry = iter.next().unwrap()?; assert_eq!(entry.get_key_as_str(), "fakeobj2"); assert_eq!(entry.get_hash_as_str(), "fakeobj2hash"); assert_eq!(entry.get_size_as_u64(), 2u64); let err = iter.next().unwrap().unwrap_err(); assert_eq!( err.kind(), ResponseErrorKind::StatusCodeError(StatusCode::from_u16(599)?) ); assert!(iter.next().is_none()); assert_eq!(before_request_callback_counter.load(Ordering::Relaxed), 2usize); assert_eq!(after_response_ok_callback_counter.load(Ordering::Relaxed), 1usize); assert_eq!(after_response_error_callback_counter.load(Ordering::Relaxed), 1usize); Ok(()) } #[test] fn test_sync_list_v2_with_cancellation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, request: &mut SyncRequest<'_>) -> SyncResponseResult { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); SyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } _ => unreachable!(), }; Ok(SyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) } #[cfg(feature = "async")] fn async_call(&self, _request: &mut AsyncRequest<'_>) -> BoxFuture<AsyncResponseResult> { unreachable!() } } let counter = AtomicUsize::new(0); for (i, entry) in get_bucket(FakeHttpCaller::default()) .list() .version(ListVersion::V2) .before_request_callback(|_| { if counter.load(Ordering::Relaxed) > 0 { CallbackResult::Cancel } else { CallbackResult::Continue } }) .iter() .enumerate() { if counter.fetch_add(1, Ordering::Relaxed) < 2 { let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } else { let err = entry.unwrap_err(); assert!(matches!( err.kind(), ResponseErrorKind::HttpError(HttpResponseErrorKind::UserCanceled { .. }) )); break; } } assert_eq!(counter.into_inner(), 3usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v1() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1000")); AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "", "items": [{ "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }, { "key": "fakeobj4", "put_time": generate_put_time(), "hash": "fakeobj4hash", "fsize": 4usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let mut counter = 0usize; let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket.list().version(ListVersion::V1).stream().enumerate(); while let Some((i, entry)) = stream.next().await { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 4usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v1_with_error() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let (code, body) = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); ( StatusCode::OK, AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1000")); ( StatusCode::from_u16(599).unwrap(), AsyncResponseBody::from_bytes( json_to_vec(&json!({ "error": "Test Error" })) .unwrap(), ), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(code) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let before_request_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_ok_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_error_callback_counter = Arc::new(AtomicUsize::new(0)); let bucket = get_bucket(FakeHttpCaller::default()); let mut iter = bucket .list() .version(ListVersion::V1) .before_request_callback({ let before_request_callback_counter = before_request_callback_counter.to_owned(); move |_| { before_request_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_ok_callback({ let after_response_ok_callback_counter = after_response_ok_callback_counter.to_owned(); move |_| { after_response_ok_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_error_callback({ let after_response_error_callback_counter = after_response_error_callback_counter.to_owned(); move |_| { after_response_error_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .stream(); let mut entry = iter.try_next().await?.unwrap(); assert_eq!(entry.get_key_as_str(), "fakeobj1"); assert_eq!(entry.get_hash_as_str(), "fakeobj1hash"); assert_eq!(entry.get_size_as_u64(), 1u64); entry = iter.try_next().await?.unwrap(); assert_eq!(entry.get_key_as_str(), "fakeobj2"); assert_eq!(entry.get_hash_as_str(), "fakeobj2hash"); assert_eq!(entry.get_size_as_u64(), 2u64); let err = iter.try_next().await.unwrap_err(); assert_eq!( err.kind(), ResponseErrorKind::StatusCodeError(StatusCode::from_u16(599)?) ); assert!(iter.try_next().await?.is_none()); assert_eq!(before_request_callback_counter.load(Ordering::Relaxed), 2usize); assert_eq!(after_response_ok_callback_counter.load(Ordering::Relaxed), 1usize); assert_eq!(after_response_error_callback_counter.load(Ordering::Relaxed), 1usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v1_with_prefix_and_limitation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=3&prefix=fakeobj")); AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarker&limit=1&prefix=fakeobj")); AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "", "items": [{ "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let mut counter = 0usize; let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket .list() .version(ListVersion::V1) .prefix("fakeobj") .limit(3) .stream() .enumerate(); while let Some((i, entry)) = stream.next().await { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 3usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v1_with_cancellation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&limit=1000")); AsyncResponseBody::from_bytes( json_to_vec(&json!({ "marker": "fakemarker", "items": [{ "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }] })) .unwrap(), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let counter = Arc::new(AtomicUsize::new(0)); { let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket .list() .version(ListVersion::V1) .before_request_callback({ let counter = counter.to_owned(); move |_| { if counter.load(Ordering::Relaxed) > 0 { CallbackResult::Cancel } else { CallbackResult::Continue } } }) .stream() .enumerate(); while let Some((i, entry)) = stream.next().await { if counter.fetch_add(1, Ordering::Relaxed) < 2 { let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } else { let err = entry.unwrap_err(); assert!(matches!( err.kind(), ResponseErrorKind::HttpError(HttpResponseErrorKind::UserCanceled { .. }) )); break; } } } assert_eq!(Arc::try_unwrap(counter).unwrap().into_inner(), 3usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v2() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); AsyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } 1 => { assert!(request .url() .to_string() .ends_with("/list?bucket=fakebucketname&marker=fakemarkerobj2")); AsyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj3", "put_time": generate_put_time(), "hash": "fakeobj3hash", "fsize": 3usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj3", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj4", "put_time": generate_put_time(), "hash": "fakeobj4hash", "fsize": 4usize, "mime_type": "text/plain", }, "marker": "", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let mut counter = 0usize; let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket.list().version(ListVersion::V2).stream().enumerate(); while let Some((i, entry)) = stream.next().await { counter += 1; let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } assert_eq!(counter, 4usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v2_with_error() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let (code, body) = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); ( StatusCode::OK, AsyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ), ) } 1 => { assert!(request .url() .to_string() .ends_with("/v2/list?bucket=fakebucketname&marker=fakemarkerobj2")); ( StatusCode::from_u16(599).unwrap(), AsyncResponseBody::from_bytes( json_to_vec(&json!({ "error": "Test Error" })) .unwrap(), ), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(code) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let before_request_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_ok_callback_counter = Arc::new(AtomicUsize::new(0)); let after_response_error_callback_counter = Arc::new(AtomicUsize::new(0)); let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket .list() .version(ListVersion::V2) .before_request_callback({ let before_request_callback_counter = before_request_callback_counter.to_owned(); move |_| { before_request_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_ok_callback({ let after_response_ok_callback_counter = after_response_ok_callback_counter.to_owned(); move |_| { after_response_ok_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .after_response_error_callback({ let after_response_error_callback_counter = after_response_error_callback_counter.to_owned(); move |_| { after_response_error_callback_counter.fetch_add(1, Ordering::Relaxed); CallbackResult::Continue } }) .stream(); let mut entry = stream.try_next().await?.unwrap(); assert_eq!(entry.get_key_as_str(), "fakeobj1"); assert_eq!(entry.get_hash_as_str(), "fakeobj1hash"); assert_eq!(entry.get_size_as_u64(), 1u64); entry = stream.try_next().await?.unwrap(); assert_eq!(entry.get_key_as_str(), "fakeobj2"); assert_eq!(entry.get_hash_as_str(), "fakeobj2hash"); assert_eq!(entry.get_size_as_u64(), 2u64); let err = stream.try_next().await.unwrap_err(); assert_eq!( err.kind(), ResponseErrorKind::StatusCodeError(StatusCode::from_u16(599)?) ); assert!(stream.try_next().await?.is_none()); assert_eq!(before_request_callback_counter.load(Ordering::Relaxed), 2usize); assert_eq!(after_response_ok_callback_counter.load(Ordering::Relaxed), 1usize); assert_eq!(after_response_error_callback_counter.load(Ordering::Relaxed), 1usize); Ok(()) } #[async_std::test] #[cfg(feature = "async")] async fn test_async_list_v2_with_cancellation() -> anyhow::Result<()> { env_logger::builder().is_test(true).try_init().ok(); #[derive(Debug, Default)] struct FakeHttpCaller { counter: AtomicUsize, } impl HttpCaller for FakeHttpCaller { fn call(&self, _request: &mut SyncRequest<'_>) -> SyncResponseResult { unreachable!() } fn async_call<'a>(&'a self, request: &'a mut AsyncRequest<'_>) -> BoxFuture<'a, AsyncResponseResult> { Box::pin(async move { let n = self.counter.fetch_add(1, Ordering::SeqCst); let body = match n { 0 => { assert!(request.url().to_string().ends_with("/v2/list?bucket=fakebucketname")); AsyncResponseBody::from_bytes( [ json_to_string(&json!({ "item": { "key": "fakeobj1", "put_time": generate_put_time(), "hash": "fakeobj1hash", "fsize": 1usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj1", })) .unwrap(), json_to_string(&json!({ "item": { "key": "fakeobj2", "put_time": generate_put_time(), "hash": "fakeobj2hash", "fsize": 2usize, "mime_type": "text/plain", }, "marker": "fakemarkerobj2", })) .unwrap(), ] .join("\n") .as_bytes() .to_owned(), ) } _ => unreachable!(), }; Ok(AsyncResponse::builder() .status_code(StatusCode::OK) .header("x-reqid", HeaderValue::from_static("FakeReqid")) .body(body) .build()) }) } } let counter = Arc::new(AtomicUsize::new(0)); { let bucket = get_bucket(FakeHttpCaller::default()); let mut stream = bucket .list() .version(ListVersion::V2) .before_request_callback({ let counter = counter.to_owned(); move |_| { if counter.load(Ordering::Relaxed) > 0 { CallbackResult::Cancel } else { CallbackResult::Continue } } }) .stream() .enumerate(); while let Some((i, entry)) = stream.next().await { if counter.fetch_add(1, Ordering::Relaxed) < 2 { let entry = entry?; assert_eq!(entry.get_key_as_str(), &format!("fakeobj{}", i + 1)); assert_eq!(entry.get_hash_as_str(), &format!("fakeobj{}hash", i + 1)); assert_eq!(entry.get_size_as_u64(), i as u64 + 1); } else { let err = entry.unwrap_err(); assert!(matches!( err.kind(), ResponseErrorKind::HttpError(HttpResponseErrorKind::UserCanceled { .. }) )); break; } } } assert_eq!(Arc::try_unwrap(counter).unwrap().into_inner(), 3usize); Ok(()) } fn get_bucket(caller: impl HttpCaller + 'static) -> Bucket { let object_manager = ObjectsManager::builder(get_credential()) .http_client( HttpClient::builder(caller) .chooser(DirectChooser) .request_retrier(NeverRetrier) .backoff(NO_BACKOFF) .build(), ) .build(); object_manager.bucket_with_region(get_bucket_name(), single_rsf_domain_region()) } fn get_credential() -> Credential { Credential::new("fakeaccesskey", "fakesecretkey") } fn get_bucket_name() -> BucketName { "fakebucketname".into() } fn generate_put_time() -> u64 { SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos() as u64 / 100 } fn single_rsf_domain_region() -> Region { Region::builder("chaotic") .add_rsf_preferred_endpoint(("fakersf.example.com".to_owned(), 8080).into()) .build() } }
40.404053
119
0.413073
d7a19f3c8ef4b9500e93a321ae92d606d3f9bd1a
36,315
// Copyright © 2019 Intel Corporation // // SPDX-License-Identifier: Apache-2.0 OR BSD-3-Clause // extern crate devices; extern crate pci; extern crate vm_allocator; use crate::vfio_device::VfioDevice; use byteorder::{ByteOrder, LittleEndian}; use devices::BusDevice; use kvm_bindings::kvm_userspace_memory_region; use kvm_ioctls::*; use pci::{ msi_num_enabled_vectors, BarReprogrammingParams, MsiConfig, MsixCap, MsixConfig, PciBarConfiguration, PciBarRegionType, PciCapabilityID, PciClassCode, PciConfiguration, PciDevice, PciDeviceError, PciHeaderType, PciSubclass, MSIX_TABLE_ENTRY_SIZE, }; use std::any::Any; use std::os::unix::io::AsRawFd; use std::ptr::null_mut; use std::sync::Arc; use std::{fmt, io, result}; use vfio_bindings::bindings::vfio::*; use vm_allocator::SystemAllocator; use vm_device::interrupt::{ InterruptIndex, InterruptManager, InterruptSourceGroup, MsiIrqGroupConfig, }; use vm_memory::{Address, GuestAddress, GuestUsize}; use vmm_sys_util::eventfd::EventFd; #[derive(Debug)] pub enum VfioPciError { AllocateGsi, EventFd(io::Error), InterruptSourceGroupCreate(io::Error), IrqFd(kvm_ioctls::Error), NewVfioPciDevice, MapRegionGuest(kvm_ioctls::Error), SetGsiRouting(kvm_ioctls::Error), MsiNotConfigured, MsixNotConfigured, UpdateMsiEventFd, UpdateMsixEventFd, } pub type Result<T> = std::result::Result<T, VfioPciError>; impl fmt::Display for VfioPciError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { VfioPciError::AllocateGsi => write!(f, "failed to allocate GSI"), VfioPciError::EventFd(e) => write!(f, "failed to create eventfd: {}", e), VfioPciError::InterruptSourceGroupCreate(e) => { write!(f, "failed to create interrupt source group: {}", e) } VfioPciError::IrqFd(e) => write!(f, "failed to register irqfd: {}", e), VfioPciError::NewVfioPciDevice => write!(f, "failed to create VFIO PCI device"), VfioPciError::MapRegionGuest(e) => { write!(f, "failed to map VFIO PCI region into guest: {}", e) } VfioPciError::SetGsiRouting(e) => write!(f, "failed to set GSI routes for KVM: {}", e), VfioPciError::MsiNotConfigured => write!(f, "MSI interrupt not yet configured"), VfioPciError::MsixNotConfigured => write!(f, "MSI-X interrupt not yet configured"), VfioPciError::UpdateMsiEventFd => write!(f, "failed to update MSI eventfd"), VfioPciError::UpdateMsixEventFd => write!(f, "failed to update MSI-X eventfd"), } } } #[derive(Copy, Clone)] enum PciVfioSubclass { VfioSubclass = 0xff, } impl PciSubclass for PciVfioSubclass { fn get_register_value(&self) -> u8 { *self as u8 } } enum InterruptUpdateAction { EnableMsi, DisableMsi, EnableMsix, DisableMsix, } struct VfioMsi { cfg: MsiConfig, cap_offset: u32, interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>, } impl VfioMsi { fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { let old_enabled = self.cfg.enabled(); self.cfg.update(offset, data); let new_enabled = self.cfg.enabled(); if !old_enabled && new_enabled { return Some(InterruptUpdateAction::EnableMsi); } if old_enabled && !new_enabled { return Some(InterruptUpdateAction::DisableMsi); } None } } struct VfioMsix { bar: MsixConfig, cap: MsixCap, cap_offset: u32, interrupt_source_group: Arc<Box<dyn InterruptSourceGroup>>, } impl VfioMsix { fn update(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { let old_enabled = self.bar.enabled(); // Update "Message Control" word if offset == 2 && data.len() == 2 { self.bar.set_msg_ctl(LittleEndian::read_u16(data)); } let new_enabled = self.bar.enabled(); if !old_enabled && new_enabled { return Some(InterruptUpdateAction::EnableMsix); } if old_enabled && !new_enabled { return Some(InterruptUpdateAction::DisableMsix); } None } fn table_accessed(&self, bar_index: u32, offset: u64) -> bool { let table_offset: u64 = u64::from(self.cap.table_offset()); let table_size: u64 = u64::from(self.cap.table_size()) * (MSIX_TABLE_ENTRY_SIZE as u64); let table_bir: u32 = self.cap.table_bir(); bar_index == table_bir && offset >= table_offset && offset < table_offset + table_size } } struct Interrupt { msi: Option<VfioMsi>, msix: Option<VfioMsix>, } impl Interrupt { fn update_msi(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { if let Some(ref mut msi) = &mut self.msi { let action = msi.update(offset, data); return action; } None } fn update_msix(&mut self, offset: u64, data: &[u8]) -> Option<InterruptUpdateAction> { if let Some(ref mut msix) = &mut self.msix { let action = msix.update(offset, data); return action; } None } fn accessed(&self, offset: u64) -> Option<(PciCapabilityID, u64)> { if let Some(msi) = &self.msi { if offset >= u64::from(msi.cap_offset) && offset < u64::from(msi.cap_offset) + msi.cfg.size() { return Some(( PciCapabilityID::MessageSignalledInterrupts, u64::from(msi.cap_offset), )); } } if let Some(msix) = &self.msix { if offset == u64::from(msix.cap_offset) { return Some((PciCapabilityID::MSIX, u64::from(msix.cap_offset))); } } None } fn msix_table_accessed(&self, bar_index: u32, offset: u64) -> bool { if let Some(msix) = &self.msix { return msix.table_accessed(bar_index, offset); } false } fn msix_write_table(&mut self, offset: u64, data: &[u8]) { if let Some(ref mut msix) = &mut self.msix { let offset = offset - u64::from(msix.cap.table_offset()); msix.bar.write_table(offset, data) } } fn msix_read_table(&self, offset: u64, data: &mut [u8]) { if let Some(msix) = &self.msix { let offset = offset - u64::from(msix.cap.table_offset()); msix.bar.read_table(offset, data) } } } #[derive(Copy, Clone)] struct MmioRegion { start: GuestAddress, length: GuestUsize, type_: PciBarRegionType, index: u32, mem_slot: Option<u32>, host_addr: Option<u64>, mmap_size: Option<usize>, } struct VfioPciConfig { device: Arc<VfioDevice>, } impl VfioPciConfig { fn new(device: Arc<VfioDevice>) -> Self { VfioPciConfig { device } } fn read_config_byte(&self, offset: u32) -> u8 { let mut data: [u8; 1] = [0]; self.device .region_read(VFIO_PCI_CONFIG_REGION_INDEX, data.as_mut(), offset.into()); data[0] } fn read_config_word(&self, offset: u32) -> u16 { let mut data: [u8; 2] = [0, 0]; self.device .region_read(VFIO_PCI_CONFIG_REGION_INDEX, data.as_mut(), offset.into()); u16::from_le_bytes(data) } fn read_config_dword(&self, offset: u32) -> u32 { let mut data: [u8; 4] = [0, 0, 0, 0]; self.device .region_read(VFIO_PCI_CONFIG_REGION_INDEX, data.as_mut(), offset.into()); u32::from_le_bytes(data) } fn write_config_dword(&self, buf: u32, offset: u32) { let data: [u8; 4] = buf.to_le_bytes(); self.device .region_write(VFIO_PCI_CONFIG_REGION_INDEX, &data, offset.into()) } } /// VfioPciDevice represents a VFIO PCI device. /// This structure implements the BusDevice and PciDevice traits. /// /// A VfioPciDevice is bound to a VfioDevice and is also a PCI device. /// The VMM creates a VfioDevice, then assigns it to a VfioPciDevice, /// which then gets added to the PCI bus. pub struct VfioPciDevice { vm_fd: Arc<VmFd>, device: Arc<VfioDevice>, vfio_pci_configuration: VfioPciConfig, configuration: PciConfiguration, mmio_regions: Vec<MmioRegion>, interrupt: Interrupt, } impl VfioPciDevice { /// Constructs a new Vfio Pci device for the given Vfio device pub fn new( vm_fd: &Arc<VmFd>, device: VfioDevice, interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, ) -> Result<Self> { let device = Arc::new(device); device.reset(); let configuration = PciConfiguration::new( 0, 0, PciClassCode::Other, &PciVfioSubclass::VfioSubclass, None, PciHeaderType::Device, 0, 0, None, ); let vfio_pci_configuration = VfioPciConfig::new(Arc::clone(&device)); let mut vfio_pci_device = VfioPciDevice { vm_fd: vm_fd.clone(), device, configuration, vfio_pci_configuration, mmio_regions: Vec::new(), interrupt: Interrupt { msi: None, msix: None, }, }; vfio_pci_device.parse_capabilities(interrupt_manager); Ok(vfio_pci_device) } fn parse_msix_capabilities( &mut self, cap: u8, interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, ) { let msg_ctl = self .vfio_pci_configuration .read_config_word((cap + 2).into()); let table = self .vfio_pci_configuration .read_config_dword((cap + 4).into()); let pba = self .vfio_pci_configuration .read_config_dword((cap + 8).into()); let msix_cap = MsixCap { msg_ctl, table, pba, }; let interrupt_source_group = interrupt_manager .create_group(MsiIrqGroupConfig { base: 0, count: msix_cap.table_size() as InterruptIndex, }) .unwrap(); let msix_config = MsixConfig::new(msix_cap.table_size(), interrupt_source_group.clone()); self.interrupt.msix = Some(VfioMsix { bar: msix_config, cap: msix_cap, cap_offset: cap.into(), interrupt_source_group, }); } fn parse_msi_capabilities( &mut self, cap: u8, interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, ) { let msg_ctl = self .vfio_pci_configuration .read_config_word((cap + 2).into()); let interrupt_source_group = interrupt_manager .create_group(MsiIrqGroupConfig { base: 0, count: msi_num_enabled_vectors(msg_ctl) as InterruptIndex, }) .unwrap(); let msi_config = MsiConfig::new(msg_ctl, interrupt_source_group.clone()); self.interrupt.msi = Some(VfioMsi { cfg: msi_config, cap_offset: cap.into(), interrupt_source_group, }); } fn parse_capabilities( &mut self, interrupt_manager: &Arc<dyn InterruptManager<GroupConfig = MsiIrqGroupConfig>>, ) { let mut cap_next = self .vfio_pci_configuration .read_config_byte(PCI_CONFIG_CAPABILITY_OFFSET); while cap_next != 0 { let cap_id = self .vfio_pci_configuration .read_config_byte(cap_next.into()); match PciCapabilityID::from(cap_id) { PciCapabilityID::MessageSignalledInterrupts => { self.parse_msi_capabilities(cap_next, interrupt_manager); } PciCapabilityID::MSIX => { self.parse_msix_capabilities(cap_next, interrupt_manager); } _ => {} }; cap_next = self .vfio_pci_configuration .read_config_byte((cap_next + 1).into()); } } fn update_msi_capabilities(&mut self, offset: u64, data: &[u8]) -> Result<()> { match self.interrupt.update_msi(offset, data) { Some(InterruptUpdateAction::EnableMsi) => { if let Some(msi) = &self.interrupt.msi { let mut irq_fds: Vec<&EventFd> = Vec::new(); for i in 0..msi.cfg.num_enabled_vectors() { if let Some(eventfd) = msi.interrupt_source_group.notifier(i as InterruptIndex) { irq_fds.push(eventfd); } else { return Err(VfioPciError::UpdateMsiEventFd); } } if let Err(e) = self.device.enable_msi(irq_fds) { warn!("Could not enable MSI: {}", e); } } } Some(InterruptUpdateAction::DisableMsi) => { if let Err(e) = self.device.disable_msi() { warn!("Could not disable MSI: {}", e); } } _ => {} } Ok(()) } fn update_msix_capabilities(&mut self, offset: u64, data: &[u8]) -> Result<()> { match self.interrupt.update_msix(offset, data) { Some(InterruptUpdateAction::EnableMsix) => { if let Some(msix) = &self.interrupt.msix { let mut irq_fds: Vec<&EventFd> = Vec::new(); for i in 0..msix.bar.table_entries.len() { if let Some(eventfd) = msix.interrupt_source_group.notifier(i as InterruptIndex) { irq_fds.push(eventfd); } else { return Err(VfioPciError::UpdateMsiEventFd); } } if let Err(e) = self.device.enable_msix(irq_fds) { warn!("Could not enable MSI-X: {}", e); } } } Some(InterruptUpdateAction::DisableMsix) => { if let Err(e) = self.device.disable_msix() { warn!("Could not disable MSI-X: {}", e); } } _ => {} } Ok(()) } fn find_region(&self, addr: u64) -> Option<MmioRegion> { for region in self.mmio_regions.iter() { if addr >= region.start.raw_value() && addr < region.start.unchecked_add(region.length).raw_value() { return Some(*region); } } None } /// Map MMIO regions into the guest, and avoid VM exits when the guest tries /// to reach those regions. /// /// # Arguments /// /// * `vm` - The KVM VM file descriptor. It is used to set the VFIO MMIO regions /// as KVM user memory regions. /// * `mem_slot` - The KVM memory slot to set the user memopry regions. /// # Return value /// /// This function returns the updated KVM memory slot id. pub fn map_mmio_regions<F>(&mut self, vm: &Arc<VmFd>, mem_slot: F) -> Result<()> where F: Fn() -> u32, { let fd = self.device.as_raw_fd(); for region in self.mmio_regions.iter_mut() { // We want to skip the mapping of the BAR containing the MSI-X // table even if it is mappable. The reason is we need to trap // any access to the MSI-X table and update the GSI routing // accordingly. if let Some(msix) = &self.interrupt.msix { if region.index == msix.cap.table_bir() || region.index == msix.cap.pba_bir() { continue; } } let region_flags = self.device.get_region_flags(region.index); if region_flags & VFIO_REGION_INFO_FLAG_MMAP != 0 { let mut prot = 0; if region_flags & VFIO_REGION_INFO_FLAG_READ != 0 { prot |= libc::PROT_READ; } if region_flags & VFIO_REGION_INFO_FLAG_WRITE != 0 { prot |= libc::PROT_WRITE; } let (mmap_offset, mmap_size) = self.device.get_region_mmap(region.index); let offset = self.device.get_region_offset(region.index) + mmap_offset; let host_addr = unsafe { libc::mmap( null_mut(), mmap_size as usize, prot, libc::MAP_SHARED, fd, offset as libc::off_t, ) }; if host_addr == libc::MAP_FAILED { error!( "Could not mmap regions, error:{}", io::Error::last_os_error() ); continue; } let slot = mem_slot(); let mem_region = kvm_userspace_memory_region { slot, guest_phys_addr: region.start.raw_value() + mmap_offset, memory_size: mmap_size as u64, userspace_addr: host_addr as u64, flags: 0, }; // Safe because the guest regions are guaranteed not to overlap. unsafe { vm.set_user_memory_region(mem_region) .map_err(VfioPciError::MapRegionGuest)?; } // Update the region with memory mapped info. region.mem_slot = Some(slot); region.host_addr = Some(host_addr as u64); region.mmap_size = Some(mmap_size as usize); } } Ok(()) } pub fn unmap_mmio_regions(&mut self) { for region in self.mmio_regions.iter() { if let (Some(host_addr), Some(mmap_size), Some(mem_slot)) = (region.host_addr, region.mmap_size, region.mem_slot) { let (mmap_offset, _) = self.device.get_region_mmap(region.index); // Remove region from KVM let kvm_region = kvm_userspace_memory_region { slot: mem_slot, guest_phys_addr: region.start.raw_value() + mmap_offset, memory_size: 0, userspace_addr: host_addr, flags: 0, }; // Safe because the guest regions are guaranteed not to overlap. if let Err(e) = unsafe { self.vm_fd.set_user_memory_region(kvm_region) } { error!( "Could not remove the userspace memory region from KVM: {}", e ); } let ret = unsafe { libc::munmap(host_addr as *mut libc::c_void, mmap_size) }; if ret != 0 { error!( "Could not unmap region {}, error:{}", region.index, io::Error::last_os_error() ); } } } } } impl Drop for VfioPciDevice { fn drop(&mut self) { self.unmap_mmio_regions(); if let Some(msix) = &self.interrupt.msix { if msix.bar.enabled() && self.device.disable_msix().is_err() { error!("Could not disable MSI-X"); } } if let Some(msi) = &self.interrupt.msi { if msi.cfg.enabled() && self.device.disable_msi().is_err() { error!("Could not disable MSI"); } } if self.device.unset_dma_map().is_err() { error!("failed to remove all guest memory regions from iommu table"); } } } impl BusDevice for VfioPciDevice { fn read(&mut self, base: u64, offset: u64, data: &mut [u8]) { self.read_bar(base, offset, data) } fn write(&mut self, base: u64, offset: u64, data: &[u8]) { self.write_bar(base, offset, data) } } // First BAR offset in the PCI config space. const PCI_CONFIG_BAR_OFFSET: u32 = 0x10; // Capability register offset in the PCI config space. const PCI_CONFIG_CAPABILITY_OFFSET: u32 = 0x34; // IO BAR when first BAR bit is 1. const PCI_CONFIG_IO_BAR: u32 = 0x1; // Memory BAR flags (lower 4 bits). const PCI_CONFIG_MEMORY_BAR_FLAG_MASK: u32 = 0xf; // 64-bit memory bar flag. const PCI_CONFIG_MEMORY_BAR_64BIT: u32 = 0x4; // PCI config register size (4 bytes). const PCI_CONFIG_REGISTER_SIZE: usize = 4; // Number of BARs for a PCI device const BAR_NUMS: usize = 6; // PCI Header Type register index const PCI_HEADER_TYPE_REG_INDEX: usize = 3; // First BAR register index const PCI_CONFIG_BAR0_INDEX: usize = 4; // PCI ROM expansion BAR register index const PCI_ROM_EXP_BAR_INDEX: usize = 12; // PCI interrupt pin and line register index const PCI_INTX_REG_INDEX: usize = 15; impl PciDevice for VfioPciDevice { fn allocate_bars( &mut self, allocator: &mut SystemAllocator, ) -> std::result::Result<Vec<(GuestAddress, GuestUsize, PciBarRegionType)>, PciDeviceError> { let mut ranges = Vec::new(); let mut bar_id = VFIO_PCI_BAR0_REGION_INDEX as u32; // Going through all regular regions to compute the BAR size. // We're not saving the BAR address to restore it, because we // are going to allocate a guest address for each BAR and write // that new address back. while bar_id < VFIO_PCI_CONFIG_REGION_INDEX { let mut lsb_size: u32 = 0xffff_ffff; let mut msb_size = 0; let mut region_size: u64; let bar_addr: GuestAddress; // Read the BAR size (Starts by all 1s to the BAR) let bar_offset = if bar_id == VFIO_PCI_ROM_REGION_INDEX { (PCI_ROM_EXP_BAR_INDEX * 4) as u32 } else { PCI_CONFIG_BAR_OFFSET + bar_id * 4 }; self.vfio_pci_configuration .write_config_dword(lsb_size, bar_offset); lsb_size = self.vfio_pci_configuration.read_config_dword(bar_offset); // We've just read the BAR size back. Or at least its LSB. let lsb_flag = lsb_size & PCI_CONFIG_MEMORY_BAR_FLAG_MASK; if lsb_size == 0 { bar_id += 1; continue; } // Is this an IO BAR? let io_bar = if bar_id != VFIO_PCI_ROM_REGION_INDEX { match lsb_flag & PCI_CONFIG_IO_BAR { PCI_CONFIG_IO_BAR => true, _ => false, } } else { false }; // Is this a 64-bit BAR? let is_64bit_bar = if bar_id != VFIO_PCI_ROM_REGION_INDEX { match lsb_flag & PCI_CONFIG_MEMORY_BAR_64BIT { PCI_CONFIG_MEMORY_BAR_64BIT => true, _ => false, } } else { false }; // By default, the region type is 32 bits memory BAR. let mut region_type = PciBarRegionType::Memory32BitRegion; if io_bar { // IO BAR region_type = PciBarRegionType::IORegion; // Clear first bit. lsb_size &= 0xffff_fffc; // Find the first bit that's set to 1. let first_bit = lsb_size.trailing_zeros(); region_size = 2u64.pow(first_bit); // We need to allocate a guest PIO address range for that BAR. // The address needs to be 4 bytes aligned. bar_addr = allocator .allocate_io_addresses(None, region_size, Some(0x4)) .ok_or_else(|| PciDeviceError::IoAllocationFailed(region_size))?; } else { if is_64bit_bar { // 64 bits Memory BAR region_type = PciBarRegionType::Memory64BitRegion; msb_size = 0xffff_ffff; let msb_bar_offset: u32 = PCI_CONFIG_BAR_OFFSET + (bar_id + 1) * 4; self.vfio_pci_configuration .write_config_dword(msb_size, msb_bar_offset); msb_size = self .vfio_pci_configuration .read_config_dword(msb_bar_offset); } // Clear the first four bytes from our LSB. lsb_size &= 0xffff_fff0; region_size = u64::from(msb_size); region_size <<= 32; region_size |= u64::from(lsb_size); // Find the first that's set to 1. let first_bit = region_size.trailing_zeros(); region_size = 2u64.pow(first_bit); // We need to allocate a guest MMIO address range for that BAR. // In case the BAR is mappable directly, this means it might be // set as KVM user memory region, which expects to deal with 4K // pages. Therefore, the aligment has to be set accordingly. let bar_alignment = if (bar_id == VFIO_PCI_ROM_REGION_INDEX) || (self.device.get_region_flags(bar_id) & VFIO_REGION_INFO_FLAG_MMAP != 0) { // 4K alignment 0x1000 } else { // Default 16 bytes alignment 0x10 }; if is_64bit_bar { bar_addr = allocator .allocate_mmio_addresses(None, region_size, Some(bar_alignment)) .ok_or_else(|| PciDeviceError::IoAllocationFailed(region_size))?; } else { bar_addr = allocator .allocate_mmio_hole_addresses(None, region_size, Some(bar_alignment)) .ok_or_else(|| PciDeviceError::IoAllocationFailed(region_size))?; } } let reg_idx = if bar_id == VFIO_PCI_ROM_REGION_INDEX { PCI_ROM_EXP_BAR_INDEX } else { bar_id as usize }; // We can now build our BAR configuration block. let config = PciBarConfiguration::default() .set_register_index(reg_idx) .set_address(bar_addr.raw_value()) .set_size(region_size) .set_region_type(region_type); if bar_id == VFIO_PCI_ROM_REGION_INDEX { self.configuration .add_pci_rom_bar(&config, lsb_flag & 0x1) .map_err(|e| PciDeviceError::IoRegistrationFailed(bar_addr.raw_value(), e))?; } else { self.configuration .add_pci_bar(&config) .map_err(|e| PciDeviceError::IoRegistrationFailed(bar_addr.raw_value(), e))?; } ranges.push((bar_addr, region_size, region_type)); self.mmio_regions.push(MmioRegion { start: bar_addr, length: region_size, type_: region_type, index: bar_id as u32, mem_slot: None, host_addr: None, mmap_size: None, }); bar_id += 1; if is_64bit_bar { bar_id += 1; } } if self.device.setup_dma_map().is_err() { error!("failed to add all guest memory regions into iommu table"); } Ok(ranges) } fn free_bars( &mut self, allocator: &mut SystemAllocator, ) -> std::result::Result<(), PciDeviceError> { for region in self.mmio_regions.iter() { match region.type_ { PciBarRegionType::IORegion => { allocator.free_io_addresses(region.start, region.length); } PciBarRegionType::Memory32BitRegion => { allocator.free_mmio_hole_addresses(region.start, region.length); } PciBarRegionType::Memory64BitRegion => { allocator.free_mmio_addresses(region.start, region.length); } } } Ok(()) } fn write_config_register(&mut self, reg_idx: usize, offset: u64, data: &[u8]) { // When the guest wants to write to a BAR, we trap it into // our local configuration space. We're not reprogramming // VFIO device. if (reg_idx >= PCI_CONFIG_BAR0_INDEX && reg_idx < PCI_CONFIG_BAR0_INDEX + BAR_NUMS) || reg_idx == PCI_ROM_EXP_BAR_INDEX { // We keep our local cache updated with the BARs. // We'll read it back from there when the guest is asking // for BARs (see read_config_register()). return self .configuration .write_config_register(reg_idx, offset, data); } let reg = (reg_idx * PCI_CONFIG_REGISTER_SIZE) as u64; // If the MSI or MSI-X capabilities are accessed, we need to // update our local cache accordingly. // Depending on how the capabilities are modified, this could // trigger a VFIO MSI or MSI-X toggle. if let Some((cap_id, cap_base)) = self.interrupt.accessed(reg) { let cap_offset: u64 = reg - cap_base + offset; match cap_id { PciCapabilityID::MessageSignalledInterrupts => { if let Err(e) = self.update_msi_capabilities(cap_offset, data) { error!("Could not update MSI capabilities: {}", e); } } PciCapabilityID::MSIX => { if let Err(e) = self.update_msix_capabilities(cap_offset, data) { error!("Could not update MSI-X capabilities: {}", e); } } _ => {} } } // Make sure to write to the device's PCI config space after MSI/MSI-X // interrupts have been enabled/disabled. In case of MSI, when the // interrupts are enabled through VFIO (using VFIO_DEVICE_SET_IRQS), // the MSI Enable bit in the MSI capability structure found in the PCI // config space is disabled by default. That's why when the guest is // enabling this bit, we first need to enable the MSI interrupts with // VFIO through VFIO_DEVICE_SET_IRQS ioctl, and only after we can write // to the device region to update the MSI Enable bit. self.device .region_write(VFIO_PCI_CONFIG_REGION_INDEX, data, reg + offset); } fn read_config_register(&mut self, reg_idx: usize) -> u32 { // When reading the BARs, we trap it and return what comes // from our local configuration space. We want the guest to // use that and not the VFIO device BARs as it does not map // with the guest address space. if (reg_idx >= PCI_CONFIG_BAR0_INDEX && reg_idx < PCI_CONFIG_BAR0_INDEX + BAR_NUMS) || reg_idx == PCI_ROM_EXP_BAR_INDEX { return self.configuration.read_reg(reg_idx); } // Since we don't support INTx (only MSI and MSI-X), we should not // expose an invalid Interrupt Pin to the guest. By using a specific // mask in case the register being read correspond to the interrupt // register, this code makes sure to always expose an Interrupt Pin // value of 0, which stands for no interrupt pin support. // // Since we don't support passing multi-functions devices, we should // mask the multi-function bit, bit 7 of the Header Type byte on the // register 3. let mask = if reg_idx == PCI_INTX_REG_INDEX { 0xffff_00ff } else if reg_idx == PCI_HEADER_TYPE_REG_INDEX { 0xff7f_ffff } else { 0xffff_ffff }; // The config register read comes from the VFIO device itself. self.vfio_pci_configuration .read_config_dword((reg_idx * 4) as u32) & mask } fn detect_bar_reprogramming( &mut self, reg_idx: usize, data: &[u8], ) -> Option<BarReprogrammingParams> { self.configuration.detect_bar_reprogramming(reg_idx, data) } fn read_bar(&mut self, base: u64, offset: u64, data: &mut [u8]) { let addr = base + offset; if let Some(region) = self.find_region(addr) { let offset = addr - region.start.raw_value(); if self.interrupt.msix_table_accessed(region.index, offset) { self.interrupt.msix_read_table(offset, data); } else { self.device.region_read(region.index, data, offset); } } } fn write_bar(&mut self, base: u64, offset: u64, data: &[u8]) { let addr = base + offset; if let Some(region) = self.find_region(addr) { let offset = addr - region.start.raw_value(); // If the MSI-X table is written to, we need to update our cache. if self.interrupt.msix_table_accessed(region.index, offset) { self.interrupt.msix_write_table(offset, data); } else { self.device.region_write(region.index, data, offset); } } } fn move_bar(&mut self, old_base: u64, new_base: u64) -> result::Result<(), io::Error> { for region in self.mmio_regions.iter_mut() { if region.start.raw_value() == old_base { region.start = GuestAddress(new_base); if let Some(mem_slot) = region.mem_slot { if let Some(host_addr) = region.host_addr { let (mmap_offset, mmap_size) = self.device.get_region_mmap(region.index); // Remove old region from KVM let old_mem_region = kvm_userspace_memory_region { slot: mem_slot, guest_phys_addr: old_base + mmap_offset, memory_size: 0, userspace_addr: host_addr, flags: 0, }; // Safe because the guest regions are guaranteed not to overlap. unsafe { self.vm_fd .set_user_memory_region(old_mem_region) .map_err(|e| io::Error::from_raw_os_error(e.errno()))?; } // Insert new region to KVM let new_mem_region = kvm_userspace_memory_region { slot: mem_slot, guest_phys_addr: new_base + mmap_offset, memory_size: mmap_size as u64, userspace_addr: host_addr, flags: 0, }; // Safe because the guest regions are guaranteed not to overlap. unsafe { self.vm_fd .set_user_memory_region(new_mem_region) .map_err(|e| io::Error::from_raw_os_error(e.errno()))?; } } } } } Ok(()) } fn as_any(&mut self) -> &mut dyn Any { self } }
35.154889
99
0.540576
d56cfb15eebd97502496a531836af2ffca0118f9
14,812
use crate::common::{AluminaError, ArenaAllocatable, CodeErrorKind, WithSpanDuringParsing}; use crate::ast::{AstCtx, Attribute, ItemP}; use crate::global_ctx::GlobalCtx; use crate::name_resolution::scope::{NamedItemKind, Scope, ScopeType}; use crate::parser::{AluminaVisitor, ParseCtx}; use std::result::Result; use tree_sitter::Node; use crate::visitors::{AttributeVisitor, UseClauseVisitor, VisitorExt}; use super::path::Path; use super::scope::NamedItem; pub struct FirstPassVisitor<'ast, 'src> { global_ctx: GlobalCtx, ast: &'ast AstCtx<'ast>, scope: Scope<'ast, 'src>, code: &'src ParseCtx<'src>, enum_item: Option<ItemP<'ast>>, main_module_path: Option<Path<'ast>>, main_candidate: Option<ItemP<'ast>>, } impl<'ast, 'src> FirstPassVisitor<'ast, 'src> { pub fn new(global_ctx: GlobalCtx, ast: &'ast AstCtx<'ast>, scope: Scope<'ast, 'src>) -> Self { Self { global_ctx, ast, code: scope .code() .expect("cannot run on scope without parse context"), scope, enum_item: None, main_module_path: None, main_candidate: None, } } pub fn with_main( global_ctx: GlobalCtx, ast: &'ast AstCtx<'ast>, scope: Scope<'ast, 'src>, ) -> Self { Self { global_ctx, ast, code: scope .code() .expect("cannot run on scope without parse context"), main_module_path: Some(scope.path()), scope, enum_item: None, main_candidate: None, } } pub fn main_candidate(&self) -> Option<ItemP<'ast>> { self.main_candidate } } macro_rules! with_child_scope { ($self:ident, $scope:expr, $body:block) => { let previous_scope = std::mem::replace(&mut $self.scope, $scope); $body $self.scope = previous_scope; }; } impl<'ast, 'src> FirstPassVisitor<'ast, 'src> { fn parse_name(&self, node: Node<'src>) -> &'ast str { let name_node = node.child_by_field_name("name").unwrap(); self.code.node_text(name_node).alloc_on(self.ast) } } macro_rules! parse_attributes { (@, $self:expr, $node:expr, $item:expr) => { match AttributeVisitor::parse_attributes($self.global_ctx.clone(), $self.ast, $self.scope.clone(), $node, $item)? { Some(attributes) => attributes, None => return Ok(()), } }; ($self:expr, $node:expr, $item:expr) => { parse_attributes!(@, $self, $node, Some($item)) }; ($self:expr, $node:expr) => { parse_attributes!(@, $self, $node, None) }; } pub(crate) use parse_attributes; impl<'ast, 'src> AluminaVisitor<'src> for FirstPassVisitor<'ast, 'src> { type ReturnType = Result<(), AluminaError>; fn visit_source_file(&mut self, node: Node<'src>) -> Self::ReturnType { self.visit_children(node) } fn visit_mod_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Module, name); self.scope .add_item( Some(name), NamedItem::new(NamedItemKind::Module(child_scope.clone()), attributes), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { self.visit_children_by_field(node, "body")?; }); Ok(()) } fn visit_top_level_block(&mut self, node: Node<'src>) -> Self::ReturnType { let _ = parse_attributes!(self, node); self.visit_children_by_field(node, "items") } fn visit_protocol_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Protocol, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::Protocol(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } self.visit_children_by_field(node, "body")?; }); Ok(()) } fn visit_struct_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::StructLike, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::Type(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } self.visit_children_by_field(node, "body")?; }); Ok(()) } fn visit_impl_block(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Impl, name); self.scope .add_item( Some(name), NamedItem::new(NamedItemKind::Impl(node, child_scope.clone()), attributes), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } self.visit_children_by_field(node, "body")?; }); Ok(()) } fn visit_enum_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Enum, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::Type(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { self.enum_item = Some(item); self.visit_children_by_field(node, "body")?; }); Ok(()) } fn visit_enum_item(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::EnumMember(self.enum_item.unwrap(), self.ast.make_id(), node), attributes, ), ) .with_span_from(&self.scope, node)?; Ok(()) } fn visit_struct_field(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new(NamedItemKind::Field(node), attributes), ) .with_span_from(&self.scope, node)?; Ok(()) } fn visit_function_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); if let Some(path) = self.main_module_path.as_ref() { if self.global_ctx.cfg("test").is_some() { if attributes.contains(&Attribute::TestMain) && self.main_candidate.replace(item).is_some() { return Err(CodeErrorKind::MultipleMainFunctions) .with_span_from(&self.scope, node); } } else if &self.scope.path() == path && name == "main" { if self.main_candidate.replace(item).is_some() { return Err(CodeErrorKind::MultipleMainFunctions) .with_span_from(&self.scope, node); } } } let child_scope = self.scope.named_child(ScopeType::Function, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::Function(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } self.visit_children_by_field(node, "parameters")?; }); Ok(()) } fn visit_type_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Function, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::TypeDef(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } }); Ok(()) } fn visit_mixin(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let child_scope = self.scope.anonymous_child(ScopeType::Function); self.scope .add_item( None, NamedItem::new(NamedItemKind::Mixin(node, child_scope.clone()), attributes), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { if let Some(f) = node.child_by_field_name("type_arguments") { self.visit(f)?; } }); Ok(()) } fn visit_static_declaration(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new(NamedItemKind::Static(item, node), attributes), ) .with_span_from(&self.scope, node)?; Ok(()) } fn visit_generic_argument_list(&mut self, node: Node<'src>) -> Self::ReturnType { let mut cursor = node.walk(); for argument in node.children_by_field_name("argument", &mut cursor) { let name = self .code .node_text(argument.child_by_field_name("placeholder").unwrap()) .alloc_on(self.ast); self.scope .add_item( Some(name), NamedItem::new_default(NamedItemKind::Placeholder( self.ast.make_id(), argument, )), ) .with_span_from(&self.scope, node)?; } Ok(()) } fn visit_parameter(&mut self, node: Node<'src>) -> Self::ReturnType { let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new_default(NamedItemKind::Parameter(self.ast.make_id(), node)), ) .with_span_from(&self.scope, node)?; Ok(()) } fn visit_macro_parameter(&mut self, node: Node<'src>) -> Self::ReturnType { let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new_default(NamedItemKind::MacroParameter( self.ast.make_id(), node.child_by_field_name("et_cetera").is_some(), )), ) .with_span_from(&self.scope, node)?; Ok(()) } fn visit_parameter_list(&mut self, node: Node<'src>) -> Self::ReturnType { self.visit_children_by_field(node, "parameter") } fn visit_macro_parameter_list(&mut self, node: Node<'src>) -> Self::ReturnType { self.visit_children_by_field(node, "parameter") } fn visit_use_declaration(&mut self, node: Node<'src>) -> Self::ReturnType { let attributes = parse_attributes!(self, node); let mut visitor = UseClauseVisitor::new(self.ast, self.scope.clone(), attributes, false); visitor.visit(node.child_by_field_name("argument").unwrap())?; Ok(()) } fn visit_macro_definition(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); let child_scope = self.scope.named_child(ScopeType::Macro, name); self.scope .add_item( Some(name), NamedItem::new( NamedItemKind::Macro(item, node, child_scope.clone()), attributes, ), ) .with_span_from(&self.scope, node)?; with_child_scope!(self, child_scope, { self.visit_children_by_field(node, "parameters")?; }); Ok(()) } fn visit_const_declaration(&mut self, node: Node<'src>) -> Self::ReturnType { let item = self.ast.make_symbol(); let attributes = parse_attributes!(self, node, item); let name = self.parse_name(node); self.scope .add_item( Some(name), NamedItem::new(NamedItemKind::Const(item, node), attributes), ) .with_span_from(&self.scope, node)?; Ok(()) } }
31.183158
123
0.53855
bbb74928052df396570772b00ec1fe54ba83affb
408
//! Encoding tables for RISC-V. use super::registers::*; use ir; use isa; use isa::constraints::*; use isa::enc_tables::*; use isa::encoding::{base_size, RecipeSizing}; // Include the generated encoding tables: // - `LEVEL1_RV32` // - `LEVEL1_RV64` // - `LEVEL2` // - `ENCLIST` // - `INFO` include!(concat!(env!("OUT_DIR"), "/encoding-riscv.rs")); include!(concat!(env!("OUT_DIR"), "/legalize-riscv.rs"));
22.666667
57
0.651961
ccfbe9d6ae0c54f4b2282b2a9bfee870fd733739
430
/// A JSON Patch "remove" operation. /// /// Removes the value at the target location. /// /// [More Info](https://tools.ietf.org/html/rfc6902#section-4.2) #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] pub struct OpRemove { /// A string containing a JSON-Pointer value that references a location within /// the target document (the "target location") where the operation is /// performed. pub path: String, }
33.076923
80
0.706977
0e603bc7df1044997f00083557d456ba5953774f
9,287
#![crate_name = "uu_dircolors"] // This file is part of the uutils coreutils package. // // (c) Jian Zeng <anonymousknight96@gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // extern crate glob; #[macro_use] extern crate uucore; use std::fs::File; use std::io::{BufRead, BufReader}; use std::borrow::Borrow; use std::env; static SYNTAX: &'static str = "[OPTION]... [FILE]"; static SUMMARY: &'static str = "Output commands to set the LS_COLORS environment variable."; static LONG_HELP: &'static str = " If FILE is specified, read it to determine which colors to use for which file types and extensions. Otherwise, a precompiled database is used. For details on the format of these files, run 'dircolors --print-database' "; mod colors; use colors::INTERNAL_DB; #[derive(PartialEq, Debug)] pub enum OutputFmt { Shell, CShell, Unknown, } pub fn guess_syntax() -> OutputFmt { use std::path::Path; match env::var("SHELL") { Ok(ref s) if !s.is_empty() => { let shell_path: &Path = s.as_ref(); if let Some(name) = shell_path.file_name() { if name == "csh" || name == "tcsh" { OutputFmt::CShell } else { OutputFmt::Shell } } else { OutputFmt::Shell } } _ => OutputFmt::Unknown, } } pub fn uumain(args: Vec<String>) -> i32 { let matches = new_coreopts!(SYNTAX, SUMMARY, LONG_HELP) .optflag("b", "sh", "output Bourne shell code to set LS_COLORS") .optflag("", "bourne-shell", "output Bourne shell code to set LS_COLORS") .optflag("c", "csh", "output C shell code to set LS_COLORS") .optflag("", "c-shell", "output C shell code to set LS_COLORS") .optflag("p", "print-database", "print the byte counts") .parse(args); if (matches.opt_present("csh") || matches.opt_present("c-shell") || matches.opt_present("sh") || matches.opt_present("bourne-shell")) && matches.opt_present("print-database") { disp_err!("the options to output dircolors' internal database and\nto select a shell \ syntax are mutually exclusive"); return 1; } if matches.opt_present("print-database") { if !matches.free.is_empty() { disp_err!("extra operand ‘{}’\nfile operands cannot be combined with \ --print-database (-p)", matches.free[0]); return 1; } println!("{}", INTERNAL_DB); return 0; } let mut out_format = OutputFmt::Unknown; if matches.opt_present("csh") || matches.opt_present("c-shell") { out_format = OutputFmt::CShell; } else if matches.opt_present("sh") || matches.opt_present("bourne-shell") { out_format = OutputFmt::Shell; } if out_format == OutputFmt::Unknown { match guess_syntax() { OutputFmt::Unknown => { show_info!("no SHELL environment variable, and no shell type option given"); return 1; } fmt => out_format = fmt, } } let result; if matches.free.is_empty() { result = parse(INTERNAL_DB.lines(), out_format, "") } else { if matches.free.len() > 1 { disp_err!("extra operand ‘{}’", matches.free[1]); return 1; } match File::open(matches.free[0].as_str()) { Ok(f) => { let fin = BufReader::new(f); result = parse(fin.lines().filter_map(|l| l.ok()), out_format, matches.free[0].as_str()) } Err(e) => { show_info!("{}: {}", matches.free[0], e); return 1; } } } match result { Ok(s) => { println!("{}", s); 0 } Err(s) => { show_info!("{}", s); 1 } } } pub trait StrUtils { /// Remove comments and trim whitespace fn purify(&self) -> &Self; /// Like split_whitespace() but only produce 2 components fn split_two(&self) -> (&str, &str); fn fnmatch(&self, pattern: &str) -> bool; } impl StrUtils for str { fn purify(&self) -> &Self { let mut line = self; for (n, c) in self.chars().enumerate() { if c != '#' { continue; } // Ignore if '#' is at the beginning of line if n == 0 { line = &self[..0]; break; } // Ignore the content after '#' // only if it is preceded by at least one whitespace if self.chars().nth(n - 1).unwrap().is_whitespace() { line = &self[..n]; } } line.trim() } fn split_two(&self) -> (&str, &str) { if let Some(b) = self.find(char::is_whitespace) { let key = &self[..b]; if let Some(e) = self[b..].find(|c: char| !c.is_whitespace()) { (key, &self[b + e..]) } else { (key, "") } } else { ("", "") } } fn fnmatch(&self, pat: &str) -> bool { pat.parse::<glob::Pattern>().unwrap().matches(self) } } #[derive(PartialEq)] enum ParseState { Global, Matched, Continue, Pass, } use std::collections::HashMap; fn parse<T>(lines: T, fmt: OutputFmt, fp: &str) -> Result<String, String> where T: IntoIterator, T::Item: Borrow<str> { // 1440 > $(dircolors | wc -m) let mut result = String::with_capacity(1440); match fmt { OutputFmt::Shell => result.push_str("LS_COLORS='"), OutputFmt::CShell => result.push_str("setenv LS_COLORS '"), _ => unreachable!(), } let mut table: HashMap<&str, &str> = HashMap::with_capacity(48); table.insert("normal", "no"); table.insert("norm", "no"); table.insert("file", "fi"); table.insert("reset", "rs"); table.insert("dir", "di"); table.insert("lnk", "ln"); table.insert("link", "ln"); table.insert("symlink", "ln"); table.insert("orphan", "or"); table.insert("missing", "mi"); table.insert("fifo", "pi"); table.insert("pipe", "pi"); table.insert("sock", "so"); table.insert("blk", "bd"); table.insert("block", "bd"); table.insert("chr", "cd"); table.insert("char", "cd"); table.insert("door", "do"); table.insert("exec", "ex"); table.insert("left", "lc"); table.insert("leftcode", "lc"); table.insert("right", "rc"); table.insert("rightcode", "rc"); table.insert("end", "ec"); table.insert("endcode", "ec"); table.insert("suid", "su"); table.insert("setuid", "su"); table.insert("sgid", "sg"); table.insert("setgid", "sg"); table.insert("sticky", "st"); table.insert("other_writable", "ow"); table.insert("owr", "ow"); table.insert("sticky_other_writable", "tw"); table.insert("owt", "tw"); table.insert("capability", "ca"); table.insert("multihardlink", "mh"); table.insert("clrtoeol", "cl"); let term = env::var("TERM").unwrap_or("none".to_owned()); let term = term.as_str(); let mut state = ParseState::Global; for (num, line) in lines.into_iter().enumerate() { let num = num + 1; let line = line.borrow().purify(); if line.is_empty() { continue; } let (key, val) = line.split_two(); if val.is_empty() { return Err(format!("{}:{}: invalid line; missing second token", fp, num)); } let lower = key.to_lowercase(); if lower == "term" { if term.fnmatch(val) { state = ParseState::Matched; } else if state != ParseState::Matched { state = ParseState::Pass; } } else { if state == ParseState::Matched { // prevent subsequent mismatched TERM from // cancelling the input state = ParseState::Continue; } if state != ParseState::Pass { if key.starts_with(".") { result.push_str(format!("*{}={}:", key, val).as_str()); } else if key.starts_with("*") { result.push_str(format!("{}={}:", key, val).as_str()); } else if lower == "options" || lower == "color" || lower == "eightbit" { // Slackware only. Ignore } else { if let Some(s) = table.get(lower.as_str()) { result.push_str(format!("{}={}:", s, val).as_str()); } else { return Err(format!("{}:{}: unrecognized keyword {}", fp, num, key)); } } } } } match fmt { OutputFmt::Shell => result.push_str("';\nexport LS_COLORS"), OutputFmt::CShell => result.push('\''), _ => unreachable!(), } Ok(result) }
30.751656
94
0.510283
1cbcd1644f51c6ea7fc820a926275cbcf3b89859
46,699
#![deny(missing_docs)] //! A Conductor is a dynamically changing group of [Cell]s. //! //! A Conductor can be managed: //! - externally, via a [AppInterfaceApi] //! - from within a [Cell], via [CellConductorApi] //! //! In normal use cases, a single Holochain user runs a single Conductor in a single process. //! However, there's no reason we can't have multiple Conductors in a single process, simulating multiple //! users in a testing environment. use super::api::RealAdminInterfaceApi; use super::api::RealAppInterfaceApi; use super::config::AdminInterfaceConfig; use super::config::InterfaceDriver; use super::dna_store::DnaDefBuf; use super::dna_store::RealDnaStore; use super::entry_def_store::get_entry_defs; use super::entry_def_store::EntryDefBuf; use super::error::ConductorError; use super::error::CreateAppError; use super::handle::ConductorHandleImpl; use super::interface::error::InterfaceResult; use super::interface::websocket::spawn_admin_interface_task; use super::interface::websocket::spawn_app_interface_task; use super::interface::websocket::spawn_websocket_listener; use super::interface::websocket::SIGNAL_BUFFER_SIZE; use super::interface::SignalBroadcaster; use super::manager::keep_alive_task; use super::manager::spawn_task_manager; use super::manager::ManagedTaskAdd; use super::manager::ManagedTaskHandle; use super::manager::TaskManagerRunHandle; use super::p2p_store; use super::p2p_store::all_agent_infos; use super::p2p_store::get_single_agent_info; use super::p2p_store::inject_agent_infos; use super::paths::EnvironmentRootPath; use super::state::AppInterfaceId; use super::state::ConductorState; use super::CellError; use super::{api::CellConductorApi, state::AppInterfaceConfig}; use super::{api::CellConductorApiT, interface::AppInterfaceRuntime}; use crate::conductor::api::error::ConductorApiResult; use crate::conductor::cell::Cell; use crate::conductor::config::ConductorConfig; use crate::conductor::error::ConductorResult; use crate::conductor::handle::ConductorHandle; use crate::core::queue_consumer::InitialQueueTriggers; use crate::core::workflow::integrate_dht_ops_workflow; pub use builder::*; use fallible_iterator::FallibleIterator; use futures::future; use futures::future::TryFutureExt; use futures::stream::StreamExt; use holo_hash::DnaHash; use holochain_conductor_api::JsonDump; use holochain_keystore::lair_keystore::spawn_lair_keystore; use holochain_keystore::test_keystore::spawn_test_keystore; use holochain_keystore::KeystoreSender; use holochain_keystore::KeystoreSenderExt; use holochain_lmdb::buffer::BufferedStore; use holochain_lmdb::buffer::KvStore; use holochain_lmdb::buffer::KvStoreT; use holochain_lmdb::db; use holochain_lmdb::env::EnvironmentKind; use holochain_lmdb::env::EnvironmentWrite; use holochain_lmdb::env::ReadManager; use holochain_lmdb::exports::SingleStore; use holochain_lmdb::fresh_reader; use holochain_lmdb::prelude::*; use holochain_state::source_chain::SourceChainBuf; use holochain_state::wasm::WasmBuf; use holochain_types::prelude::*; use kitsune_p2p::agent_store::AgentInfoSigned; use std::collections::HashMap; use std::sync::Arc; use tokio::sync::mpsc; use tokio::sync::RwLock; use tracing::*; #[cfg(any(test, feature = "test_utils"))] use super::handle::MockConductorHandleT; /// Conductor-specific Cell state, this can probably be stored in a database. /// Hypothesis: If nothing remains in this struct, then the Conductor state is /// essentially immutable, and perhaps we just throw it out and make a new one /// when we need to load new config, etc. pub struct CellState { /// Whether or not we should call any methods on the cell _active: bool, } /// An [Cell] tracked by a Conductor, along with some [CellState] struct CellItem<CA> where CA: CellConductorApiT, { cell: Arc<Cell<CA>>, _state: CellState, } pub type StopBroadcaster = tokio::sync::broadcast::Sender<()>; pub type StopReceiver = tokio::sync::broadcast::Receiver<()>; /// A Conductor is a group of [Cell]s pub struct Conductor<DS = RealDnaStore, CA = CellConductorApi> where DS: DnaStore, CA: CellConductorApiT, { /// The collection of cells associated with this Conductor cells: HashMap<CellId, CellItem<CA>>, /// The LMDB environment for persisting state related to this Conductor env: EnvironmentWrite, /// An LMDB environment for storing wasm wasm_env: EnvironmentWrite, /// The LMDB environment for storing AgentInfoSigned p2p_env: EnvironmentWrite, /// The database for persisting [ConductorState] state_db: ConductorStateDb, /// Set to true when `conductor.shutdown()` has been called, so that other /// tasks can check on the shutdown status shutting_down: bool, /// The admin websocket ports this conductor has open. /// This exists so that we can run tests and bind to port 0, and find out /// the dynamically allocated port later. admin_websocket_ports: Vec<u16>, /// Collection app interface data, keyed by id app_interfaces: HashMap<AppInterfaceId, AppInterfaceRuntime>, /// Channel on which to send info about tasks we want to manage managed_task_add_sender: mpsc::Sender<ManagedTaskAdd>, /// By sending on this channel, managed_task_stop_broadcaster: StopBroadcaster, /// The main task join handle to await on. /// The conductor is intended to live as long as this task does. task_manager_run_handle: Option<TaskManagerRunHandle>, /// Placeholder for what will be the real DNA/Wasm cache dna_store: DS, /// Access to private keys for signing and encryption. keystore: KeystoreSender, /// The root environment directory where all environments are created root_env_dir: EnvironmentRootPath, /// Handle to the network actor. holochain_p2p: holochain_p2p::HolochainP2pRef, } impl Conductor { /// Create a conductor builder pub fn builder() -> ConductorBuilder { ConductorBuilder::new() } } //----------------------------------------------------------------------------- // Public methods //----------------------------------------------------------------------------- impl<DS> Conductor<DS> where DS: DnaStore + 'static, { /// Returns a port which is guaranteed to have a websocket listener with an Admin interface /// on it. Useful for specifying port 0 and letting the OS choose a free port. pub fn get_arbitrary_admin_websocket_port(&self) -> Option<u16> { self.admin_websocket_ports.get(0).copied() } } //----------------------------------------------------------------------------- /// Methods used by the [ConductorHandle] //----------------------------------------------------------------------------- impl<DS> Conductor<DS> where DS: DnaStore + 'static, { pub(super) fn cell_by_id(&self, cell_id: &CellId) -> ConductorResult<Arc<Cell>> { let item = self .cells .get(cell_id) .ok_or_else(|| ConductorError::CellMissing(cell_id.clone()))?; Ok(item.cell.clone()) } /// A gate to put at the top of public functions to ensure that work is not /// attempted after a shutdown has been issued pub(super) fn check_running(&self) -> ConductorResult<()> { if self.shutting_down { Err(ConductorError::ShuttingDown) } else { Ok(()) } } pub(super) fn dna_store(&self) -> &DS { &self.dna_store } pub(super) fn dna_store_mut(&mut self) -> &mut DS { &mut self.dna_store } /// Broadcasts the shutdown signal to all managed tasks. /// To actually wait for these tasks to complete, be sure to /// `take_shutdown_handle` to await for completion. pub(super) fn shutdown(&mut self) { self.shutting_down = true; tracing::info!( "Sending shutdown signal to {} managed tasks.", self.managed_task_stop_broadcaster.receiver_count(), ); self.managed_task_stop_broadcaster .send(()) .map(|_| ()) .unwrap_or_else(|e| { error!(?e, "Couldn't broadcast stop signal to managed tasks!"); }) } /// Return the handle which waits for the task manager task to complete pub(super) fn take_shutdown_handle(&mut self) -> Option<TaskManagerRunHandle> { self.task_manager_run_handle.take() } /// Spawn all admin interface tasks, register them with the TaskManager, /// and modify the conductor accordingly, based on the config passed in pub(super) async fn add_admin_interfaces_via_handle( &mut self, configs: Vec<AdminInterfaceConfig>, handle: ConductorHandle, ) -> ConductorResult<()> where DS: DnaStore + 'static, { let admin_api = RealAdminInterfaceApi::new(handle); let stop_tx = self.managed_task_stop_broadcaster.clone(); // Closure to process each admin config item let spawn_from_config = |AdminInterfaceConfig { driver, .. }| { let admin_api = admin_api.clone(); let stop_tx = stop_tx.clone(); async move { match driver { InterfaceDriver::Websocket { port } => { let (listener_handle, listener) = spawn_websocket_listener(port).await?; let port = listener_handle.local_addr().port().unwrap_or(port); let handle: ManagedTaskHandle = spawn_admin_interface_task( listener_handle, listener, admin_api.clone(), stop_tx.subscribe(), )?; InterfaceResult::Ok((port, handle)) } } } }; // spawn interface tasks, collect their JoinHandles, // panic on errors. let handles: Result<Vec<_>, _> = future::join_all(configs.into_iter().map(spawn_from_config)) .await .into_iter() .collect(); // Exit if the admin interfaces fail to be created let handles = handles.map_err(Box::new)?; { let mut ports = Vec::new(); // First, register the keepalive task, to ensure the conductor doesn't shut down // in the absence of other "real" tasks self.manage_task(ManagedTaskAdd::dont_handle(tokio::spawn(keep_alive_task( stop_tx.subscribe(), )))) .await?; // Now that tasks are spawned, register them with the TaskManager for (port, handle) in handles { ports.push(port); self.manage_task(ManagedTaskAdd::new( handle, Box::new(|result| { result.unwrap_or_else(|e| { error!(error = &e as &dyn std::error::Error, "Interface died") }); None }), )) .await? } for p in ports { self.add_admin_port(p); } } Ok(()) } pub(super) async fn add_app_interface_via_handle( &mut self, port: u16, handle: ConductorHandle, ) -> ConductorResult<u16> { tracing::debug!("Attaching interface {}", port); let interface_id = AppInterfaceId::new(port); let app_api = RealAppInterfaceApi::new(handle, interface_id.clone()); // This receiver is thrown away because we can produce infinite new // receivers from the Sender let (signal_tx, _r) = tokio::sync::broadcast::channel(SIGNAL_BUFFER_SIZE); let stop_rx = self.managed_task_stop_broadcaster.subscribe(); let (port, task) = spawn_app_interface_task(port, app_api, signal_tx.clone(), stop_rx) .await .map_err(Box::new)?; // TODO: RELIABILITY: Handle this task by restarting it if it fails and log the error self.manage_task(ManagedTaskAdd::dont_handle(task)).await?; let interface = AppInterfaceRuntime::Websocket { signal_tx }; if self.app_interfaces.contains_key(&interface_id) { return Err(ConductorError::AppInterfaceIdCollision(interface_id)); } self.app_interfaces.insert(interface_id.clone(), interface); let config = AppInterfaceConfig::websocket(port); self.update_state(|mut state| { state.app_interfaces.insert(interface_id, config); Ok(state) }) .await?; tracing::debug!("App interface added at port: {}", port); Ok(port) } pub(super) async fn list_app_interfaces(&self) -> ConductorResult<Vec<u16>> { Ok(self .get_state() .await? .app_interfaces .values() .map(|config| config.driver.port()) .collect()) } pub(super) async fn register_dna_wasm( &self, dna: DnaFile, ) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> { let is_full_wasm_dna = dna .dna_def() .zomes .iter() .all(|(_, zome_def)| matches!(zome_def, ZomeDef::Wasm(_))); // Only install wasm if the DNA is composed purely of WasmZomes (no InlineZomes) if is_full_wasm_dna { Ok(self.put_wasm(dna.clone()).await?) } else { Ok(Vec::with_capacity(0)) } } pub(super) async fn register_dna_entry_defs( &mut self, entry_defs: Vec<(EntryDefBufferKey, EntryDef)>, ) -> ConductorResult<()> { self.dna_store_mut().add_entry_defs(entry_defs); Ok(()) } pub(super) async fn register_phenotype(&mut self, dna: DnaFile) -> ConductorResult<()> { self.dna_store_mut().add_dna(dna); Ok(()) } /// Start all app interfaces currently in state. /// This should only be run at conductor initialization. #[allow(irrefutable_let_patterns)] pub(super) async fn startup_app_interfaces_via_handle( &mut self, handle: ConductorHandle, ) -> ConductorResult<()> { for (id, i) in self.get_state().await?.app_interfaces.iter() { tracing::debug!("Starting up app interface: {:?}", id); let port = if let InterfaceDriver::Websocket { port } = i.driver { if id.port() == port { port } else { id.port() } } else { unreachable!() }; let _ = self .add_app_interface_via_handle(port, handle.clone()) .await?; } Ok(()) } pub(super) fn signal_broadcaster(&self) -> SignalBroadcaster { SignalBroadcaster::new( self.app_interfaces .values() .map(|i| i.signal_tx()) .cloned() .collect(), ) } /// Perform Genesis on the source chains for each of the specified CellIds. /// /// If genesis fails for any cell, this entire function fails, and all other /// partial or complete successes are rolled back. pub(super) async fn genesis_cells( &self, cell_ids_with_proofs: Vec<(CellId, Option<MembraneProof>)>, conductor_handle: ConductorHandle, ) -> ConductorResult<()> { let root_env_dir = std::path::PathBuf::from(self.root_env_dir.clone()); let keystore = self.keystore.clone(); let cells_tasks = cell_ids_with_proofs.into_iter().map(|(cell_id, proof)| { let root_env_dir = root_env_dir.clone(); let keystore = self.keystore.clone(); let conductor_handle = conductor_handle.clone(); let cell_id_inner = cell_id.clone(); tokio::spawn(async move { let env = EnvironmentWrite::new( &root_env_dir, EnvironmentKind::Cell(cell_id_inner.clone()), keystore.clone(), )?; Cell::genesis(cell_id_inner, conductor_handle, env, proof).await }) .map_err(CellError::from) .and_then(|result| async move { result.map(|_| cell_id) }) }); let (success, errors): (Vec<_>, Vec<_>) = futures::future::join_all(cells_tasks) .await .into_iter() .partition(Result::is_ok); // unwrap safe because of the partition let success = success.into_iter().map(Result::unwrap); // If there were errors, cleanup and return the errors if !errors.is_empty() { for cell_id in success { let env = EnvironmentWrite::new( &root_env_dir, EnvironmentKind::Cell(cell_id), keystore.clone(), )?; env.remove().await?; } // match needed to avoid Debug requirement on unwrap_err let errors = errors .into_iter() .map(|e| match e { Err(e) => e, Ok(_) => unreachable!("Safe because of the partition"), }) .collect(); Err(ConductorError::GenesisFailed { errors }) } else { // No errors so return the cells Ok(()) } } /// Create Cells for each CellId marked active in the ConductorState db pub(super) async fn create_active_app_cells( &self, conductor_handle: ConductorHandle, ) -> ConductorResult<Vec<Result<Vec<(Cell, InitialQueueTriggers)>, CreateAppError>>> { // Only create the active apps let active_apps = self.get_state().await?.active_apps; // Data required to create apps let root_env_dir = self.root_env_dir.clone(); let keystore = self.keystore.clone(); // Closure for creating all cells in an app let tasks = active_apps.into_iter().map( move |(installed_app_id, app): (InstalledAppId, InstalledApp)| { // Clone data for async block let root_env_dir = std::path::PathBuf::from(root_env_dir.clone()); let conductor_handle = conductor_handle.clone(); let keystore = keystore.clone(); // Task that creates the cells async move { // Only create cells not already created let cells_to_create = app .all_cells() .filter(|cell_id| !self.cells.contains_key(cell_id)) .map(|cell_id| { ( cell_id, root_env_dir.clone(), keystore.clone(), conductor_handle.clone(), ) }); use holochain_p2p::actor::HolochainP2pRefToCell; // Create each cell let cells_tasks = cells_to_create.map( |(cell_id, dir, keystore, conductor_handle)| async move { let holochain_p2p_cell = self.holochain_p2p.to_cell( cell_id.dna_hash().clone(), cell_id.agent_pubkey().clone(), ); let env = EnvironmentWrite::new_cell( &dir, cell_id.clone(), keystore.clone(), )?; Cell::create( cell_id.clone(), conductor_handle.clone(), env, holochain_p2p_cell, self.managed_task_add_sender.clone(), self.managed_task_stop_broadcaster.clone(), ) .await }, ); // Join all the cell create tasks for this app // and separate any errors let (success, errors): (Vec<_>, Vec<_>) = futures::future::join_all(cells_tasks) .await .into_iter() .partition(Result::is_ok); // unwrap safe because of the partition let success = success.into_iter().map(Result::unwrap); // If there was errors, cleanup and return the errors if !errors.is_empty() { for cell in success { // Error needs to capture which app failed cell.0.destroy().await.map_err(|e| CreateAppError::Failed { installed_app_id: installed_app_id.clone(), errors: vec![e], })?; } // match needed to avoid Debug requirement on unwrap_err let errors = errors .into_iter() .map(|e| match e { Err(e) => e, Ok(_) => unreachable!("Safe because of the partition"), }) .collect(); Err(CreateAppError::Failed { installed_app_id, errors, }) } else { // No errors so return the cells Ok(success.collect()) } } }, ); // Join on all apps and return a list of // apps that had succelly created cells // and any apps that encounted errors Ok(futures::future::join_all(tasks).await) } /// Register an app inactive in the database pub(super) async fn add_inactive_app_to_db( &mut self, app: InstalledApp, ) -> ConductorResult<()> { trace!(?app); self.update_state(move |mut state| { debug!(?app); let is_active = state.active_apps.contains_key(app.installed_app_id()); let is_inactive = state.inactive_apps.insert(app.clone()).is_some(); if is_active || is_inactive { Err(ConductorError::AppAlreadyInstalled( app.installed_app_id().clone(), )) } else { Ok(state) } }) .await?; Ok(()) } /// Activate an app in the database pub(super) async fn activate_app_in_db( &mut self, installed_app_id: InstalledAppId, ) -> ConductorResult<()> { self.update_state(move |mut state| { let app = state .inactive_apps .remove(&installed_app_id) .ok_or_else(|| ConductorError::AppNotInstalled(installed_app_id.clone()))?; state.active_apps.insert(app); Ok(state) }) .await?; Ok(()) } /// Deactivate an app in the database pub(super) async fn deactivate_app_in_db( &mut self, installed_app_id: InstalledAppId, ) -> ConductorResult<Vec<CellId>> { let state = self .update_state({ let installed_app_id = installed_app_id.clone(); move |mut state| { let app = state .active_apps .remove(&installed_app_id) .ok_or_else(|| ConductorError::AppNotActive(installed_app_id.clone()))?; state.inactive_apps.insert(app); Ok(state) } }) .await?; Ok(state .inactive_apps .get(&installed_app_id) .expect("This app was just put here") .clone() .all_cells() .cloned() .collect()) } /// Add fully constructed cells to the cell map in the Conductor pub(super) fn add_cells(&mut self, cells: Vec<(Cell, InitialQueueTriggers)>) { for (cell, trigger) in cells { let cell_id = cell.id().clone(); tracing::info!(?cell_id, "ADD CELL"); self.cells.insert( cell_id, CellItem { cell: Arc::new(cell), _state: CellState { _active: false }, }, ); trigger.initialize_workflows(); } } /// Associate a Cell with an existing App pub(super) async fn add_clone_cell_to_app( &mut self, installed_app_id: &InstalledAppId, slot_id: &SlotId, properties: YamlProperties, ) -> ConductorResult<CellId> { let (_, child_dna) = self .update_state_prime(|mut state| { if let Some(app) = state.active_apps.get_mut(installed_app_id) { let slot = app .slots() .get(slot_id) .ok_or_else(|| AppError::SlotIdMissing(slot_id.to_owned()))?; let parent_dna_hash = slot.dna_hash(); let dna = self .dna_store .get(parent_dna_hash) .ok_or_else(|| DnaError::DnaMissing(parent_dna_hash.to_owned()))? .modify_phenotype(random_uuid(), properties)?; Ok((state, dna)) } else { Err(ConductorError::AppNotActive(installed_app_id.clone())) } }) .await?; let child_dna_hash = child_dna.dna_hash().to_owned(); self.register_phenotype(child_dna).await?; let (_, cell_id) = self .update_state_prime(|mut state| { if let Some(app) = state.active_apps.get_mut(installed_app_id) { let agent_key = app.slot(slot_id)?.agent_key().to_owned(); let cell_id = CellId::new(child_dna_hash, agent_key); app.add_clone(slot_id, cell_id.clone())?; Ok((state, cell_id)) } else { Err(ConductorError::AppNotActive(installed_app_id.clone())) } }) .await?; Ok(cell_id) } pub(super) async fn load_wasms_into_dna_files( &self, ) -> ConductorResult<( impl IntoIterator<Item = (DnaHash, DnaFile)>, impl IntoIterator<Item = (EntryDefBufferKey, EntryDef)>, )> { let environ = &self.wasm_env; let wasm = environ.get_db(&*holochain_lmdb::db::WASM)?; let dna_def_db = environ.get_db(&*holochain_lmdb::db::DNA_DEF)?; let entry_def_db = environ.get_db(&*holochain_lmdb::db::ENTRY_DEF)?; let wasm_buf = Arc::new(WasmBuf::new(environ.clone().into(), wasm)?); let dna_def_buf = DnaDefBuf::new(environ.clone().into(), dna_def_db)?; let entry_def_buf = EntryDefBuf::new(environ.clone().into(), entry_def_db)?; // Load out all dna defs let wasm_tasks = dna_def_buf .get_all()? .into_iter() .map(|dna_def| { // Load all wasms for each dna_def from the wasm db into memory let wasms = dna_def.zomes.clone().into_iter().map(|(zome_name, zome)| { let wasm_buf = wasm_buf.clone(); async move { wasm_buf .get(&zome.wasm_hash(&zome_name)?) .await? .map(|hashed| hashed.into_content()) .ok_or(ConductorError::WasmMissing) } }); async move { let wasms = futures::future::try_join_all(wasms).await?; let dna_file = DnaFile::new(dna_def.into_content(), wasms).await?; ConductorResult::Ok((dna_file.dna_hash().clone(), dna_file)) } }) // This needs to happen due to the environment not being Send .collect::<Vec<_>>(); // try to join all the tasks and return the list of dna files let dnas = futures::future::try_join_all(wasm_tasks).await?; let defs = fresh_reader!(environ, |r| entry_def_buf.get_all(&r)?.collect::<Vec<_>>())?; Ok((dnas, defs)) } /// Remove cells from the cell map in the Conductor pub(super) fn remove_cells(&mut self, cell_ids: Vec<CellId>) { for cell_id in cell_ids { self.cells.remove(&cell_id); } } pub(super) fn add_agent_infos( &self, agent_infos: Vec<AgentInfoSigned>, ) -> ConductorApiResult<()> { Ok(inject_agent_infos(self.p2p_env.clone(), agent_infos)?) } pub(super) fn get_agent_infos( &self, cell_id: Option<CellId>, ) -> ConductorApiResult<Vec<AgentInfoSigned>> { match cell_id { Some(c) => { let (d, a) = c.into_dna_and_agent(); Ok(get_single_agent_info(self.p2p_env.clone().into(), d, a)? .map(|a| vec![a]) .unwrap_or_default()) } None => Ok(all_agent_infos(self.p2p_env.clone().into())?), } } pub(super) async fn put_wasm( &self, dna: DnaFile, ) -> ConductorResult<Vec<(EntryDefBufferKey, EntryDef)>> { let environ = self.wasm_env.clone(); let wasm = environ.get_db(&*holochain_lmdb::db::WASM)?; let dna_def_db = environ.get_db(&*holochain_lmdb::db::DNA_DEF)?; let entry_def_db = environ.get_db(&*holochain_lmdb::db::ENTRY_DEF)?; let zome_defs = get_entry_defs(dna.clone())?; let mut entry_def_buf = EntryDefBuf::new(environ.clone().into(), entry_def_db)?; for (key, entry_def) in zome_defs.clone() { entry_def_buf.put(key, entry_def)?; } let mut wasm_buf = WasmBuf::new(environ.clone().into(), wasm)?; let mut dna_def_buf = DnaDefBuf::new(environ.clone().into(), dna_def_db)?; // TODO: PERF: This loop might be slow for (wasm_hash, dna_wasm) in dna.code().clone().into_iter() { if wasm_buf.get(&wasm_hash).await?.is_none() { wasm_buf.put(DnaWasmHashed::from_content(dna_wasm).await); } } if dna_def_buf.get(dna.dna_hash()).await?.is_none() { dna_def_buf.put(dna.dna_def().clone()).await?; } { let env = environ.guard(); // write the wasm db env.with_commit(|writer| wasm_buf.flush_to_txn(writer))?; // write the dna_def db env.with_commit(|writer| dna_def_buf.flush_to_txn(writer))?; // write the entry_def db env.with_commit(|writer| entry_def_buf.flush_to_txn(writer))?; } Ok(zome_defs) } pub(super) async fn list_cell_ids(&self) -> ConductorResult<Vec<CellId>> { Ok(self.cells.keys().cloned().collect()) } pub(super) async fn list_active_apps(&self) -> ConductorResult<Vec<InstalledAppId>> { let active_apps = self.get_state().await?.active_apps; Ok(active_apps.keys().cloned().collect()) } pub(super) async fn dump_cell_state(&self, cell_id: &CellId) -> ConductorApiResult<String> { let cell = self.cell_by_id(cell_id)?; let arc = cell.env(); let source_chain = SourceChainBuf::new(arc.clone().into())?; let peer_dump = p2p_store::dump_state(self.p2p_env.clone().into(), Some(cell_id.clone()))?; let source_chain_dump = source_chain.dump_state().await?; let integration_dump = integrate_dht_ops_workflow::dump_state(arc.clone().into())?; let out = JsonDump { peer_dump, source_chain_dump, integration_dump, }; // Add summary let summary = out.to_string(); let out = (out, summary); Ok(serde_json::to_string_pretty(&out)?) } pub(super) fn p2p_env(&self) -> EnvironmentWrite { self.p2p_env.clone() } pub(super) fn print_setup(&self) { use std::fmt::Write; let mut out = String::new(); for port in &self.admin_websocket_ports { writeln!(&mut out, "###ADMIN_PORT:{}###", port).expect("Can't write setup to std out"); } println!("\n###HOLOCHAIN_SETUP###\n{}###HOLOCHAIN_SETUP_END###", out); } #[cfg(any(test, feature = "test_utils"))] pub(super) async fn get_state_from_handle(&self) -> ConductorResult<ConductorState> { self.get_state().await } #[cfg(any(test, feature = "test_utils"))] pub(super) async fn add_test_app_interface<I: Into<AppInterfaceId>>( &mut self, id: I, ) -> ConductorResult<()> { let id = id.into(); let (signal_tx, _r) = tokio::sync::broadcast::channel(1000); if self.app_interfaces.contains_key(&id) { return Err(ConductorError::AppInterfaceIdCollision(id)); } let _ = self .app_interfaces .insert(id, AppInterfaceRuntime::Test { signal_tx }); Ok(()) } } //----------------------------------------------------------------------------- // Private methods //----------------------------------------------------------------------------- impl<DS> Conductor<DS> where DS: DnaStore + 'static, { async fn new( env: EnvironmentWrite, wasm_env: EnvironmentWrite, p2p_env: EnvironmentWrite, dna_store: DS, keystore: KeystoreSender, root_env_dir: EnvironmentRootPath, holochain_p2p: holochain_p2p::HolochainP2pRef, ) -> ConductorResult<Self> { let db: SingleStore = env.get_db(&db::CONDUCTOR_STATE)?; let (task_tx, task_manager_run_handle) = spawn_task_manager(); let task_manager_run_handle = Some(task_manager_run_handle); let (stop_tx, _) = tokio::sync::broadcast::channel::<()>(1); Ok(Self { env, wasm_env, p2p_env, state_db: KvStore::new(db), cells: HashMap::new(), shutting_down: false, app_interfaces: HashMap::new(), managed_task_add_sender: task_tx, managed_task_stop_broadcaster: stop_tx, task_manager_run_handle, admin_websocket_ports: Vec::new(), dna_store, keystore, root_env_dir, holochain_p2p, }) } pub(super) async fn get_state(&self) -> ConductorResult<ConductorState> { let guard = self.env.guard(); let reader = guard.reader()?; Ok(self.state_db.get(&reader, &UnitDbKey)?.unwrap_or_default()) } /// Update the internal state with a pure function mapping old state to new async fn update_state<F: Send>(&self, f: F) -> ConductorResult<ConductorState> where F: FnOnce(ConductorState) -> ConductorResult<ConductorState>, { let (state, _) = self.update_state_prime(|s| Ok((f(s)?, ()))).await?; Ok(state) } /// Update the internal state with a pure function mapping old state to new, /// which may also produce an output value which will be the output of /// this function async fn update_state_prime<F: Send, O>(&self, f: F) -> ConductorResult<(ConductorState, O)> where F: FnOnce(ConductorState) -> ConductorResult<(ConductorState, O)>, { self.check_running()?; let guard = self.env.guard(); let output = guard.with_commit(|txn| { let state: ConductorState = self.state_db.get(txn, &UnitDbKey)?.unwrap_or_default(); let (new_state, output) = f(state)?; self.state_db.put(txn, &UnitDbKey, &new_state)?; Result::<_, ConductorError>::Ok((new_state, output)) })?; Ok(output) } fn add_admin_port(&mut self, port: u16) { self.admin_websocket_ports.push(port); } /// Sends a JoinHandle to the TaskManager task to be managed async fn manage_task(&mut self, handle: ManagedTaskAdd) -> ConductorResult<()> { self.managed_task_add_sender .send(handle) .await .map_err(|e| ConductorError::SubmitTaskError(format!("{}", e))) } } /// The database used to store ConductorState. It has only one key-value pair. pub type ConductorStateDb = KvStore<UnitDbKey, ConductorState>; mod builder { use super::*; use crate::conductor::dna_store::RealDnaStore; use crate::conductor::ConductorHandle; use holochain_lmdb::env::EnvironmentKind; #[cfg(any(test, feature = "test_utils"))] use holochain_lmdb::test_utils::TestEnvironments; /// A configurable Builder for Conductor and sometimes ConductorHandle #[derive(Default)] pub struct ConductorBuilder<DS = RealDnaStore> { /// The configuration pub config: ConductorConfig, /// The DnaStore (mockable) pub dna_store: DS, /// Optional keystore override pub keystore: Option<KeystoreSender>, #[cfg(any(test, feature = "test_utils"))] /// Optional state override (for testing) pub state: Option<ConductorState>, #[cfg(any(test, feature = "test_utils"))] /// Optional handle mock (for testing) pub mock_handle: Option<MockConductorHandleT>, } impl ConductorBuilder { /// Default ConductorBuilder pub fn new() -> Self { Self::default() } } impl ConductorBuilder<MockDnaStore> { /// ConductorBuilder using mocked DnaStore, for testing pub fn with_mock_dna_store(dna_store: MockDnaStore) -> ConductorBuilder<MockDnaStore> { Self { dna_store, ..Default::default() } } } impl<DS> ConductorBuilder<DS> where DS: DnaStore + 'static, { /// Set the ConductorConfig used to build this Conductor pub fn config(mut self, config: ConductorConfig) -> Self { self.config = config; self } /// Initialize a "production" Conductor pub async fn build(self) -> ConductorResult<ConductorHandle> { cfg_if::cfg_if! { // if mock_handle is specified, return that instead of // a real handle if #[cfg(test)] { if let Some(handle) = self.mock_handle { return Ok(Arc::new(handle)); } } } tracing::info!(?self.config); let keystore = if let Some(keystore) = self.keystore { keystore } else if self.config.use_dangerous_test_keystore { let keystore = spawn_test_keystore().await?; // pre-populate with our two fixture agent keypairs keystore .generate_sign_keypair_from_pure_entropy() .await .unwrap(); keystore .generate_sign_keypair_from_pure_entropy() .await .unwrap(); keystore } else { spawn_lair_keystore(self.config.keystore_path.as_deref()).await? }; let env_path = self.config.environment_path.clone(); let environment = EnvironmentWrite::new( env_path.as_ref(), EnvironmentKind::Conductor, keystore.clone(), )?; let wasm_environment = EnvironmentWrite::new(env_path.as_ref(), EnvironmentKind::Wasm, keystore.clone())?; let p2p_environment = EnvironmentWrite::new(env_path.as_ref(), EnvironmentKind::P2p, keystore.clone())?; #[cfg(any(test, feature = "test_utils"))] let state = self.state; let Self { dna_store, config, .. } = self; let network_config = match &config.network { None => holochain_p2p::kitsune_p2p::KitsuneP2pConfig::default(), Some(config) => config.clone(), }; let (cert_digest, cert, cert_priv_key) = keystore.get_or_create_first_tls_cert().await?; let tls_config = holochain_p2p::kitsune_p2p::dependencies::kitsune_p2p_proxy::TlsConfig { cert, cert_priv_key, cert_digest, }; let (holochain_p2p, p2p_evt) = holochain_p2p::spawn_holochain_p2p(network_config, tls_config).await?; let conductor = Conductor::new( environment, wasm_environment, p2p_environment, dna_store, keystore, env_path, holochain_p2p, ) .await?; #[cfg(any(test, feature = "test_utils"))] let conductor = Self::update_fake_state(state, conductor).await?; Self::finish(conductor, config, p2p_evt).await } async fn finish( conductor: Conductor<DS>, conductor_config: ConductorConfig, p2p_evt: holochain_p2p::event::HolochainP2pEventReceiver, ) -> ConductorResult<ConductorHandle> { // Get data before handle let keystore = conductor.keystore.clone(); let holochain_p2p = conductor.holochain_p2p.clone(); // Create handle let handle: ConductorHandle = Arc::new(ConductorHandleImpl { conductor: RwLock::new(conductor), keystore, holochain_p2p, }); handle.load_dnas().await?; tokio::task::spawn(p2p_event_task(p2p_evt, handle.clone())); let cell_startup_errors = handle.clone().setup_cells().await?; // TODO: This should probably be emitted over the admin interface if !cell_startup_errors.is_empty() { error!( msg = "Failed to create the following active apps", ?cell_startup_errors ); } // Create admin interfaces if let Some(configs) = conductor_config.admin_interfaces { handle.clone().add_admin_interfaces(configs).await?; } // Create app interfaces handle.clone().startup_app_interfaces().await?; handle.print_setup().await; Ok(handle) } /// Pass a test keystore in, to ensure that generated test agents /// are actually available for signing (especially for tryorama compat) pub fn with_keystore(mut self, keystore: KeystoreSender) -> Self { self.keystore = Some(keystore); self } #[cfg(any(test, feature = "test_utils"))] /// Sets some fake conductor state for tests pub fn fake_state(mut self, state: ConductorState) -> Self { self.state = Some(state); self } /// Pass a mock handle in, which will be returned regardless of whatever /// else happens to this builder #[cfg(any(test, feature = "test_utils"))] pub fn with_mock_handle(mut self, handle: MockConductorHandleT) -> Self { self.mock_handle = Some(handle); self } #[cfg(any(test, feature = "test_utils"))] async fn update_fake_state( state: Option<ConductorState>, conductor: Conductor<DS>, ) -> ConductorResult<Conductor<DS>> { if let Some(state) = state { conductor.update_state(move |_| Ok(state)).await?; } Ok(conductor) } /// Build a Conductor with a test environment #[cfg(any(test, feature = "test_utils"))] pub async fn test(self, envs: &TestEnvironments) -> ConductorResult<ConductorHandle> { let keystore = envs.conductor().keystore(); let (holochain_p2p, p2p_evt) = holochain_p2p::spawn_holochain_p2p(self.config.network.clone().unwrap_or_default(), holochain_p2p::kitsune_p2p::dependencies::kitsune_p2p_proxy::TlsConfig::new_ephemeral().await.unwrap()) .await?; let conductor = Conductor::new( envs.conductor(), envs.wasm(), envs.p2p(), self.dna_store, keystore, envs.tempdir().path().to_path_buf().into(), holochain_p2p, ) .await?; #[cfg(any(test, feature = "test_utils"))] let conductor = Self::update_fake_state(self.state, conductor).await?; Self::finish(conductor, self.config, p2p_evt).await } } } #[instrument(skip(p2p_evt, handle))] async fn p2p_event_task( p2p_evt: holochain_p2p::event::HolochainP2pEventReceiver, handle: ConductorHandle, ) { /// The number of events we allow to run in parallel before /// starting to await on the join handles. const NUM_PARALLEL_EVTS: usize = 100; p2p_evt .for_each_concurrent(NUM_PARALLEL_EVTS, |evt| { let handle = handle.clone(); async move { let cell_id = CellId::new(evt.dna_hash().clone(), evt.target_agent_as_ref().clone()); if let Err(e) = handle.dispatch_holochain_p2p_event(&cell_id, evt).await { tracing::error!( message = "error dispatching network event", error = ?e, ); } } .in_current_span() }) .await; tracing::warn!("p2p_event_task has ended"); } #[cfg(test)] pub mod tests;
37.210359
203
0.55635
8f66b22c3a56be91f53d2081012ac4eeae8a3044
5,213
use ash::vk; use ash::version::DeviceV1_0; use gsma::collect_handle; use crate::core::GsDevice; use crate::core::device::enums::{ DeviceQueueIdentifier, QueueRequestStrategy }; use crate::core::device::queue::{ GsGraphicsQueue, GsPresentQueue, GsTransferQueue, GsTransfer }; use crate::core::device::queue::{ GsQueue, QueueSubmitBundle }; use crate::sync::GsFence; use crate::error::{ VkResult, VkError }; use crate::types::vklint; use std::ptr; pub struct GsLogicalDevice { pub(crate) handle: ash::Device, graphics_queue: GsGraphicsQueue, present_queue : GsPresentQueue, transfer_queue: GsTransferQueue, } impl GsLogicalDevice { pub(super) fn new(handle: ash::Device, graphics: GsGraphicsQueue, present: GsPresentQueue, transfer: GsTransferQueue) -> GsLogicalDevice { GsLogicalDevice { handle, graphics_queue: graphics, present_queue : present, transfer_queue: transfer, } } /// Tell device to wait for a group of fences. /// /// To wait for a single fence, use GsFence::wait() method instead. pub fn wait_fences(&self, fences: &[&GsFence], wait_all: bool, timeout: vklint) -> VkResult<()> { let handles: Vec<vk::Fence> = collect_handle!(fences); unsafe { self.handle.wait_for_fences(&handles, wait_all, timeout) .or(Err(VkError::device("Failed to reset fence.")))? } Ok(()) } pub fn reset_fences(&self, fences: &[&GsFence]) -> VkResult<()> { let handles: Vec<vk::Fence> = collect_handle!(fences); unsafe { self.handle.reset_fences(&handles) .or(Err(VkError::device("Failed to reset fence.")))? } Ok(()) } /// Submit a singe command bundle to Device. pub fn submit_single(&self, bundle: &QueueSubmitBundle, fence: Option<&GsFence>, queue_ident: DeviceQueueIdentifier) -> VkResult<()> { // TODO: Add configuration to select submit queue family // TODO: Add Speed test to this function. let wait_semaphores: Vec<vk::Semaphore> = collect_handle!(bundle.wait_semaphores); let sign_semaphores: Vec<vk::Semaphore> = collect_handle!(bundle.sign_semaphores); let commands: Vec<vk::CommandBuffer> = collect_handle!(bundle.commands); let submit_info = vk::SubmitInfo { s_type: vk::StructureType::SUBMIT_INFO, p_next: ptr::null(), // an array of semaphores upon which to wait before the command buffers for this batch begin execution. wait_semaphore_count : wait_semaphores.len() as _, p_wait_semaphores : wait_semaphores.as_ptr(), // an array of pipeline stages at which each corresponding semaphore wait will occur. p_wait_dst_stage_mask : bundle.wait_stages.as_ptr(), // an array of command buffers to execute in the batch. command_buffer_count : commands.len() as _, p_command_buffers : commands.as_ptr(), // an array of semaphores which will be signaled when the command buffers for this batch have completed execution. signal_semaphore_count : sign_semaphores.len() as _, p_signal_semaphores : sign_semaphores.as_ptr(), }; let queue = self.queue_handle_by_identifier(queue_ident); let fence = fence .and_then(|f| Some(f.handle)) .unwrap_or(vk::Fence::null()); unsafe { self.handle.queue_submit(queue.handle, &[submit_info], fence) .or(Err(VkError::device("Failed to submit command to device.")))? } Ok(()) } pub fn wait_idle(&self) -> VkResult<()> { unsafe { self.handle.device_wait_idle() .or(Err(VkError::device("Device failed to wait idle."))) } } pub fn discard(&self) { unsafe { self.graphics_queue.discard(); self.present_queue.discard(); self.transfer_queue.discard(self); self.handle.destroy_device(None); } } pub fn transfer(device: &GsDevice) -> VkResult<GsTransfer> { device.logic.transfer_queue.transfer(device) } pub fn queue_handle_by_identifier(&self, identifier: DeviceQueueIdentifier) -> &GsQueue { match identifier { | DeviceQueueIdentifier::Graphics => &self.graphics_queue.queue(), | DeviceQueueIdentifier::Present => &self.present_queue.queue(), | DeviceQueueIdentifier::Transfer => &self.transfer_queue.queue(), } } pub fn update_descriptor_sets(&self, write_contents: &Vec<vk::WriteDescriptorSet>) { unsafe { self.handle.update_descriptor_sets(&write_contents, &[]); } } pub(crate) fn transfer_queue(&self) -> &GsTransferQueue { &self.transfer_queue } } #[derive(Debug, Clone)] pub struct DeviceConfig { pub queue_request_strategy: QueueRequestStrategy, pub transfer_wait_time: vklint, pub print_device_name : bool, pub print_device_api : bool, pub print_device_type : bool, pub print_device_queues: bool, }
32.993671
142
0.631115
67e0be62449fe2cea5a9c6e1dd6fb4d2d715a01e
20,016
use std::cell::RefCell; use std::collections::VecDeque; use std::sync::{Arc, Mutex, Weak}; use std::sync::atomic::{AtomicBool, Ordering}; use {EventsLoopClosed, ControlFlow}; use super::WindowId; use super::window::WindowStore; use super::keyboard::init_keyboard; use wayland_client::{EnvHandler, EnvNotify, default_connect, EventQueue, EventQueueHandle, Proxy, StateToken}; use wayland_client::protocol::{wl_compositor, wl_seat, wl_shell, wl_shm, wl_subcompositor, wl_display, wl_registry, wl_output, wl_surface, wl_pointer, wl_keyboard, wl_touch}; use super::wayland_window::{Frame, Shell, create_frame, FrameImplementation}; use super::wayland_protocols::unstable::xdg_shell::v6::client::zxdg_shell_v6; pub struct EventsLoopSink { buffer: VecDeque<::Event> } unsafe impl Send for EventsLoopSink { } impl EventsLoopSink { pub fn new() -> EventsLoopSink{ EventsLoopSink { buffer: VecDeque::new() } } pub fn send_event(&mut self, evt: ::WindowEvent, wid: WindowId) { let evt = ::Event::WindowEvent { event: evt, window_id: ::WindowId(::platform::WindowId::Wayland(wid)) }; self.buffer.push_back(evt); } pub fn send_raw_event(&mut self, evt: ::Event) { self.buffer.push_back(evt); } fn empty_with<F>(&mut self, callback: &mut F) where F: FnMut(::Event) { for evt in self.buffer.drain(..) { callback(evt) } } } pub struct EventsLoop { // The Event Queue pub evq: RefCell<EventQueue>, // our sink, shared with some handlers, buffering the events sink: Arc<Mutex<EventsLoopSink>>, // Whether or not there is a pending `Awakened` event to be emitted. pending_wakeup: Arc<AtomicBool>, // The window store pub store: StateToken<WindowStore>, // the env env_token: StateToken<EnvHandler<InnerEnv>>, // the ctxt pub ctxt_token: StateToken<StateContext>, // a cleanup switch to prune dead windows pub cleanup_needed: Arc<Mutex<bool>>, // The wayland display pub display: Arc<wl_display::WlDisplay>, } // A handle that can be sent across threads and used to wake up the `EventsLoop`. // // We should only try and wake up the `EventsLoop` if it still exists, so we hold Weak ptrs. #[derive(Clone)] pub struct EventsLoopProxy { display: Weak<wl_display::WlDisplay>, pending_wakeup: Weak<AtomicBool>, } impl EventsLoopProxy { // Causes the `EventsLoop` to stop blocking on `run_forever` and emit an `Awakened` event. // // Returns `Err` if the associated `EventsLoop` no longer exists. pub fn wakeup(&self) -> Result<(), EventsLoopClosed> { let display = self.display.upgrade(); let wakeup = self.pending_wakeup.upgrade(); match (display, wakeup) { (Some(display), Some(wakeup)) => { // Update the `EventsLoop`'s `pending_wakeup` flag. wakeup.store(true, Ordering::Relaxed); // Cause the `EventsLoop` to break from `dispatch` if it is currently blocked. display.sync(); display.flush().map_err(|_| EventsLoopClosed)?; Ok(()) }, _ => Err(EventsLoopClosed), } } } impl EventsLoop { pub fn new() -> Option<EventsLoop> { let (display, mut event_queue) = match default_connect() { Ok(ret) => ret, Err(_) => return None }; let registry = display.get_registry(); let ctxt_token = event_queue.state().insert( StateContext::new(registry.clone().unwrap()) ); let env_token = EnvHandler::init_with_notify( &mut event_queue, &registry, env_notify(), ctxt_token.clone() ); // two round trips to fully initialize event_queue.sync_roundtrip().expect("Wayland connection unexpectedly lost"); event_queue.sync_roundtrip().expect("Wayland connection unexpectedly lost"); event_queue.state().with_value(&ctxt_token, |proxy, ctxt| { ctxt.ensure_shell(proxy.get_mut(&env_token)) }); let sink = Arc::new(Mutex::new(EventsLoopSink::new())); let store = event_queue.state().insert(WindowStore::new()); let seat_idata = SeatIData { sink: sink.clone(), keyboard: None, pointer: None, touch: None, windows_token: store.clone() }; let mut me = EventsLoop { display: Arc::new(display), evq: RefCell::new(event_queue), sink: sink, pending_wakeup: Arc::new(AtomicBool::new(false)), store: store, ctxt_token: ctxt_token, env_token: env_token, cleanup_needed: Arc::new(Mutex::new(false)) }; me.init_seat(|evqh, seat| { evqh.register(seat, seat_implementation(), seat_idata); }); Some(me) } pub fn create_proxy(&self) -> EventsLoopProxy { EventsLoopProxy { display: Arc::downgrade(&self.display), pending_wakeup: Arc::downgrade(&self.pending_wakeup), } } pub fn poll_events<F>(&mut self, mut callback: F) where F: FnMut(::Event) { // send pending events to the server self.display.flush().expect("Wayland connection lost."); // dispatch any pre-buffered events self.sink.lock().unwrap().empty_with(&mut callback); // try to read pending events if let Some(h) = self.evq.get_mut().prepare_read() { h.read_events().expect("Wayland connection lost."); } // dispatch wayland events self.evq.get_mut().dispatch_pending().expect("Wayland connection lost."); self.post_dispatch_triggers(); // dispatch buffered events to client self.sink.lock().unwrap().empty_with(&mut callback); } pub fn run_forever<F>(&mut self, mut callback: F) where F: FnMut(::Event) -> ControlFlow, { // send pending events to the server self.display.flush().expect("Wayland connection lost."); // Check for control flow by wrapping the callback. let control_flow = ::std::cell::Cell::new(ControlFlow::Continue); let mut callback = |event| if let ControlFlow::Break = callback(event) { control_flow.set(ControlFlow::Break); }; // dispatch any pre-buffered events self.post_dispatch_triggers(); self.sink.lock().unwrap().empty_with(&mut callback); loop { // dispatch events blocking if needed self.evq.get_mut().dispatch().expect("Wayland connection lost."); self.post_dispatch_triggers(); // empty buffer of events self.sink.lock().unwrap().empty_with(&mut callback); if let ControlFlow::Break = control_flow.get() { break; } } } pub fn get_primary_monitor(&self) -> MonitorId { let mut guard = self.evq.borrow_mut(); let state = guard.state(); let state_ctxt = state.get(&self.ctxt_token); if let Some(info) = state_ctxt.monitors.iter().next() { MonitorId { info: info.clone() } } else { panic!("No monitor is available.") } } pub fn get_available_monitors(&self) -> VecDeque<MonitorId> { let mut guard = self.evq.borrow_mut(); let state = guard.state(); let state_ctxt = state.get(&self.ctxt_token); state_ctxt.monitors.iter() .map(|m| MonitorId { info: m.clone() }) .collect() } } /* * Private EventsLoop Internals */ wayland_env!(InnerEnv, compositor: wl_compositor::WlCompositor, shm: wl_shm::WlShm, subcompositor: wl_subcompositor::WlSubcompositor ); pub struct StateContext { registry: wl_registry::WlRegistry, seat: Option<wl_seat::WlSeat>, shell: Option<Shell>, monitors: Vec<Arc<Mutex<OutputInfo>>> } impl StateContext { fn new(registry: wl_registry::WlRegistry) -> StateContext { StateContext { registry: registry, seat: None, shell: None, monitors: Vec::new() } } /// Ensures a shell is available /// /// If a shell is already bound, do nothing. Otherwise, /// try to bind wl_shell as a fallback. If this fails, /// panic, as this is a bug from the compositor. fn ensure_shell(&mut self, env: &mut EnvHandler<InnerEnv>) { if self.shell.is_some() { return; } // xdg_shell is not available, so initialize wl_shell for &(name, ref interface, _) in env.globals() { if interface == "wl_shell" { self.shell = Some(Shell::Wl(self.registry.bind::<wl_shell::WlShell>(1, name))); return; } } // This is a compositor bug, it _must_ at least support wl_shell panic!("Compositor didi not advertize xdg_shell not wl_shell."); } pub fn monitor_id_for(&self, output: &wl_output::WlOutput) -> MonitorId { for info in &self.monitors { let guard = info.lock().unwrap(); if guard.output.equals(output) { return MonitorId { info: info.clone() }; } } panic!("Received an inexistent wl_output?!"); } } impl EventsLoop { pub fn init_seat<F>(&mut self, f: F) where F: FnOnce(&mut EventQueueHandle, &wl_seat::WlSeat) { let mut guard = self.evq.borrow_mut(); if guard.state().get(&self.ctxt_token).seat.is_some() { // seat has already been init return; } // clone the token to make borrow checker happy let ctxt_token = self.ctxt_token.clone(); let seat = guard.state().with_value(&self.env_token, |proxy, env| { let ctxt = proxy.get(&ctxt_token); for &(name, ref interface, _) in env.globals() { if interface == wl_seat::WlSeat::interface_name() { return Some(ctxt.registry.bind::<wl_seat::WlSeat>(5, name)); } } None }); if let Some(seat) = seat { f(&mut *guard, &seat); guard.state().get_mut(&self.ctxt_token).seat = Some(seat) } } fn post_dispatch_triggers(&mut self) { let mut sink = self.sink.lock().unwrap(); let evq = self.evq.get_mut(); // process a possible pending wakeup call if self.pending_wakeup.load(Ordering::Relaxed) { sink.send_raw_event(::Event::Awakened); self.pending_wakeup.store(false, Ordering::Relaxed); } // prune possible dead windows { let mut cleanup_needed = self.cleanup_needed.lock().unwrap(); if *cleanup_needed { evq.state().get_mut(&self.store).cleanup(); *cleanup_needed = false; } } // process pending resize/refresh evq.state().get_mut(&self.store).for_each( |newsize, refresh, frame_refresh, closed, wid, frame| { if let Some(frame) = frame { if let Some((w, h)) = newsize { frame.resize(w as i32, h as i32); frame.refresh(); sink.send_event(::WindowEvent::Resized(w as u32, h as u32), wid); } else if frame_refresh { frame.refresh(); } } if refresh { sink.send_event(::WindowEvent::Refresh, wid); } if closed { sink.send_event(::WindowEvent::Closed, wid); } } ) } /// Create a new window with given dimensions /// /// Grabs a lock on the event queue in the process pub fn create_window<ID: 'static, F>(&self, width: u32, height: u32, implem: FrameImplementation<ID>, idata: F) -> (wl_surface::WlSurface, Frame) where F: FnOnce(&wl_surface::WlSurface) -> ID { let (surface, frame) = { let mut guard = self.evq.borrow_mut(); let env = guard.state().get(&self.env_token).clone_inner().unwrap(); let shell = match guard.state().get(&self.ctxt_token).shell { Some(Shell::Wl(ref wl_shell)) => Shell::Wl(wl_shell.clone().unwrap()), Some(Shell::Xdg(ref xdg_shell)) => Shell::Xdg(xdg_shell.clone().unwrap()), None => unreachable!() }; let seat = guard.state().get(&self.ctxt_token).seat.as_ref().and_then(|s| s.clone()); let surface = env.compositor.create_surface(); let frame = create_frame( &mut guard, implem, idata(&surface), &surface, width as i32, height as i32, &env.compositor, &env.subcompositor, &env.shm, &shell, seat ).expect("Failed to create a tmpfile buffer."); (surface, frame) }; (surface, frame) } } /* * Wayland protocol implementations */ fn env_notify() -> EnvNotify<StateToken<StateContext>> { EnvNotify { new_global: |evqh, token, registry, id, interface, version| { use std::cmp::min; if interface == wl_output::WlOutput::interface_name() { // a new output is available let output = registry.bind::<wl_output::WlOutput>(min(version, 3), id); evqh.register(&output, output_impl(), token.clone()); evqh.state().get_mut(&token).monitors.push( Arc::new(Mutex::new(OutputInfo::new(output, id))) ); } else if interface == zxdg_shell_v6::ZxdgShellV6::interface_name() { // We have an xdg_shell, bind it let xdg_shell = registry.bind::<zxdg_shell_v6::ZxdgShellV6>(1, id); evqh.register(&xdg_shell, xdg_ping_implementation(), ()); evqh.state().get_mut(&token).shell = Some(Shell::Xdg(xdg_shell)); } }, del_global: |evqh, token, _, id| { // maybe this was a monitor, cleanup evqh.state().get_mut(&token).monitors.retain( |m| m.lock().unwrap().id != id ); }, ready: |_, _, _| {} } } fn xdg_ping_implementation() -> zxdg_shell_v6::Implementation<()> { zxdg_shell_v6::Implementation { ping: |_, _, shell, serial| { shell.pong(serial); } } } struct SeatIData { sink: Arc<Mutex<EventsLoopSink>>, pointer: Option<wl_pointer::WlPointer>, keyboard: Option<wl_keyboard::WlKeyboard>, touch: Option<wl_touch::WlTouch>, windows_token: StateToken<WindowStore> } fn seat_implementation() -> wl_seat::Implementation<SeatIData> { wl_seat::Implementation { name: |_, _, _, _| {}, capabilities: |evqh, idata, seat, capabilities| { // create pointer if applicable if capabilities.contains(wl_seat::Capability::Pointer) && idata.pointer.is_none() { let pointer = seat.get_pointer().expect("Seat is not dead"); let p_idata = super::pointer::PointerIData::new( &idata.sink, idata.windows_token.clone() ); evqh.register(&pointer, super::pointer::pointer_implementation(), p_idata); idata.pointer = Some(pointer); } // destroy pointer if applicable if !capabilities.contains(wl_seat::Capability::Pointer) { if let Some(pointer) = idata.pointer.take() { pointer.release(); } } // create keyboard if applicable if capabilities.contains(wl_seat::Capability::Keyboard) && idata.keyboard.is_none() { let kbd = seat.get_keyboard().expect("Seat is not dead"); init_keyboard(evqh, &kbd, &idata.sink); idata.keyboard = Some(kbd); } // destroy keyboard if applicable if !capabilities.contains(wl_seat::Capability::Keyboard) { if let Some(kbd) = idata.keyboard.take() { kbd.release(); } } // create touch if applicable if capabilities.contains(wl_seat::Capability::Touch) && idata.touch.is_none() { let touch = seat.get_touch().expect("Seat is not dead"); let t_idata = super::touch::TouchIData::new( &idata.sink, idata.windows_token.clone() ); evqh.register(&touch, super::touch::touch_implementation(), t_idata); idata.touch = Some(touch); } // destroy touch if applicable if !capabilities.contains(wl_seat::Capability::Touch) { if let Some(touch) = idata.touch.take() { touch.release(); } } } } } /* * Monitor stuff */ fn output_impl() -> wl_output::Implementation<StateToken<StateContext>> { wl_output::Implementation { geometry: |evqh, token, output, x, y, _, _, _, make, model, _| { let ctxt = evqh.state().get_mut(token); for info in &ctxt.monitors { let mut guard = info.lock().unwrap(); if guard.output.equals(output) { guard.pix_pos = (x, y); guard.name = format!("{} - {}", make, model); return; } } }, mode: |evqh, token, output, flags, w, h, _refresh| { if flags.contains(wl_output::Mode::Current) { let ctxt = evqh.state().get_mut(token); for info in &ctxt.monitors { let mut guard = info.lock().unwrap(); if guard.output.equals(output) { guard.pix_size = (w as u32, h as u32); return; } } } }, done: |_, _, _| {}, scale: |evqh, token, output, scale| { let ctxt = evqh.state().get_mut(token); for info in &ctxt.monitors { let mut guard = info.lock().unwrap(); if guard.output.equals(output) { guard.scale = scale as f32; return; } } } } } pub struct OutputInfo { pub output: wl_output::WlOutput, pub id: u32, pub scale: f32, pub pix_size: (u32, u32), pub pix_pos: (i32, i32), pub name: String } impl OutputInfo { fn new(output: wl_output::WlOutput, id: u32) -> OutputInfo { OutputInfo { output: output, id: id, scale: 1.0, pix_size: (0, 0), pix_pos: (0, 0), name: "".into() } } } #[derive(Clone)] pub struct MonitorId { pub info: Arc<Mutex<OutputInfo>> } impl MonitorId { pub fn get_name(&self) -> Option<String> { Some(self.info.lock().unwrap().name.clone()) } #[inline] pub fn get_native_identifier(&self) -> u32 { self.info.lock().unwrap().id } pub fn get_dimensions(&self) -> (u32, u32) { self.info.lock().unwrap().pix_size } pub fn get_position(&self) -> (i32, i32) { self.info.lock().unwrap().pix_pos } #[inline] pub fn get_hidpi_factor(&self) -> f32 { self.info.lock().unwrap().scale } }
33.810811
115
0.548961
de84333affb9bc3e29d48cf6afabbca8293f4e31
1,626
mod builder; pub mod data_series_encoding_map; pub mod encoding; pub mod preservation_map; mod tag_encoding_map; pub use self::{ builder::Builder, data_series_encoding_map::DataSeriesEncodingMap, encoding::Encoding, preservation_map::{PreservationMap, SubstitutionMatrix, TagIdsDictionary}, tag_encoding_map::TagEncodingMap, }; use std::{convert::TryFrom, io}; use crate::reader::compression_header::read_compression_header; use super::Block; #[derive(Debug)] pub struct CompressionHeader { preservation_map: PreservationMap, data_series_encoding_map: DataSeriesEncodingMap, tag_encoding_map: TagEncodingMap, } impl CompressionHeader { pub fn builder() -> Builder { Builder::default() } pub fn new( preservation_map: PreservationMap, data_series_encoding_map: DataSeriesEncodingMap, tag_encoding_map: TagEncodingMap, ) -> Self { Self { preservation_map, data_series_encoding_map, tag_encoding_map, } } pub fn preservation_map(&self) -> &PreservationMap { &self.preservation_map } pub fn data_series_encoding_map(&self) -> &DataSeriesEncodingMap { &self.data_series_encoding_map } pub fn tag_encoding_map(&self) -> &TagEncodingMap { &self.tag_encoding_map } } impl TryFrom<&Block> for CompressionHeader { type Error = io::Error; fn try_from(block: &Block) -> Result<Self, Self::Error> { let data = block.decompressed_data()?; let mut reader = &data[..]; read_compression_header(&mut reader) } }
24.268657
78
0.682042
5b8e11abaa0daa702b9c41ec36d794df97f36e0d
8,646
use std::panic::{catch_unwind, AssertUnwindSafe}; use std::path::{Path, PathBuf}; use rustc_ast::token::{DelimToken, TokenKind}; use rustc_ast::{ast, ptr}; use rustc_errors::Diagnostic; use rustc_parse::{ new_parser_from_file, parser::{ForceCollect, Parser as RawParser}, }; use rustc_span::{sym, symbol::kw, Span}; use crate::formatting::attr::first_attr_value_str_by_name; use crate::formatting::syntux::session::ParseSess; use crate::Input; pub(crate) type DirectoryOwnership = rustc_expand::module::DirOwnership; pub(crate) type ModulePathSuccess = rustc_expand::module::ModulePathSuccess; pub(crate) type ModError<'a> = rustc_expand::module::ModError<'a>; #[derive(Clone)] pub(crate) struct Directory { pub(crate) path: PathBuf, pub(crate) ownership: DirectoryOwnership, } /// A parser for Rust source code. pub(crate) struct Parser<'a> { parser: RawParser<'a>, } /// A builder for the `Parser`. #[derive(Default)] pub(crate) struct ParserBuilder<'a> { sess: Option<&'a ParseSess>, input: Option<Input>, } impl<'a> ParserBuilder<'a> { pub(crate) fn input(mut self, input: Input) -> ParserBuilder<'a> { self.input = Some(input); self } pub(crate) fn sess(mut self, sess: &'a ParseSess) -> ParserBuilder<'a> { self.sess = Some(sess); self } pub(crate) fn build(self) -> Result<Parser<'a>, ParserError> { let sess = self.sess.ok_or(ParserError::NoParseSess)?; let input = self.input.ok_or(ParserError::NoInput)?; let parser = match Self::parser(sess.inner(), input) { Ok(p) => p, Err(db) => { if let Some(diagnostics) = db { sess.emit_diagnostics(diagnostics); return Err(ParserError::ParserCreationError); } return Err(ParserError::ParsePanicError); } }; Ok(Parser { parser }) } fn parser( sess: &'a rustc_session::parse::ParseSess, input: Input, ) -> Result<rustc_parse::parser::Parser<'a>, Option<Vec<Diagnostic>>> { match input { Input::File(ref file) => catch_unwind(AssertUnwindSafe(move || { new_parser_from_file(sess, file, None) })) .map_err(|_| None), Input::Text(text) => rustc_parse::maybe_new_parser_from_source_str( sess, rustc_span::FileName::Custom("stdin".to_owned()), text, ) .map_err(Some), } } } #[derive(Debug, PartialEq)] pub(crate) enum ParserError { NoParseSess, NoInput, ParserCreationError, ParseError, ParsePanicError, } impl<'a> Parser<'a> { pub(crate) fn submod_path_from_attr(attrs: &[ast::Attribute], path: &Path) -> Option<PathBuf> { let path_string = first_attr_value_str_by_name(attrs, sym::path)?.as_str(); // On windows, the base path might have the form // `\\?\foo\bar` in which case it does not tolerate // mixed `/` and `\` separators, so canonicalize // `/` to `\`. #[cfg(windows)] let path_string = path_string.replace("/", "\\"); Some(path.join(&*path_string)) } pub(crate) fn parse_file_as_module( sess: &'a ParseSess, path: &Path, span: Option<Span>, ) -> Result<(Vec<ast::Attribute>, Vec<ptr::P<ast::Item>>, Span), ParserError> { let result = catch_unwind(AssertUnwindSafe(|| { let mut parser = new_parser_from_file(sess.inner(), &path, span); match parser.parse_mod(&TokenKind::Eof) { Ok(result) => Some(result), Err(mut e) => { sess.emit_or_cancel_diagnostic(&mut e); if sess.can_reset_errors() { sess.reset_errors(); } None } } })); match result { Ok(Some(m)) => { if !sess.has_errors() { return Ok(m); } if sess.can_reset_errors() { sess.reset_errors(); return Ok(m); } Err(ParserError::ParseError) } Ok(None) => Err(ParserError::ParseError), Err(..) if path.exists() => Err(ParserError::ParseError), Err(_) => Err(ParserError::ParsePanicError), } } pub(crate) fn parse_crate( input: Input, sess: &'a ParseSess, ) -> Result<ast::Crate, ParserError> { let krate = Parser::parse_crate_inner(input, sess)?; if !sess.has_errors() { return Ok(krate); } if sess.can_reset_errors() { sess.reset_errors(); return Ok(krate); } Err(ParserError::ParseError) } fn parse_crate_inner(input: Input, sess: &'a ParseSess) -> Result<ast::Crate, ParserError> { let mut parser = ParserBuilder::default().input(input).sess(sess).build()?; parser.parse_crate_mod() } fn parse_crate_mod(&mut self) -> Result<ast::Crate, ParserError> { let mut parser = AssertUnwindSafe(&mut self.parser); match catch_unwind(move || parser.parse_crate_mod()) { Ok(Ok(k)) => Ok(k), Ok(Err(mut db)) => { db.emit(); Err(ParserError::ParseError) } Err(_) => Err(ParserError::ParsePanicError), } } pub(crate) fn parse_cfg_if( sess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result<Vec<ast::Item>, &'static str> { match catch_unwind(AssertUnwindSafe(|| Parser::parse_cfg_if_inner(sess, mac))) { Ok(Ok(items)) => Ok(items), Ok(err @ Err(_)) => err, Err(..) => Err("failed to parse cfg_if!"), } } fn parse_cfg_if_inner( sess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result<Vec<ast::Item>, &'static str> { let token_stream = mac.args.inner_tokens(); let mut parser = rustc_parse::stream_to_parser(sess.inner(), token_stream, Some("")); let mut items = vec![]; let mut process_if_cfg = true; while parser.token.kind != TokenKind::Eof { if process_if_cfg { if !parser.eat_keyword(kw::If) { return Err("Expected `if`"); } // Inner attributes are not actually syntactically permitted here, but we don't // care about inner vs outer attributes in this position. Our purpose with this // special case parsing of cfg_if macros is to ensure we can correctly resolve // imported modules that may have a custom `path` defined. // // As such, we just need to advance the parser past the attribute and up to // to the opening brace. // See also https://github.com/rust-lang/rust/pull/79433 parser .parse_attribute(rustc_parse::parser::attr::InnerAttrPolicy::Permitted) .map_err(|_| "Failed to parse attributes")?; } if !parser.eat(&TokenKind::OpenDelim(DelimToken::Brace)) { return Err("Expected an opening brace"); } while parser.token != TokenKind::CloseDelim(DelimToken::Brace) && parser.token.kind != TokenKind::Eof { let item = match parser.parse_item(ForceCollect::No) { Ok(Some(item_ptr)) => item_ptr.into_inner(), Ok(None) => continue, Err(mut err) => { err.cancel(); parser.sess.span_diagnostic.reset_err_count(); return Err( "Expected item inside cfg_if block, but failed to parse it as an item", ); } }; if let ast::ItemKind::Mod(..) = item.kind { items.push(item); } } if !parser.eat(&TokenKind::CloseDelim(DelimToken::Brace)) { return Err("Expected a closing brace"); } if parser.eat(&TokenKind::Eof) { break; } if !parser.eat_keyword(kw::Else) { return Err("Expected `else`"); } process_if_cfg = parser.token.is_keyword(kw::If); } Ok(items) } }
33.382239
99
0.533195
abf0d230f7e36fe1e6ce94bffd0087ee5f2c0d8e
2,197
// Copyright 2021, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mod error; pub use error::MergeMineError; mod helpers; pub use helpers::{ append_merge_mining_tag, construct_monero_data, create_blockhashing_blob_from_block, create_ordered_transaction_hashes_from_block, deserialize_monero_block_from_hex, extract_tari_hash, monero_difficulty, serialize_monero_block_to_hex, }; mod fixed_array; pub use fixed_array::FixedByteArray; mod pow_data; pub use pow_data::MoneroPowData; mod merkle_tree; pub use merkle_tree::{create_merkle_proof, tree_hash}; // Re-exports pub use monero::{ consensus::{deserialize, serialize}, Block as MoneroBlock, BlockHeader as MoneroBlockHeader, };
43.078431
119
0.779244
f96cc4375c855a964feacd3767a2dcd1bb6d0d1d
22,328
pub mod pddl; pub mod sexpr; use crate::chronicles::*; use crate::classical::state::{SvId, World}; use crate::parsing::pddl::{PddlFeature, TypedSymbol}; use crate::chronicles::constraints::Constraint; use crate::parsing::sexpr::SExpr; use anyhow::*; use aries_model::bounds::Bound; use aries_model::lang::*; use aries_model::symbols::SymbolTable; use aries_model::types::TypeHierarchy; use aries_utils::input::{ErrLoc, Loc, Sym}; use itertools::Itertools; use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::ops::Deref; use std::sync::Arc; /// Names for built in types. They contain UTF-8 symbols for sexiness (and to avoid collision with user defined symbols) static TASK_TYPE: &str = "★task★"; static ABSTRACT_TASK_TYPE: &str = "★abstract_task★"; static ACTION_TYPE: &str = "★action★"; static METHOD_TYPE: &str = "★method★"; static PREDICATE_TYPE: &str = "★predicate★"; static OBJECT_TYPE: &str = "★object★"; type Pb = Problem; pub fn pddl_to_chronicles(dom: &pddl::Domain, prob: &pddl::Problem) -> Result<Pb> { // top types in pddl let mut types: Vec<(Sym, Option<Sym>)> = vec![ (TASK_TYPE.into(), None), (ABSTRACT_TASK_TYPE.into(), Some(TASK_TYPE.into())), (ACTION_TYPE.into(), Some(TASK_TYPE.into())), (METHOD_TYPE.into(), None), (PREDICATE_TYPE.into(), None), (OBJECT_TYPE.into(), None), ]; let top_type = OBJECT_TYPE.into(); // determine the top types in the user-defined hierarchy. // this is typically "object" by convention but might something else (e.g. "obj" in some hddl problems). { let all_types: HashSet<&Sym> = dom.types.iter().map(|tpe| &tpe.symbol).collect(); let top_types = dom .types .iter() .filter_map(|tpe| tpe.tpe.as_ref()) .filter(|tpe| !all_types.contains(tpe)) .unique(); for t in top_types { types.push((t.clone(), Some(OBJECT_TYPE.into()))); } } for t in &dom.types { types.push((t.symbol.clone(), t.tpe.clone())); } let ts = TypeHierarchy::new(types)?; let mut symbols: Vec<TypedSymbol> = prob.objects.clone(); for c in &dom.constants { symbols.push(c.clone()); } // predicates are symbols as well, add them to the table for p in &dom.predicates { symbols.push(TypedSymbol::new(&p.name, PREDICATE_TYPE)); } for a in &dom.actions { symbols.push(TypedSymbol::new(&a.name, ACTION_TYPE)); } for t in &dom.tasks { symbols.push(TypedSymbol::new(&t.name, ABSTRACT_TASK_TYPE)); } for m in &dom.methods { symbols.push(TypedSymbol::new(&m.name, METHOD_TYPE)); } let symbols = symbols .drain(..) .map(|ts| (ts.symbol, ts.tpe.unwrap_or_else(|| OBJECT_TYPE.into()))) .collect(); let symbol_table = SymbolTable::new(ts, symbols)?; let mut state_variables = Vec::with_capacity(dom.predicates.len()); for pred in &dom.predicates { let sym = symbol_table .id(&pred.name) .ok_or_else(|| pred.name.invalid("Unknown symbol"))?; let mut args = Vec::with_capacity(pred.args.len() + 1); for a in &pred.args { let tpe = a.tpe.as_ref().unwrap_or(&top_type); let tpe = symbol_table .types .id_of(tpe) .ok_or_else(|| tpe.invalid("Unknown type"))?; args.push(Type::Sym(tpe)); } args.push(Type::Bool); // return type (last one) is a boolean state_variables.push(StateFun { sym, tpe: args }) } let mut context = Ctx::new(Arc::new(symbol_table), state_variables); // Initial chronicle construction let mut init_ch = Chronicle { kind: ChronicleKind::Problem, presence: Bound::TRUE, start: context.origin(), end: context.horizon(), name: vec![], task: None, conditions: vec![], effects: vec![], constraints: vec![], subtasks: vec![], }; // Transforms atoms of an s-expression into the corresponding representation for chronicles let as_model_atom_no_borrow = |atom: &sexpr::SAtom, context: &Ctx| -> Result<SAtom> { let atom = context .model .symbols .id(atom.as_str()) .ok_or_else(|| atom.invalid("Unknown atom"))?; let atom = context.typed_sym(atom); Ok(atom.into()) }; let as_model_atom = |atom: &sexpr::SAtom| as_model_atom_no_borrow(atom, &context); for goal in &prob.goal { let goals = read_conjunction(goal, as_model_atom)?; for TermLoc(goal, loc) in goals { match goal { Term::Binding(sv, value) => init_ch.conditions.push(Condition { start: init_ch.end, end: init_ch.end, state_var: sv, value, }), _ => return Err(loc.invalid("Unsupported in goal expression").into()), } } } // if we have negative preconditions, we need to assume a closed world assumption. // indeed, some preconditions might rely on initial facts being false let closed_world = dom.features.contains(&PddlFeature::NegativePreconditions); for (sv, val) in read_init(&prob.init, closed_world, as_model_atom, &context)? { init_ch.effects.push(Effect { transition_start: init_ch.start, persistence_start: init_ch.start, state_var: sv, value: val, }); } if let Some(ref task_network) = &prob.task_network { read_task_network( &task_network, &as_model_atom_no_borrow, &mut init_ch, None, &mut context, )?; } let init_ch = ChronicleInstance { parameters: vec![], origin: ChronicleOrigin::Original, chronicle: init_ch, }; let mut templates = Vec::new(); for a in &dom.actions { let template = read_chronicle_template(a, &mut context)?; templates.push(template); } for m in &dom.methods { let template = read_chronicle_template(m, &mut context)?; templates.push(template); } let problem = Problem { context, templates, chronicles: vec![init_ch], }; Ok(problem) } /// Transforms PDDL initial facts into binding of state variables to their values /// If `closed_world` is true, then all predicates that are not given a true value will be set to false. fn read_init( initial_facts: &[SExpr], closed_world: bool, as_model_atom: impl Fn(&sexpr::SAtom) -> Result<SAtom>, context: &Ctx, ) -> Result<Vec<(Sv, Atom)>> { let mut facts = Vec::new(); if closed_world { // closed world, every predicate that is not given a true value should be given a false value // to do this, we rely on the classical classical planning state let state_desc = World::new(context.model.symbols.deref().clone(), &context.state_functions)?; let mut s = state_desc.make_new_state(); for init in initial_facts { let pred = read_sv(init, &state_desc)?; s.add(pred); } let sv_to_sv = |sv| -> Vec<SAtom> { state_desc .sv_of(sv) .iter() .map(|&sym| context.typed_sym(sym).into()) .collect() }; for literal in s.literals() { let sv = sv_to_sv(literal.var()); let val: Atom = literal.val().into(); facts.push((sv, val)); } } else { // open world, we only add to the initial facts the one explicitly given in the problem definition for e in initial_facts { match read_term(e, &as_model_atom)? { TermLoc(Term::Binding(sv, val), _) => facts.push((sv, val)), TermLoc(_, loc) => return Err(loc.invalid("Unsupported in initial facts").into()), } } } Ok(facts) } /// Transforms a PDDL action into a Chronicle template fn read_chronicle_template( // pddl_action: &pddl::Action, pddl: impl ChronicleTemplateView, context: &mut Ctx, ) -> Result<ChronicleTemplate> { let top_type = OBJECT_TYPE.into(); let mut params: Vec<Variable> = Vec::new(); let prez_var = context.model.new_bvar("present"); params.push(prez_var.into()); let prez = prez_var.true_lit(); let start = context.model.new_optional_ivar(0, INT_CST_MAX, prez, "start"); params.push(start.into()); let end: IAtom = match pddl.kind() { ChronicleKind::Problem => panic!("unsupported case"), ChronicleKind::Method => { let end = context.model.new_optional_ivar(0, INT_CST_MAX, prez, "end"); params.push(end.into()); end.into() } ChronicleKind::Action => start + 1, }; // name of the chronicle : name of the action + parameters let mut name: Vec<SAtom> = Vec::with_capacity(1 + pddl.parameters().len()); let base_name = pddl.base_name(); name.push( context .typed_sym( context .model .symbols .id(base_name) .ok_or_else(|| base_name.invalid("Unknown atom"))?, ) .into(), ); // Process, the arguments of the action, adding them to the parameters of the chronicle and to the name of the action for arg in pddl.parameters() { let tpe = arg.tpe.as_ref().unwrap_or(&top_type); let tpe = context .model .symbols .types .id_of(tpe) .ok_or_else(|| tpe.invalid("Unknown atom"))?; let arg = context.model.new_optional_sym_var(tpe, prez, &arg.symbol); params.push(arg.into()); name.push(arg.into()); } // Transforms atoms of an s-expression into the corresponding representation for chronicles let as_chronicle_atom_no_borrow = |atom: &sexpr::SAtom, context: &Ctx| -> Result<SAtom> { match pddl .parameters() .iter() .position(|arg| arg.symbol.as_str() == atom.as_str()) { Some(i) => Ok(name[i as usize + 1]), None => { let atom = context .model .symbols .id(atom.as_str()) .ok_or_else(|| atom.invalid("Unknown atom"))?; let atom = context.typed_sym(atom); Ok(atom.into()) } } }; let as_chronicle_atom = |atom: &sexpr::SAtom| -> Result<SAtom> { as_chronicle_atom_no_borrow(atom, context) }; let task = if let Some(task) = pddl.task() { let mut task_name = Vec::with_capacity(task.arguments.len() + 1); task_name.push(as_chronicle_atom(&task.name)?); for task_arg in &task.arguments { task_name.push(as_chronicle_atom(task_arg)?); } task_name } else { // no explicit task (typical for a primitive action), use the name as the task name.clone() }; let mut ch = Chronicle { kind: pddl.kind(), presence: prez, start: start.into(), end, name: name.clone(), task: Some(task), conditions: vec![], effects: vec![], constraints: vec![], subtasks: vec![], }; for eff in pddl.effects() { if pddl.kind() != ChronicleKind::Action { return Err(eff.invalid("Unexpected effect").into()); } let effects = read_conjunction(eff, &as_chronicle_atom)?; for TermLoc(term, loc) in effects { match term { Term::Binding(sv, val) => ch.effects.push(Effect { transition_start: ch.start, persistence_start: ch.end, state_var: sv, value: val, }), _ => return Err(loc.invalid("Unsupported in action effects").into()), } } } // a common pattern in PDDL is to have two effect (not x) et (x) on the same state variable. // this is to force mutual exclusion on x. The semantics of PDDL have the negative effect applied first. // This is already enforced by our translation of a positive effect on x as `]start, end] x = true` // Thus if we have both a positive effect and a negative effect on the same state variable, // we remove the negative one let positive_effects: HashSet<Sv> = ch .effects .iter() .filter(|e| e.value == Atom::from(true)) .map(|e| e.state_var.clone()) .collect(); ch.effects .retain(|e| e.value != Atom::from(false) || !positive_effects.contains(&e.state_var)); for cond in pddl.preconditions() { let effects = read_conjunction(cond, &as_chronicle_atom)?; for TermLoc(term, _) in effects { match term { Term::Binding(sv, val) => { let as_effect_on_same_state_variable = ch .effects .iter() .map(|e| e.state_var.as_slice()) .any(|x| x == sv.as_slice()); // end time of the effect, if it is a method, or there is an effect of the same state variable, // then we have an instantaneous start condition. // Otherwise, the condition spans the entire action let end = if as_effect_on_same_state_variable || pddl.kind() == ChronicleKind::Method { ch.start // there is corresponding effect } else { ch.end // no effect, condition needs to persist until the end of the action }; ch.conditions.push(Condition { start: ch.start, end, state_var: sv, value: val, }); } Term::Eq(a, b) => ch.constraints.push(Constraint::eq(a, b)), Term::Neq(a, b) => ch.constraints.push(Constraint::neq(a, b)), } } } if let Some(tn) = pddl.task_network() { read_task_network(tn, &as_chronicle_atom_no_borrow, &mut ch, Some(&mut params), context)? } let template = ChronicleTemplate { label: Some(pddl.base_name().to_string()), parameters: params, chronicle: ch, }; Ok(template) } /// An adapter to allow treating pddl actions and hddl methods identically trait ChronicleTemplateView { fn kind(&self) -> ChronicleKind; fn base_name(&self) -> &Sym; fn parameters(&self) -> &[TypedSymbol]; fn task(&self) -> Option<&pddl::Task>; fn preconditions(&self) -> &[SExpr]; fn effects(&self) -> &[SExpr]; fn task_network(&self) -> Option<&pddl::TaskNetwork>; } impl ChronicleTemplateView for &pddl::Action { fn kind(&self) -> ChronicleKind { ChronicleKind::Action } fn base_name(&self) -> &Sym { &self.name } fn parameters(&self) -> &[TypedSymbol] { &self.args } fn task(&self) -> Option<&pddl::Task> { None } fn preconditions(&self) -> &[SExpr] { &self.pre } fn effects(&self) -> &[SExpr] { &self.eff } fn task_network(&self) -> Option<&pddl::TaskNetwork> { None } } impl ChronicleTemplateView for &pddl::Method { fn kind(&self) -> ChronicleKind { ChronicleKind::Method } fn base_name(&self) -> &Sym { &self.name } fn parameters(&self) -> &[TypedSymbol] { &self.parameters } fn task(&self) -> Option<&pddl::Task> { Some(&self.task) } fn preconditions(&self) -> &[SExpr] { &self.precondition } fn effects(&self) -> &[SExpr] { &[] } fn task_network(&self) -> Option<&pddl::TaskNetwork> { Some(&self.subtask_network) } } /// Parses a task network and adds its components (subtasks and constraints) to the target `chronicle. /// All newly created variables (timepoints of the subtasks) are added to the new_variables buffer. fn read_task_network( tn: &pddl::TaskNetwork, as_chronicle_atom: &impl Fn(&sexpr::SAtom, &Ctx) -> Result<SAtom>, chronicle: &mut Chronicle, mut new_variables: Option<&mut Vec<Variable>>, context: &mut Ctx, ) -> Result<()> { // stores the start/end timepoints of each named task let mut named_task: HashMap<String, (IVar, IVar)> = HashMap::new(); let presence = chronicle.presence; // creates a new subtask. This will create new variables for the start and end // timepoints of the task and push the `new_variables` vector, if any. let mut make_subtask = |t: &pddl::Task| -> Result<SubTask> { let id = t.id.as_ref().map(|id| id.to_string()); // get the name + parameters of the task let mut task_name = Vec::with_capacity(t.arguments.len() + 1); task_name.push(as_chronicle_atom(&t.name, &context)?); for param in &t.arguments { task_name.push(as_chronicle_atom(param, &context)?); } // create timepoints for the subtask let start = context.model.new_optional_ivar(0, INT_CST_MAX, presence, "task_start"); let end = context.model.new_optional_ivar(0, INT_CST_MAX, presence, "task_end"); if let Some(ref mut params) = new_variables { params.push(start.into()); params.push(end.into()); } if let Some(name) = id.as_ref() { named_task.insert(name.to_string(), (start, end)); } Ok(SubTask { id, start: start.into(), end: end.into(), task: task_name, }) }; for t in &tn.unordered_tasks { let t = make_subtask(t)?; chronicle.subtasks.push(t); } // parse all ordered tasks, adding precedence constraints between subsequent ones let mut previous_end = None; for t in &tn.ordered_tasks { let t = make_subtask(t)?; if let Some(previous_end) = previous_end { chronicle.constraints.push(Constraint::lt(previous_end, t.start)) } previous_end = Some(t.end); chronicle.subtasks.push(t); } for ord in &tn.orderings { let first_end = named_task .get(ord.first_task_id.as_str()) .ok_or_else(|| ord.first_task_id.invalid("Unknown task id"))? .1; let second_start = named_task .get(ord.second_task_id.as_str()) .ok_or_else(|| ord.second_task_id.invalid("Unknown task id"))? .0; chronicle.constraints.push(Constraint::lt(first_end, second_start)); } Ok(()) } enum Term { Binding(Sv, Atom), Eq(Atom, Atom), Neq(Atom, Atom), } struct TermLoc(Term, Loc); fn read_conjunction(e: &SExpr, t: impl Fn(&sexpr::SAtom) -> Result<SAtom>) -> Result<Vec<TermLoc>> { let mut result = Vec::new(); read_conjunction_impl(e, &t, &mut result)?; Ok(result) } fn read_conjunction_impl(e: &SExpr, t: &impl Fn(&sexpr::SAtom) -> Result<SAtom>, out: &mut Vec<TermLoc>) -> Result<()> { if let Some(l) = e.as_list_iter() { if l.is_empty() { return Ok(()); // empty conjunction } } if let Some(conjuncts) = e.as_application("and") { for c in conjuncts.iter() { read_conjunction_impl(c, t, out)?; } } else if let Some([to_negate]) = e.as_application("not") { let TermLoc(t, _) = read_term(to_negate, &t)?; let negated = match t { Term::Binding(sv, value) => { if let Ok(value) = BAtom::try_from(value) { Term::Binding(sv, Atom::from(!value)) } else { return Err(to_negate.invalid("Could not apply 'not' to this expression").into()); } } Term::Eq(a, b) => Term::Neq(a, b), Term::Neq(a, b) => Term::Eq(a, b), }; out.push(TermLoc(negated, e.loc())); } else { // should be directly a predicate out.push(read_term(e, &t)?); } Ok(()) } fn read_term(expr: &SExpr, t: impl Fn(&sexpr::SAtom) -> Result<SAtom>) -> Result<TermLoc> { let mut l = expr.as_list_iter().ok_or_else(|| expr.invalid("Expected a term"))?; if let Some(head) = l.peek() { let head = head.as_atom().ok_or_else(|| head.invalid("Expected an atom"))?; let term = match head.as_str() { "=" => { l.pop_known_atom("=")?; let a = l.pop_atom()?.clone(); let b = l.pop_atom()?.clone(); if let Some(unexpected) = l.next() { return Err(unexpected.invalid("Unexpected expr").into()); } Term::Eq(t(&a)?.into(), t(&b)?.into()) } _ => { let mut sv = Vec::with_capacity(l.len()); for e in l { let atom = e.as_atom().ok_or_else(|| e.invalid("Expected an atom"))?; let atom = t(atom)?; sv.push(atom); } Term::Binding(sv, true.into()) } }; Ok(TermLoc(term, expr.loc())) } else { Err(l.loc().end().invalid("Expected a term").into()) } } fn read_sv(e: &SExpr, desc: &World) -> Result<SvId> { let p = e.as_list().context("Expected s-expression")?; let atoms: Result<Vec<_>, ErrLoc> = p .iter() .map(|e| e.as_atom().ok_or_else(|| e.invalid("Expected atom"))) .collect(); let atom_ids: Result<Vec<_>, ErrLoc> = atoms? .iter() .map(|atom| desc.table.id(atom.as_str()).ok_or_else(|| atom.invalid("Unknown atom"))) .collect(); let atom_ids = atom_ids?; desc.sv_id(atom_ids.as_slice()).with_context(|| { format!( "Unknown predicate {} (wrong number of arguments or badly typed args ?)", desc.table.format(&atom_ids) ) }) }
35.385103
121
0.559656
5b0797843333c666b11e263b0449ca94514d81b7
14,068
/// SnapshotItem is an item contained in a rootmulti.Store snapshot. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct SnapshotItem { /// item is the specific type of snapshot item. #[prost(oneof = "snapshot_item::Item", tags = "1, 2")] pub item: ::core::option::Option<snapshot_item::Item>, } /// Nested message and enum types in `SnapshotItem`. pub mod snapshot_item { /// item is the specific type of snapshot item. use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] #[derive(Clone, PartialEq, ::prost::Oneof)] pub enum Item { #[prost(message, tag = "1")] Store(super::SnapshotStoreItem), #[prost(message, tag = "2")] Iavl(super::SnapshotIavlItem), } } /// SnapshotStoreItem contains metadata about a snapshotted store. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct SnapshotStoreItem { #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, } /// SnapshotIAVLItem is an exported IAVL node. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct SnapshotIavlItem { #[prost(bytes = "vec", tag = "1")] #[serde( serialize_with="crate::utils::bytes_to_base64", deserialize_with="crate::utils::base64_to_bytes" )] pub key: ::prost::alloc::vec::Vec<u8>, #[prost(bytes = "vec", tag = "2")] #[serde( serialize_with="crate::utils::bytes_to_base64", deserialize_with="crate::utils::base64_to_bytes" )] pub value: ::prost::alloc::vec::Vec<u8>, #[prost(int64, tag = "3")] pub version: i64, #[prost(int32, tag = "4")] pub height: i32, } /// CommitInfo defines commit information used by the multi-store when committing /// a version/height. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct CommitInfo { #[prost(int64, tag = "1")] pub version: i64, #[prost(message, repeated, tag = "2")] pub store_infos: ::prost::alloc::vec::Vec<StoreInfo>, } /// StoreInfo defines store-specific commit information. It contains a reference /// between a store name and the commit ID. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct StoreInfo { #[prost(string, tag = "1")] pub name: ::prost::alloc::string::String, #[prost(message, optional, tag = "2")] pub commit_id: ::core::option::Option<CommitId>, } /// CommitID defines the committment information when a specific store is /// committed. #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct CommitId { #[prost(int64, tag = "1")] pub version: i64, #[prost(bytes = "vec", tag = "2")] #[serde( serialize_with="crate::utils::bytes_to_base64", deserialize_with="crate::utils::base64_to_bytes" )] pub hash: ::prost::alloc::vec::Vec<u8>, } /// StoreKVPair is a KVStore KVPair used for listening to state changes (Sets and Deletes) /// It optionally includes the StoreKey for the originating KVStore and a Boolean flag to distinguish between Sets and /// Deletes #[derive(Serialize, Deserialize)] #[serde(default)] #[derive(Clone, PartialEq, ::prost::Message)] pub struct StoreKvPair { /// the store key for the KVStore this pair originates from #[prost(string, tag = "1")] pub store_key: ::prost::alloc::string::String, /// true indicates a delete operation, false indicates a set operation #[prost(bool, tag = "2")] pub delete: bool, #[prost(bytes = "vec", tag = "3")] #[serde( serialize_with="crate::utils::bytes_to_base64", deserialize_with="crate::utils::base64_to_bytes" )] pub key: ::prost::alloc::vec::Vec<u8>, #[prost(bytes = "vec", tag = "4")] #[serde( serialize_with="crate::utils::bytes_to_base64", deserialize_with="crate::utils::base64_to_bytes" )] pub value: ::prost::alloc::vec::Vec<u8>, } #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_SNAPSHOT_ITEM: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.SnapshotItem")] impl ::prost_wkt::MessageSerde for SnapshotItem { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "SnapshotItem" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.SnapshotItem" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_SNAPSHOT_STORE_ITEM: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.SnapshotStoreItem")] impl ::prost_wkt::MessageSerde for SnapshotStoreItem { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "SnapshotStoreItem" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.SnapshotStoreItem" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_SNAPSHOT_IAVL_ITEM: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.SnapshotIAVLItem")] impl ::prost_wkt::MessageSerde for SnapshotIavlItem { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "SnapshotIAVLItem" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.SnapshotIAVLItem" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_COMMIT_INFO: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.CommitInfo")] impl ::prost_wkt::MessageSerde for CommitInfo { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "CommitInfo" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.CommitInfo" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_STORE_INFO: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.StoreInfo")] impl ::prost_wkt::MessageSerde for StoreInfo { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "StoreInfo" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.StoreInfo" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_COMMIT_ID: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.CommitID")] impl ::prost_wkt::MessageSerde for CommitId { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "CommitID" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.CommitID" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } }; #[allow(dead_code)] const IMPL_MESSAGE_SERDE_FOR_STORE_KV_PAIR: () = { use ::prost_wkt::typetag; #[typetag::serde(name = "/cosmos.base.store.v1beta1.StoreKVPair")] impl ::prost_wkt::MessageSerde for StoreKvPair { fn package_name(&self) -> &'static str { "cosmos.base.store.v1beta1" } fn message_name(&self) -> &'static str { "StoreKVPair" } fn type_url(&self) -> &'static str { "/cosmos.base.store.v1beta1.StoreKVPair" } fn new_instance( &self, data: Vec<u8>, ) -> Result<Box<dyn ::prost_wkt::MessageSerde>, ::prost::DecodeError> { let mut target = Self::default(); ::prost::Message::merge(&mut target, data.as_slice())?; let erased: Box<dyn ::prost_wkt::MessageSerde> = Box::new(target); Ok(erased) } fn encoded(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf).expect("Failed to encode message"); buf } fn try_encoded(&self) -> Result<Vec<u8>, ::prost::EncodeError> { let mut buf = Vec::new(); buf.reserve(::prost::Message::encoded_len(self)); ::prost::Message::encode(self, &mut buf)?; Ok(buf) } } };
36.827225
118
0.570372
e67b03b7481c90af16202a212c4e95b176ea5f39
1,584
use azure_sdk_core::prelude::*; use azure_sdk_storage_blob::Blob; use azure_sdk_storage_core::prelude::*; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // First we retrieve the account name and master key from environment variables. let account = std::env::var("STORAGE_ACCOUNT").expect("Set env variable STORAGE_ACCOUNT first!"); let master_key = std::env::var("STORAGE_MASTER_KEY").expect("Set env variable STORAGE_MASTER_KEY first!"); let source_container = std::env::args() .nth(1) .expect("please specify source container name as first command line parameter"); let source_blob = std::env::args() .nth(2) .expect("please specify source blob name as second command line parameter"); let destination_container = std::env::args() .nth(3) .expect("please specify destination container name as third command line parameter"); let destination_blob = std::env::args() .nth(4) .expect("please specify destination blob name as fourth command line parameter"); let client = Client::new(&account, &master_key)?; let source_url = format!("{}/{}/{}", client.blob_uri(), source_container, source_blob); let response = client .copy_blob_from_url() .with_container_name(&destination_container) .with_blob_name(&destination_blob) .with_source_url(&source_url as &str) .with_is_synchronous(true) .finalize() .await?; println!("response == {:?}", response); Ok(()) }
36
97
0.659722
fbccbb3ab25093d9d05f3ce19855e32da12be1b9
2,563
use pgx::*; use serde::{Deserialize, Serialize}; use std::collections::BinaryHeap; use std::cmp::Reverse; pg_module_magic!(); #[derive(Serialize, Deserialize, PostgresType)] pub struct TopState { min_heap: BinaryHeap<Reverse<i32>>, max_heap: BinaryHeap<i32>, n:usize, } impl Default for TopState { fn default() -> Self { Self { min_heap:BinaryHeap::new(),max_heap:BinaryHeap::new(),n:10 } } } impl TopState { fn acc(& mut self, v: i32) { if self.min_heap.len()<self.n{ self.min_heap.push(Reverse(v)); return } // 取出当前最小堆上的最小值 let top = self.min_heap.peek().unwrap().0; // 如果比最小值还小 , 肯定不会是要求的最大的 10 个数值, 直接丢弃 if v<=top{ return } // 插入到最小堆中,然后移除堆中的最小值 self.min_heap.push(Reverse(v)); self.min_heap.pop().unwrap(); return } fn acc_max(& mut self, v: i32) { if self.max_heap.len()<self.n{ self.max_heap.push(v); return } // 取出当前最大堆上的最大值 let top = self.max_heap.peek().unwrap(); // 如果比最大值还大 , 肯定不会是要求的最小的 10 个数值, 直接丢弃 if v>=*top{ return } // 插入到最大堆中,然后移除堆中的最大值 self.max_heap.push(v); self.max_heap.pop().unwrap(); return } } #[pg_extern] fn integer_topn_state_func( mut internal_state: TopState, next_data_value: i32, ) -> TopState { internal_state.acc(next_data_value); internal_state.acc_max(next_data_value); internal_state } #[pg_extern] fn integer_topn_final_func(internal_state: TopState) -> Vec<Vec<i32>> { vec![ internal_state.min_heap.into_sorted_vec().iter().map(|x|x.0).collect(), internal_state.max_heap.into_sorted_vec(), ] } extension_sql!( r#" CREATE AGGREGATE MYMAXN (integer) ( sfunc = integer_topn_state_func, stype = TopState, finalfunc = integer_topn_final_func, initcond = '{"min_heap":[],"max_heap":[],"n":10}' ); "# ); #[cfg(any(test, feature = "pg_test"))] mod tests { use pgx::*; #[pg_test] fn test_hello_my_topn() { // assert_eq!("Hello, my_topn", crate::hello_my_topn()); } } #[cfg(test)] pub mod pg_test { pub fn setup(_options: Vec<&str>) { // perform one-off initialization when the pg_test framework starts } pub fn postgresql_conf_options() -> Vec<&'static str> { // return any postgresql.conf settings that are required for your tests vec![] } }
21.720339
79
0.582911
d9c33fa50bd89ab8f0180b6884ec26399f0c48dd
70,898
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use ast::{self, Ident}; use syntax_pos::{self, BytePos, CharPos, Pos, Span, NO_EXPANSION}; use codemap::{CodeMap, FilePathMapping}; use errors::{FatalError, DiagnosticBuilder}; use parse::{token, ParseSess}; use str::char_at; use symbol::Symbol; use std_unicode::property::Pattern_White_Space; use std::borrow::Cow; use std::char; use std::mem::replace; use std::rc::Rc; pub mod comments; mod tokentrees; mod unicode_chars; #[derive(Clone, PartialEq, Eq, Debug)] pub struct TokenAndSpan { pub tok: token::Token, pub sp: Span, } impl Default for TokenAndSpan { fn default() -> Self { TokenAndSpan { tok: token::Underscore, sp: syntax_pos::DUMMY_SP } } } pub struct StringReader<'a> { pub sess: &'a ParseSess, /// The absolute offset within the codemap of the next character to read pub next_pos: BytePos, /// The absolute offset within the codemap of the current character pub pos: BytePos, /// The column of the next character to read pub col: CharPos, /// The current character (which has been read from self.pos) pub ch: Option<char>, pub filemap: Rc<syntax_pos::FileMap>, /// If Some, stop reading the source at this position (inclusive). pub terminator: Option<BytePos>, /// Whether to record new-lines and multibyte chars in filemap. /// This is only necessary the first time a filemap is lexed. /// If part of a filemap is being re-lexed, this should be set to false. pub save_new_lines_and_multibyte: bool, // cached: pub peek_tok: token::Token, pub peek_span: Span, pub fatal_errs: Vec<DiagnosticBuilder<'a>>, // cache a direct reference to the source text, so that we don't have to // retrieve it via `self.filemap.src.as_ref().unwrap()` all the time. source_text: Rc<String>, /// Stack of open delimiters and their spans. Used for error message. token: token::Token, span: Span, open_braces: Vec<(token::DelimToken, Span)>, pub override_span: Option<Span>, } impl<'a> StringReader<'a> { fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { unwrap_or!(self.override_span, Span::new(lo, hi, NO_EXPANSION)) } fn mk_ident(&self, string: &str) -> Ident { let mut ident = Ident::from_str(string); if let Some(span) = self.override_span { ident.ctxt = span.ctxt(); } ident } fn next_token(&mut self) -> TokenAndSpan where Self: Sized { let res = self.try_next_token(); self.unwrap_or_abort(res) } fn unwrap_or_abort(&mut self, res: Result<TokenAndSpan, ()>) -> TokenAndSpan { match res { Ok(tok) => tok, Err(_) => { self.emit_fatal_errors(); panic!(FatalError); } } } fn try_real_token(&mut self) -> Result<TokenAndSpan, ()> { let mut t = self.try_next_token()?; loop { match t.tok { token::Whitespace | token::Comment | token::Shebang(_) => { t = self.try_next_token()?; } _ => break, } } self.token = t.tok.clone(); self.span = t.sp; Ok(t) } pub fn real_token(&mut self) -> TokenAndSpan { let res = self.try_real_token(); self.unwrap_or_abort(res) } fn is_eof(&self) -> bool { if self.ch.is_none() { return true; } match self.terminator { Some(t) => self.next_pos > t, None => false, } } /// Return the next token. EFFECT: advances the string_reader. pub fn try_next_token(&mut self) -> Result<TokenAndSpan, ()> { assert!(self.fatal_errs.is_empty()); let ret_val = TokenAndSpan { tok: replace(&mut self.peek_tok, token::Underscore), sp: self.peek_span, }; self.advance_token()?; Ok(ret_val) } fn fatal(&self, m: &str) -> FatalError { self.fatal_span(self.peek_span, m) } pub fn emit_fatal_errors(&mut self) { for err in &mut self.fatal_errs { err.emit(); } self.fatal_errs.clear(); } pub fn peek(&self) -> TokenAndSpan { // FIXME(pcwalton): Bad copy! TokenAndSpan { tok: self.peek_tok.clone(), sp: self.peek_span, } } } impl<'a> StringReader<'a> { /// For comments.rs, which hackily pokes into next_pos and ch pub fn new_raw(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self { let mut sr = StringReader::new_raw_internal(sess, filemap); sr.bump(); sr } fn new_raw_internal(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self { if filemap.src.is_none() { sess.span_diagnostic.bug(&format!("Cannot lex filemap without source: {}", filemap.name)); } let source_text = (*filemap.src.as_ref().unwrap()).clone(); StringReader { sess, next_pos: filemap.start_pos, pos: filemap.start_pos, col: CharPos(0), ch: Some('\n'), filemap, terminator: None, save_new_lines_and_multibyte: true, // dummy values; not read peek_tok: token::Eof, peek_span: syntax_pos::DUMMY_SP, source_text, fatal_errs: Vec::new(), token: token::Eof, span: syntax_pos::DUMMY_SP, open_braces: Vec::new(), override_span: None, } } pub fn new(sess: &'a ParseSess, filemap: Rc<syntax_pos::FileMap>) -> Self { let mut sr = StringReader::new_raw(sess, filemap); if sr.advance_token().is_err() { sr.emit_fatal_errors(); panic!(FatalError); } sr } pub fn retokenize(sess: &'a ParseSess, mut span: Span) -> Self { let begin = sess.codemap().lookup_byte_offset(span.lo()); let end = sess.codemap().lookup_byte_offset(span.hi()); // Make the range zero-length if the span is invalid. if span.lo() > span.hi() || begin.fm.start_pos != end.fm.start_pos { span = span.with_hi(span.lo()); } let mut sr = StringReader::new_raw_internal(sess, begin.fm); // Seek the lexer to the right byte range. sr.save_new_lines_and_multibyte = false; sr.next_pos = span.lo(); sr.terminator = Some(span.hi()); sr.bump(); if sr.advance_token().is_err() { sr.emit_fatal_errors(); panic!(FatalError); } sr } pub fn ch_is(&self, c: char) -> bool { self.ch == Some(c) } /// Report a fatal lexical error with a given span. pub fn fatal_span(&self, sp: Span, m: &str) -> FatalError { self.sess.span_diagnostic.span_fatal(sp, m) } /// Report a lexical error with a given span. pub fn err_span(&self, sp: Span, m: &str) { self.sess.span_diagnostic.span_err(sp, m) } /// Report a fatal error spanning [`from_pos`, `to_pos`). fn fatal_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) -> FatalError { self.fatal_span(self.mk_sp(from_pos, to_pos), m) } /// Report a lexical error spanning [`from_pos`, `to_pos`). fn err_span_(&self, from_pos: BytePos, to_pos: BytePos, m: &str) { self.err_span(self.mk_sp(from_pos, to_pos), m) } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an /// escaped character to the error message fn fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> FatalError { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } self.fatal_span_(from_pos, to_pos, &m[..]) } fn struct_fatal_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> DiagnosticBuilder<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } self.sess.span_diagnostic.struct_span_fatal(self.mk_sp(from_pos, to_pos), &m[..]) } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending an /// escaped character to the error message fn err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } self.err_span_(from_pos, to_pos, &m[..]); } fn struct_err_span_char(&self, from_pos: BytePos, to_pos: BytePos, m: &str, c: char) -> DiagnosticBuilder<'a> { let mut m = m.to_string(); m.push_str(": "); for c in c.escape_default() { m.push(c) } self.sess.span_diagnostic.struct_span_err(self.mk_sp(from_pos, to_pos), &m[..]) } /// Report a lexical error spanning [`from_pos`, `to_pos`), appending the /// offending string to the error message fn fatal_span_verbose(&self, from_pos: BytePos, to_pos: BytePos, mut m: String) -> FatalError { m.push_str(": "); let from = self.byte_offset(from_pos).to_usize(); let to = self.byte_offset(to_pos).to_usize(); m.push_str(&self.source_text[from..to]); self.fatal_span_(from_pos, to_pos, &m[..]) } /// Advance peek_tok and peek_span to refer to the next token, and /// possibly update the interner. fn advance_token(&mut self) -> Result<(), ()> { match self.scan_whitespace_or_comment() { Some(comment) => { self.peek_span = comment.sp; self.peek_tok = comment.tok; } None => { if self.is_eof() { self.peek_tok = token::Eof; self.peek_span = self.mk_sp(self.filemap.end_pos, self.filemap.end_pos); } else { let start_bytepos = self.pos; self.peek_tok = self.next_token_inner()?; self.peek_span = self.mk_sp(start_bytepos, self.pos); }; } } Ok(()) } fn byte_offset(&self, pos: BytePos) -> BytePos { (pos - self.filemap.start_pos) } /// Calls `f` with a string slice of the source text spanning from `start` /// up to but excluding `self.pos`, meaning the slice does not include /// the character `self.ch`. pub fn with_str_from<T, F>(&self, start: BytePos, f: F) -> T where F: FnOnce(&str) -> T { self.with_str_from_to(start, self.pos, f) } /// Create a Name from a given offset to the current offset, each /// adjusted 1 towards each other (assumes that on either side there is a /// single-byte delimiter). pub fn name_from(&self, start: BytePos) -> ast::Name { debug!("taking an ident from {:?} to {:?}", start, self.pos); self.with_str_from(start, Symbol::intern) } /// As name_from, with an explicit endpoint. pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name { debug!("taking an ident from {:?} to {:?}", start, end); self.with_str_from_to(start, end, Symbol::intern) } /// Calls `f` with a string slice of the source text spanning from `start` /// up to but excluding `end`. fn with_str_from_to<T, F>(&self, start: BytePos, end: BytePos, f: F) -> T where F: FnOnce(&str) -> T { f(&self.source_text[self.byte_offset(start).to_usize()..self.byte_offset(end).to_usize()]) } /// Converts CRLF to LF in the given string, raising an error on bare CR. fn translate_crlf<'b>(&self, start: BytePos, s: &'b str, errmsg: &'b str) -> Cow<'b, str> { let mut i = 0; while i < s.len() { let ch = char_at(s, i); let next = i + ch.len_utf8(); if ch == '\r' { if next < s.len() && char_at(s, next) == '\n' { return translate_crlf_(self, start, s, errmsg, i).into(); } let pos = start + BytePos(i as u32); let end_pos = start + BytePos(next as u32); self.err_span_(pos, end_pos, errmsg); } i = next; } return s.into(); fn translate_crlf_(rdr: &StringReader, start: BytePos, s: &str, errmsg: &str, mut i: usize) -> String { let mut buf = String::with_capacity(s.len()); let mut j = 0; while i < s.len() { let ch = char_at(s, i); let next = i + ch.len_utf8(); if ch == '\r' { if j < i { buf.push_str(&s[j..i]); } j = next; if next >= s.len() || char_at(s, next) != '\n' { let pos = start + BytePos(i as u32); let end_pos = start + BytePos(next as u32); rdr.err_span_(pos, end_pos, errmsg); } } i = next; } if j < s.len() { buf.push_str(&s[j..]); } buf } } /// Advance the StringReader by one character. If a newline is /// discovered, add it to the FileMap's list of line start offsets. pub fn bump(&mut self) { let new_pos = self.next_pos; let new_byte_offset = self.byte_offset(new_pos).to_usize(); let end = self.terminator.map_or(self.source_text.len(), |t| { self.byte_offset(t).to_usize() }); if new_byte_offset < end { let old_ch_is_newline = self.ch.unwrap() == '\n'; let new_ch = char_at(&self.source_text, new_byte_offset); let new_ch_len = new_ch.len_utf8(); self.ch = Some(new_ch); self.pos = new_pos; self.next_pos = new_pos + Pos::from_usize(new_ch_len); if old_ch_is_newline { if self.save_new_lines_and_multibyte { self.filemap.next_line(self.pos); } self.col = CharPos(0); } else { self.col = self.col + CharPos(1); } if new_ch_len > 1 { if self.save_new_lines_and_multibyte { self.filemap.record_multibyte_char(self.pos, new_ch_len); } } self.filemap.record_width(self.pos, new_ch); } else { self.ch = None; self.pos = new_pos; } } pub fn nextch(&self) -> Option<char> { let offset = self.byte_offset(self.next_pos).to_usize(); if offset < self.source_text.len() { Some(char_at(&self.source_text, offset)) } else { None } } pub fn nextch_is(&self, c: char) -> bool { self.nextch() == Some(c) } pub fn nextnextch(&self) -> Option<char> { let offset = self.byte_offset(self.next_pos).to_usize(); let s = &self.source_text[..]; if offset >= s.len() { return None; } let next = offset + char_at(s, offset).len_utf8(); if next < s.len() { Some(char_at(s, next)) } else { None } } pub fn nextnextch_is(&self, c: char) -> bool { self.nextnextch() == Some(c) } /// Eats <XID_start><XID_continue>*, if possible. fn scan_optional_raw_name(&mut self) -> Option<ast::Name> { if !ident_start(self.ch) { return None; } let start = self.pos; while ident_continue(self.ch) { self.bump(); } self.with_str_from(start, |string| { if string == "_" { self.sess.span_diagnostic .struct_span_warn(self.mk_sp(start, self.pos), "underscore literal suffix is not allowed") .warn("this was previously accepted by the compiler but is \ being phased out; it will become a hard error in \ a future release!") .note("for more information, see issue #42326 \ <https://github.com/rust-lang/rust/issues/42326>") .emit(); None } else { Some(Symbol::intern(string)) } }) } /// PRECONDITION: self.ch is not whitespace /// Eats any kind of comment. fn scan_comment(&mut self) -> Option<TokenAndSpan> { if let Some(c) = self.ch { if c.is_whitespace() { let msg = "called consume_any_line_comment, but there was whitespace"; self.sess.span_diagnostic.span_err(self.mk_sp(self.pos, self.pos), msg); } } if self.ch_is('/') { match self.nextch() { Some('/') => { self.bump(); self.bump(); // line comments starting with "///" or "//!" are doc-comments let doc_comment = (self.ch_is('/') && !self.nextch_is('/')) || self.ch_is('!'); let start_bpos = self.pos - BytePos(2); while !self.is_eof() { match self.ch.unwrap() { '\n' => break, '\r' => { if self.nextch_is('\n') { // CRLF break; } else if doc_comment { self.err_span_(self.pos, self.next_pos, "bare CR not allowed in doc-comment"); } } _ => (), } self.bump(); } if doc_comment { self.with_str_from(start_bpos, |string| { // comments with only more "/"s are not doc comments let tok = if is_doc_comment(string) { token::DocComment(Symbol::intern(string)) } else { token::Comment }; Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos), }) }) } else { Some(TokenAndSpan { tok: token::Comment, sp: self.mk_sp(start_bpos, self.pos), }) } } Some('*') => { self.bump(); self.bump(); self.scan_block_comment() } _ => None, } } else if self.ch_is('#') { if self.nextch_is('!') { // Parse an inner attribute. if self.nextnextch_is('[') { return None; } // I guess this is the only way to figure out if // we're at the beginning of the file... let cmap = CodeMap::new(FilePathMapping::empty()); cmap.files.borrow_mut().push(self.filemap.clone()); let loc = cmap.lookup_char_pos_adj(self.pos); debug!("Skipping a shebang"); if loc.line == 1 && loc.col == CharPos(0) { // FIXME: Add shebang "token", return it let start = self.pos; while !self.ch_is('\n') && !self.is_eof() { self.bump(); } return Some(TokenAndSpan { tok: token::Shebang(self.name_from(start)), sp: self.mk_sp(start, self.pos), }); } } None } else { None } } /// If there is whitespace, shebang, or a comment, scan it. Otherwise, /// return None. fn scan_whitespace_or_comment(&mut self) -> Option<TokenAndSpan> { match self.ch.unwrap_or('\0') { // # to handle shebang at start of file -- this is the entry point // for skipping over all "junk" '/' | '#' => { let c = self.scan_comment(); debug!("scanning a comment {:?}", c); c }, c if is_pattern_whitespace(Some(c)) => { let start_bpos = self.pos; while is_pattern_whitespace(self.ch) { self.bump(); } let c = Some(TokenAndSpan { tok: token::Whitespace, sp: self.mk_sp(start_bpos, self.pos), }); debug!("scanning whitespace: {:?}", c); c } _ => None, } } /// Might return a sugared-doc-attr fn scan_block_comment(&mut self) -> Option<TokenAndSpan> { // block comments starting with "/**" or "/*!" are doc-comments let is_doc_comment = self.ch_is('*') || self.ch_is('!'); let start_bpos = self.pos - BytePos(2); let mut level: isize = 1; let mut has_cr = false; while level > 0 { if self.is_eof() { let msg = if is_doc_comment { "unterminated block doc-comment" } else { "unterminated block comment" }; let last_bpos = self.pos; panic!(self.fatal_span_(start_bpos, last_bpos, msg)); } let n = self.ch.unwrap(); match n { '/' if self.nextch_is('*') => { level += 1; self.bump(); } '*' if self.nextch_is('/') => { level -= 1; self.bump(); } '\r' => { has_cr = true; } _ => (), } self.bump(); } self.with_str_from(start_bpos, |string| { // but comments with only "*"s between two "/"s are not let tok = if is_block_doc_comment(string) { let string = if has_cr { self.translate_crlf(start_bpos, string, "bare CR not allowed in block doc-comment") } else { string.into() }; token::DocComment(Symbol::intern(&string[..])) } else { token::Comment }; Some(TokenAndSpan { tok, sp: self.mk_sp(start_bpos, self.pos), }) }) } /// Scan through any digits (base `scan_radix`) or underscores, /// and return how many digits there were. /// /// `real_radix` represents the true radix of the number we're /// interested in, and errors will be emitted for any digits /// between `real_radix` and `scan_radix`. fn scan_digits(&mut self, real_radix: u32, scan_radix: u32) -> usize { assert!(real_radix <= scan_radix); let mut len = 0; loop { let c = self.ch; if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } match c.and_then(|cc| cc.to_digit(scan_radix)) { Some(_) => { debug!("{:?} in scan_digits", c); // check that the hypothetical digit is actually // in range for the true radix if c.unwrap().to_digit(real_radix).is_none() { self.err_span_(self.pos, self.next_pos, &format!("invalid digit for a base {} literal", real_radix)); } len += 1; self.bump(); } _ => return len, } } } /// Lex a LIT_INTEGER or a LIT_FLOAT fn scan_number(&mut self, c: char) -> token::Lit { let num_digits; let mut base = 10; let start_bpos = self.pos; self.bump(); if c == '0' { match self.ch.unwrap_or('\0') { 'b' => { self.bump(); base = 2; num_digits = self.scan_digits(2, 10); } 'o' => { self.bump(); base = 8; num_digits = self.scan_digits(8, 10); } 'x' => { self.bump(); base = 16; num_digits = self.scan_digits(16, 16); } '0'...'9' | '_' | '.' | 'e' | 'E' => { num_digits = self.scan_digits(10, 10) + 1; } _ => { // just a 0 return token::Integer(self.name_from(start_bpos)); } } } else if c.is_digit(10) { num_digits = self.scan_digits(10, 10) + 1; } else { num_digits = 0; } if num_digits == 0 { self.err_span_(start_bpos, self.pos, "no valid digits found for number"); return token::Integer(Symbol::intern("0")); } // might be a float, but don't be greedy if this is actually an // integer literal followed by field/method access or a range pattern // (`0..2` and `12.foo()`) if self.ch_is('.') && !self.nextch_is('.') && !ident_start(self.nextch()) { // might have stuff after the ., and if it does, it needs to start // with a number self.bump(); if self.ch.unwrap_or('\0').is_digit(10) { self.scan_digits(10, 10); self.scan_float_exponent(); } let pos = self.pos; self.check_float_base(start_bpos, pos, base); token::Float(self.name_from(start_bpos)) } else { // it might be a float if it has an exponent if self.ch_is('e') || self.ch_is('E') { self.scan_float_exponent(); let pos = self.pos; self.check_float_base(start_bpos, pos, base); return token::Float(self.name_from(start_bpos)); } // but we certainly have an integer! token::Integer(self.name_from(start_bpos)) } } /// Scan over `n_digits` hex digits, stopping at `delim`, reporting an /// error if too many or too few digits are encountered. fn scan_hex_digits(&mut self, n_digits: usize, delim: char, below_0x7f_only: bool) -> bool { debug!("scanning {} digits until {:?}", n_digits, delim); let start_bpos = self.pos; let mut accum_int = 0; let mut valid = true; for _ in 0..n_digits { if self.is_eof() { let last_bpos = self.pos; panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated numeric character escape")); } if self.ch_is(delim) { let last_bpos = self.pos; self.err_span_(start_bpos, last_bpos, "numeric character escape is too short"); valid = false; break; } let c = self.ch.unwrap_or('\x00'); accum_int *= 16; accum_int += c.to_digit(16).unwrap_or_else(|| { self.err_span_char(self.pos, self.next_pos, "invalid character in numeric character escape", c); valid = false; 0 }); self.bump(); } if below_0x7f_only && accum_int >= 0x80 { self.err_span_(start_bpos, self.pos, "this form of character escape may only be used with characters in \ the range [\\x00-\\x7f]"); valid = false; } match char::from_u32(accum_int) { Some(_) => valid, None => { let last_bpos = self.pos; self.err_span_(start_bpos, last_bpos, "invalid numeric character escape"); false } } } /// Scan for a single (possibly escaped) byte or char /// in a byte, (non-raw) byte string, char, or (non-raw) string literal. /// `start` is the position of `first_source_char`, which is already consumed. /// /// Returns true if there was a valid char/byte, false otherwise. fn scan_char_or_byte(&mut self, start: BytePos, first_source_char: char, ascii_only: bool, delim: char) -> bool { match first_source_char { '\\' => { // '\X' for some X must be a character constant: let escaped = self.ch; let escaped_pos = self.pos; self.bump(); match escaped { None => {} // EOF here is an error that will be checked later. Some(e) => { return match e { 'n' | 'r' | 't' | '\\' | '\'' | '"' | '0' => true, 'x' => self.scan_byte_escape(delim, !ascii_only), 'u' => { let valid = if self.ch_is('{') { self.scan_unicode_escape(delim) && !ascii_only } else { let span = self.mk_sp(start, self.pos); self.sess.span_diagnostic .struct_span_err(span, "incorrect unicode escape sequence") .span_help(span, "format of unicode escape sequences is \ `\\u{…}`") .emit(); false }; if ascii_only { self.err_span_(start, self.pos, "unicode escape sequences cannot be used as a \ byte or in a byte string"); } valid } '\n' if delim == '"' => { self.consume_whitespace(); true } '\r' if delim == '"' && self.ch_is('\n') => { self.consume_whitespace(); true } c => { let pos = self.pos; let mut err = self.struct_err_span_char(escaped_pos, pos, if ascii_only { "unknown byte escape" } else { "unknown character \ escape" }, c); if e == '\r' { err.span_help(self.mk_sp(escaped_pos, pos), "this is an isolated carriage return; consider \ checking your editor and version control \ settings"); } if (e == '{' || e == '}') && !ascii_only { err.span_help(self.mk_sp(escaped_pos, pos), "if used in a formatting string, curly braces \ are escaped with `{{` and `}}`"); } err.emit(); false } } } } } '\t' | '\n' | '\r' | '\'' if delim == '\'' => { let pos = self.pos; self.err_span_char(start, pos, if ascii_only { "byte constant must be escaped" } else { "character constant must be escaped" }, first_source_char); return false; } '\r' => { if self.ch_is('\n') { self.bump(); return true; } else { self.err_span_(start, self.pos, "bare CR not allowed in string, use \\r instead"); return false; } } _ => { if ascii_only && first_source_char > '\x7F' { let pos = self.pos; self.err_span_(start, pos, "byte constant must be ASCII. Use a \\xHH escape for a \ non-ASCII byte"); return false; } } } true } /// Scan over a `\u{...}` escape /// /// At this point, we have already seen the `\` and the `u`, the `{` is the current character. /// We will read a hex number (with `_` separators), with 1 to 6 actual digits, /// and pass over the `}`. fn scan_unicode_escape(&mut self, delim: char) -> bool { self.bump(); // past the { let start_bpos = self.pos; let mut valid = true; if let Some('_') = self.ch { // disallow leading `_` self.err_span_(self.pos, self.next_pos, "invalid start of unicode escape"); valid = false; } let count = self.scan_digits(16, 16); if count > 6 { self.err_span_(start_bpos, self.pos, "overlong unicode escape (must have at most 6 hex digits)"); valid = false; } loop { match self.ch { Some('}') => { if valid && count == 0 { self.err_span_(start_bpos, self.pos, "empty unicode escape (must have at least 1 hex digit)"); valid = false; } self.bump(); // past the ending `}` break; }, Some(c) => { if c == delim { self.err_span_(self.pos, self.pos, "unterminated unicode escape (needed a `}`)"); valid = false; break; } else if valid { self.err_span_char(start_bpos, self.pos, "invalid character in unicode escape", c); valid = false; } }, None => { panic!(self.fatal_span_(start_bpos, self.pos, "unterminated unicode escape (found EOF)")); } } self.bump(); } valid } /// Scan over a float exponent. fn scan_float_exponent(&mut self) { if self.ch_is('e') || self.ch_is('E') { self.bump(); if self.ch_is('-') || self.ch_is('+') { self.bump(); } if self.scan_digits(10, 10) == 0 { self.err_span_(self.pos, self.next_pos, "expected at least one digit in exponent") } } } /// Check that a base is valid for a floating literal, emitting a nice /// error if it isn't. fn check_float_base(&mut self, start_bpos: BytePos, last_bpos: BytePos, base: usize) { match base { 16 => { self.err_span_(start_bpos, last_bpos, "hexadecimal float literal is not supported") } 8 => { self.err_span_(start_bpos, last_bpos, "octal float literal is not supported") } 2 => { self.err_span_(start_bpos, last_bpos, "binary float literal is not supported") } _ => (), } } fn binop(&mut self, op: token::BinOpToken) -> token::Token { self.bump(); if self.ch_is('=') { self.bump(); token::BinOpEq(op) } else { token::BinOp(op) } } /// Return the next token from the string, advances the input past that /// token, and updates the interner fn next_token_inner(&mut self) -> Result<token::Token, ()> { let c = self.ch; if ident_start(c) && match (c.unwrap(), self.nextch(), self.nextnextch()) { // Note: r as in r" or r#" is part of a raw string literal, // b as in b' is part of a byte literal. // They are not identifiers, and are handled further down. ('r', Some('"'), _) | ('r', Some('#'), _) | ('b', Some('"'), _) | ('b', Some('\''), _) | ('b', Some('r'), Some('"')) | ('b', Some('r'), Some('#')) => false, _ => true, } { let start = self.pos; while ident_continue(self.ch) { self.bump(); } return Ok(self.with_str_from(start, |string| { if string == "_" { token::Underscore } else { // FIXME: perform NFKC normalization here. (Issue #2253) token::Ident(self.mk_ident(string)) } })); } if is_dec_digit(c) { let num = self.scan_number(c.unwrap()); let suffix = self.scan_optional_raw_name(); debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix); return Ok(token::Literal(num, suffix)); } match c.expect("next_token_inner called at EOF") { // One-byte tokens. ';' => { self.bump(); Ok(token::Semi) } ',' => { self.bump(); Ok(token::Comma) } '.' => { self.bump(); if self.ch_is('.') { self.bump(); if self.ch_is('.') { self.bump(); Ok(token::DotDotDot) } else if self.ch_is('=') { self.bump(); Ok(token::DotDotEq) } else { Ok(token::DotDot) } } else { Ok(token::Dot) } } '(' => { self.bump(); Ok(token::OpenDelim(token::Paren)) } ')' => { self.bump(); Ok(token::CloseDelim(token::Paren)) } '{' => { self.bump(); Ok(token::OpenDelim(token::Brace)) } '}' => { self.bump(); Ok(token::CloseDelim(token::Brace)) } '[' => { self.bump(); Ok(token::OpenDelim(token::Bracket)) } ']' => { self.bump(); Ok(token::CloseDelim(token::Bracket)) } '@' => { self.bump(); Ok(token::At) } '#' => { self.bump(); Ok(token::Pound) } '~' => { self.bump(); Ok(token::Tilde) } '?' => { self.bump(); Ok(token::Question) } ':' => { self.bump(); if self.ch_is(':') { self.bump(); Ok(token::ModSep) } else { Ok(token::Colon) } } '$' => { self.bump(); Ok(token::Dollar) } // Multi-byte tokens. '=' => { self.bump(); if self.ch_is('=') { self.bump(); Ok(token::EqEq) } else if self.ch_is('>') { self.bump(); Ok(token::FatArrow) } else { Ok(token::Eq) } } '!' => { self.bump(); if self.ch_is('=') { self.bump(); Ok(token::Ne) } else { Ok(token::Not) } } '<' => { self.bump(); match self.ch.unwrap_or('\x00') { '=' => { self.bump(); Ok(token::Le) } '<' => { Ok(self.binop(token::Shl)) } '-' => { self.bump(); match self.ch.unwrap_or('\x00') { _ => { Ok(token::LArrow) } } } _ => { Ok(token::Lt) } } } '>' => { self.bump(); match self.ch.unwrap_or('\x00') { '=' => { self.bump(); Ok(token::Ge) } '>' => { Ok(self.binop(token::Shr)) } _ => { Ok(token::Gt) } } } '\'' => { // Either a character constant 'a' OR a lifetime name 'abc let start_with_quote = self.pos; self.bump(); let start = self.pos; // the eof will be picked up by the final `'` check below let c2 = self.ch.unwrap_or('\x00'); self.bump(); // If the character is an ident start not followed by another single // quote, then this is a lifetime name: if ident_start(Some(c2)) && !self.ch_is('\'') { while ident_continue(self.ch) { self.bump(); } // lifetimes shouldn't end with a single quote // if we find one, then this is an invalid character literal if self.ch_is('\'') { panic!(self.fatal_span_verbose( start_with_quote, self.next_pos, String::from("character literal may only contain one codepoint"))); } // Include the leading `'` in the real identifier, for macro // expansion purposes. See #12512 for the gory details of why // this is necessary. let ident = self.with_str_from(start, |lifetime_name| { self.mk_ident(&format!("'{}", lifetime_name)) }); return Ok(token::Lifetime(ident)); } let valid = self.scan_char_or_byte(start, c2, // ascii_only = false, '\''); if !self.ch_is('\'') { panic!(self.fatal_span_verbose( start_with_quote, self.pos, String::from("character literal may only contain one codepoint"))); } let id = if valid { self.name_from(start) } else { Symbol::intern("0") }; self.bump(); // advance ch past token let suffix = self.scan_optional_raw_name(); Ok(token::Literal(token::Char(id), suffix)) } 'b' => { self.bump(); let lit = match self.ch { Some('\'') => self.scan_byte(), Some('"') => self.scan_byte_string(), Some('r') => self.scan_raw_byte_string(), _ => unreachable!(), // Should have been a token::Ident above. }; let suffix = self.scan_optional_raw_name(); Ok(token::Literal(lit, suffix)) } '"' => { let start_bpos = self.pos; let mut valid = true; self.bump(); while !self.ch_is('"') { if self.is_eof() { let last_bpos = self.pos; panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated double quote string")); } let ch_start = self.pos; let ch = self.ch.unwrap(); self.bump(); valid &= self.scan_char_or_byte(ch_start, ch, // ascii_only = false, '"'); } // adjust for the ASCII " at the start of the literal let id = if valid { self.name_from(start_bpos + BytePos(1)) } else { Symbol::intern("??") }; self.bump(); let suffix = self.scan_optional_raw_name(); Ok(token::Literal(token::Str_(id), suffix)) } 'r' => { let start_bpos = self.pos; self.bump(); let mut hash_count = 0; while self.ch_is('#') { self.bump(); hash_count += 1; } if self.is_eof() { let last_bpos = self.pos; panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string")); } else if !self.ch_is('"') { let last_bpos = self.pos; let curr_char = self.ch.unwrap(); panic!(self.fatal_span_char(start_bpos, last_bpos, "found invalid character; only `#` is allowed \ in raw string delimitation", curr_char)); } self.bump(); let content_start_bpos = self.pos; let mut content_end_bpos; let mut valid = true; 'outer: loop { if self.is_eof() { let last_bpos = self.pos; panic!(self.fatal_span_(start_bpos, last_bpos, "unterminated raw string")); } // if self.ch_is('"') { // content_end_bpos = self.pos; // for _ in 0..hash_count { // self.bump(); // if !self.ch_is('#') { // continue 'outer; let c = self.ch.unwrap(); match c { '"' => { content_end_bpos = self.pos; for _ in 0..hash_count { self.bump(); if !self.ch_is('#') { continue 'outer; } } break; } '\r' => { if !self.nextch_is('\n') { let last_bpos = self.pos; self.err_span_(start_bpos, last_bpos, "bare CR not allowed in raw string, use \\r \ instead"); valid = false; } } _ => (), } self.bump(); } self.bump(); let id = if valid { self.name_from_to(content_start_bpos, content_end_bpos) } else { Symbol::intern("??") }; let suffix = self.scan_optional_raw_name(); Ok(token::Literal(token::StrRaw(id, hash_count), suffix)) } '-' => { if self.nextch_is('>') { self.bump(); self.bump(); Ok(token::RArrow) } else { Ok(self.binop(token::Minus)) } } '&' => { if self.nextch_is('&') { self.bump(); self.bump(); Ok(token::AndAnd) } else { Ok(self.binop(token::And)) } } '|' => { match self.nextch() { Some('|') => { self.bump(); self.bump(); Ok(token::OrOr) } _ => { Ok(self.binop(token::Or)) } } } '+' => { Ok(self.binop(token::Plus)) } '*' => { Ok(self.binop(token::Star)) } '/' => { Ok(self.binop(token::Slash)) } '^' => { Ok(self.binop(token::Caret)) } '%' => { Ok(self.binop(token::Percent)) } c => { let last_bpos = self.pos; let bpos = self.next_pos; let mut err = self.struct_fatal_span_char(last_bpos, bpos, "unknown start of token", c); unicode_chars::check_for_substitution(self, c, &mut err); self.fatal_errs.push(err); Err(()) } } } fn consume_whitespace(&mut self) { while is_pattern_whitespace(self.ch) && !self.is_eof() { self.bump(); } } fn read_to_eol(&mut self) -> String { let mut val = String::new(); while !self.ch_is('\n') && !self.is_eof() { val.push(self.ch.unwrap()); self.bump(); } if self.ch_is('\n') { self.bump(); } val } fn read_one_line_comment(&mut self) -> String { let val = self.read_to_eol(); assert!((val.as_bytes()[0] == b'/' && val.as_bytes()[1] == b'/') || (val.as_bytes()[0] == b'#' && val.as_bytes()[1] == b'!')); val } fn consume_non_eol_whitespace(&mut self) { while is_pattern_whitespace(self.ch) && !self.ch_is('\n') && !self.is_eof() { self.bump(); } } fn peeking_at_comment(&self) -> bool { (self.ch_is('/') && self.nextch_is('/')) || (self.ch_is('/') && self.nextch_is('*')) || // consider shebangs comments, but not inner attributes (self.ch_is('#') && self.nextch_is('!') && !self.nextnextch_is('[')) } fn scan_byte(&mut self) -> token::Lit { self.bump(); let start = self.pos; // the eof will be picked up by the final `'` check below let c2 = self.ch.unwrap_or('\x00'); self.bump(); let valid = self.scan_char_or_byte(start, c2, // ascii_only = true, '\''); if !self.ch_is('\'') { // Byte offsetting here is okay because the // character before position `start` are an // ascii single quote and ascii 'b'. let pos = self.pos; panic!(self.fatal_span_verbose(start - BytePos(2), pos, "unterminated byte constant".to_string())); } let id = if valid { self.name_from(start) } else { Symbol::intern("?") }; self.bump(); // advance ch past token token::Byte(id) } fn scan_byte_escape(&mut self, delim: char, below_0x7f_only: bool) -> bool { self.scan_hex_digits(2, delim, below_0x7f_only) } fn scan_byte_string(&mut self) -> token::Lit { self.bump(); let start = self.pos; let mut valid = true; while !self.ch_is('"') { if self.is_eof() { let pos = self.pos; panic!(self.fatal_span_(start, pos, "unterminated double quote byte string")); } let ch_start = self.pos; let ch = self.ch.unwrap(); self.bump(); valid &= self.scan_char_or_byte(ch_start, ch, // ascii_only = true, '"'); } let id = if valid { self.name_from(start) } else { Symbol::intern("??") }; self.bump(); token::ByteStr(id) } fn scan_raw_byte_string(&mut self) -> token::Lit { let start_bpos = self.pos; self.bump(); let mut hash_count = 0; while self.ch_is('#') { self.bump(); hash_count += 1; } if self.is_eof() { let pos = self.pos; panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string")); } else if !self.ch_is('"') { let pos = self.pos; let ch = self.ch.unwrap(); panic!(self.fatal_span_char(start_bpos, pos, "found invalid character; only `#` is allowed in raw \ string delimitation", ch)); } self.bump(); let content_start_bpos = self.pos; let mut content_end_bpos; 'outer: loop { match self.ch { None => { let pos = self.pos; panic!(self.fatal_span_(start_bpos, pos, "unterminated raw string")) } Some('"') => { content_end_bpos = self.pos; for _ in 0..hash_count { self.bump(); if !self.ch_is('#') { continue 'outer; } } break; } Some(c) => { if c > '\x7F' { let pos = self.pos; self.err_span_char(pos, pos, "raw byte string must be ASCII", c); } } } self.bump(); } self.bump(); token::ByteStrRaw(self.name_from_to(content_start_bpos, content_end_bpos), hash_count) } } // This tests the character for the unicode property 'PATTERN_WHITE_SPACE' which // is guaranteed to be forward compatible. http://unicode.org/reports/tr31/#R3 pub fn is_pattern_whitespace(c: Option<char>) -> bool { c.map_or(false, Pattern_White_Space) } fn in_range(c: Option<char>, lo: char, hi: char) -> bool { match c { Some(c) => lo <= c && c <= hi, _ => false, } } fn is_dec_digit(c: Option<char>) -> bool { in_range(c, '0', '9') } pub fn is_doc_comment(s: &str) -> bool { let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || s.starts_with("//!"); debug!("is {:?} a doc comment? {}", s, res); res } pub fn is_block_doc_comment(s: &str) -> bool { // Prevent `/**/` from being parsed as a doc comment let res = ((s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || s.starts_with("/*!")) && s.len() >= 5; debug!("is {:?} a doc comment? {}", s, res); res } fn ident_start(c: Option<char>) -> bool { let c = match c { Some(c) => c, None => return false, }; (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || (c > '\x7f' && c.is_xid_start()) } fn ident_continue(c: Option<char>) -> bool { let c = match c { Some(c) => c, None => return false, }; (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || (c > '\x7f' && c.is_xid_continue()) } #[cfg(test)] mod tests { use super::*; use ast::{Ident, CrateConfig}; use symbol::Symbol; use syntax_pos::{BytePos, Span, NO_EXPANSION}; use codemap::CodeMap; use errors; use feature_gate::UnstableFeatures; use parse::token; use std::cell::RefCell; use std::collections::HashSet; use std::io; use std::rc::Rc; fn mk_sess(cm: Rc<CodeMap>) -> ParseSess { let emitter = errors::emitter::EmitterWriter::new(Box::new(io::sink()), Some(cm.clone()), false); ParseSess { span_diagnostic: errors::Handler::with_emitter(true, false, Box::new(emitter)), unstable_features: UnstableFeatures::from_environment(), config: CrateConfig::new(), included_mod_stack: RefCell::new(Vec::new()), code_map: cm, missing_fragment_specifiers: RefCell::new(HashSet::new()), } } // open a string reader for the given string fn setup<'a>(cm: &CodeMap, sess: &'a ParseSess, teststr: String) -> StringReader<'a> { let fm = cm.new_filemap("zebra.rs".to_string(), teststr); StringReader::new(sess, fm) } #[test] fn t1() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut string_reader = setup(&cm, &sh, "/* my source file */ fn main() { println!(\"zebra\"); }\n" .to_string()); let id = Ident::from_str("fn"); assert_eq!(string_reader.next_token().tok, token::Comment); assert_eq!(string_reader.next_token().tok, token::Whitespace); let tok1 = string_reader.next_token(); let tok2 = TokenAndSpan { tok: token::Ident(id), sp: Span::new(BytePos(21), BytePos(23), NO_EXPANSION), }; assert_eq!(tok1, tok2); assert_eq!(string_reader.next_token().tok, token::Whitespace); // the 'main' id is already read: assert_eq!(string_reader.pos.clone(), BytePos(28)); // read another token: let tok3 = string_reader.next_token(); let tok4 = TokenAndSpan { tok: token::Ident(Ident::from_str("main")), sp: Span::new(BytePos(24), BytePos(28), NO_EXPANSION), }; assert_eq!(tok3, tok4); // the lparen is already read: assert_eq!(string_reader.pos.clone(), BytePos(29)) } // check that the given reader produces the desired stream // of tokens (stop checking after exhausting the expected vec) fn check_tokenization(mut string_reader: StringReader, expected: Vec<token::Token>) { for expected_tok in &expected { assert_eq!(&string_reader.next_token().tok, expected_tok); } } // make the identifier by looking up the string in the interner fn mk_ident(id: &str) -> token::Token { token::Ident(Ident::from_str(id)) } #[test] fn doublecolonparsing() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a b".to_string()), vec![mk_ident("a"), token::Whitespace, mk_ident("b")]); } #[test] fn dcparsing_2() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a::b".to_string()), vec![mk_ident("a"), token::ModSep, mk_ident("b")]); } #[test] fn dcparsing_3() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a ::b".to_string()), vec![mk_ident("a"), token::Whitespace, token::ModSep, mk_ident("b")]); } #[test] fn dcparsing_4() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); check_tokenization(setup(&cm, &sh, "a:: b".to_string()), vec![mk_ident("a"), token::ModSep, token::Whitespace, mk_ident("b")]); } #[test] fn character_a() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'a'".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern("a")), None)); } #[test] fn character_space() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "' '".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern(" ")), None)); } #[test] fn character_escaped() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'\\n'".to_string()).next_token().tok, token::Literal(token::Char(Symbol::intern("\\n")), None)); } #[test] fn lifetime_name() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "'abc".to_string()).next_token().tok, token::Lifetime(Ident::from_str("'abc"))); } #[test] fn raw_string() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); assert_eq!(setup(&cm, &sh, "r###\"\"#a\\b\x00c\"\"###".to_string()) .next_token() .tok, token::Literal(token::StrRaw(Symbol::intern("\"#a\\b\x00c\""), 3), None)); } #[test] fn literal_suffixes() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); macro_rules! test { ($input: expr, $tok_type: ident, $tok_contents: expr) => {{ assert_eq!(setup(&cm, &sh, format!("{}suffix", $input)).next_token().tok, token::Literal(token::$tok_type(Symbol::intern($tok_contents)), Some(Symbol::intern("suffix")))); // with a whitespace separator: assert_eq!(setup(&cm, &sh, format!("{} suffix", $input)).next_token().tok, token::Literal(token::$tok_type(Symbol::intern($tok_contents)), None)); }} } test!("'a'", Char, "a"); test!("b'a'", Byte, "a"); test!("\"a\"", Str_, "a"); test!("b\"a\"", ByteStr, "a"); test!("1234", Integer, "1234"); test!("0b101", Integer, "0b101"); test!("0xABC", Integer, "0xABC"); test!("1.0", Float, "1.0"); test!("1.0e10", Float, "1.0e10"); assert_eq!(setup(&cm, &sh, "2us".to_string()).next_token().tok, token::Literal(token::Integer(Symbol::intern("2")), Some(Symbol::intern("us")))); assert_eq!(setup(&cm, &sh, "r###\"raw\"###suffix".to_string()).next_token().tok, token::Literal(token::StrRaw(Symbol::intern("raw"), 3), Some(Symbol::intern("suffix")))); assert_eq!(setup(&cm, &sh, "br###\"raw\"###suffix".to_string()).next_token().tok, token::Literal(token::ByteStrRaw(Symbol::intern("raw"), 3), Some(Symbol::intern("suffix")))); } #[test] fn line_doc_comments() { assert!(is_doc_comment("///")); assert!(is_doc_comment("/// blah")); assert!(!is_doc_comment("////")); } #[test] fn nested_block_comments() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut lexer = setup(&cm, &sh, "/* /* */ */'a'".to_string()); match lexer.next_token().tok { token::Comment => {} _ => panic!("expected a comment!"), } assert_eq!(lexer.next_token().tok, token::Literal(token::Char(Symbol::intern("a")), None)); } #[test] fn crlf_comments() { let cm = Rc::new(CodeMap::new(FilePathMapping::empty())); let sh = mk_sess(cm.clone()); let mut lexer = setup(&cm, &sh, "// test\r\n/// test\r\n".to_string()); let comment = lexer.next_token(); assert_eq!(comment.tok, token::Comment); assert_eq!((comment.sp.lo(), comment.sp.hi()), (BytePos(0), BytePos(7))); assert_eq!(lexer.next_token().tok, token::Whitespace); assert_eq!(lexer.next_token().tok, token::DocComment(Symbol::intern("/// test"))); } }
36.734715
100
0.422029
8975474a5b7bb5a955b6bf387f7bdf353b107c3d
871
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. // // @generated SignedSource<<aef10f6b05c49cc5d35ba4fd1411373f>> // // To regenerate this file, run: // hphp/hack/src/oxidized/regen.sh use ocamlrep_derive::FromOcamlRep; use ocamlrep_derive::ToOcamlRep; use serde::Deserialize; use serde::Serialize; #[allow(unused_imports)] use crate::*; #[derive( Clone, Debug, Deserialize, Eq, FromOcamlRep, Hash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Decls { pub classes: s_map::SMap<shallow_decl_defs::ShallowClass>, pub funs: s_map::SMap<typing_defs::FunElt>, pub typedefs: s_map::SMap<typing_defs::TypedefType>, pub consts: s_map::SMap<typing_defs::Ty>, }
22.921053
66
0.701493
ebed1f757e3ccc0715107c91e7c990ef4c830201
1,410
//! Run-time feature detection on ARM Aarch32. /// Checks if `arm` feature is enabled. #[macro_export] #[unstable(feature = "stdsimd", issue = "27731")] #[allow_internal_unstable(stdsimd_internal)] macro_rules! is_arm_feature_detected { ("neon") => { cfg!(target_feature = "neon") || $crate::detect::check_for($crate::detect::Feature::neon) }; ("pmull") => { cfg!(target_feature = "pmull") || $crate::detect::check_for($crate::detect::Feature::pmull) }; ("v7") => { compile_error!("\"v7\" feature cannot be detected at run-time") }; ("vfp2") => { compile_error!("\"vfp2\" feature cannot be detected at run-time") }; ("vfp3") => { compile_error!("\"vfp3\" feature cannot be detected at run-time") }; ("vfp4") => { compile_error!("\"vfp4\" feature cannot be detected at run-time") }; ($t:tt,) => { is_arm_feature_detected!($t); }; ($t:tt) => { compile_error!(concat!("unknown arm target feature: ", $t)) }; } /// ARM CPU Feature enum. Each variant denotes a position in a bitset for a /// particular feature. /// /// PLEASE: do not use this, it is an implementation detail subject to change. #[doc(hidden)] #[allow(non_camel_case_types)] #[repr(u8)] #[unstable(feature = "stdsimd_internal", issue = "0")] pub enum Feature { /// ARM Advanced SIMD (NEON) - Aarch32 neon, /// Polynomial Multiply pmull, }
35.25
86
0.619858
0800f5fd941538966ed5fc69e83d311573972584
53,320
use std::cell::RefCell; use std::collections::HashMap; use std::path::PathBuf; use std::rc::Rc; use chrono::NaiveDateTime; use glib::Receiver; use gtk::prelude::*; use humansize::{file_size_opts as options, FileSize}; use crate::fl; use czkawka_core::duplicate::CheckingMethod; use czkawka_core::same_music::MusicSimilarity; use czkawka_core::similar_images; use crate::gui_data::GuiData; use crate::help_combo_box::IMAGES_HASH_SIZE_COMBO_BOX; use crate::help_functions::*; use crate::notebook_enums::*; pub fn connect_compute_results(gui_data: &GuiData, glib_stop_receiver: Receiver<Message>) { let combo_box_image_hash_size = gui_data.main_notebook.combo_box_image_hash_size.clone(); let buttons_search = gui_data.bottom_buttons.buttons_search.clone(); let notebook_main = gui_data.main_notebook.notebook_main.clone(); let entry_info = gui_data.entry_info.clone(); let tree_view_empty_folder_finder = gui_data.main_notebook.tree_view_empty_folder_finder.clone(); let tree_view_empty_files_finder = gui_data.main_notebook.tree_view_empty_files_finder.clone(); let tree_view_duplicate_finder = gui_data.main_notebook.tree_view_duplicate_finder.clone(); let tree_view_similar_images_finder = gui_data.main_notebook.tree_view_similar_images_finder.clone(); let tree_view_similar_videos_finder = gui_data.main_notebook.tree_view_similar_videos_finder.clone(); let buttons_array = gui_data.bottom_buttons.buttons_array.clone(); let text_view_errors = gui_data.text_view_errors.clone(); let shared_duplication_state = gui_data.shared_duplication_state.clone(); let shared_buttons = gui_data.shared_buttons.clone(); let shared_empty_folders_state = gui_data.shared_empty_folders_state.clone(); let shared_empty_files_state = gui_data.shared_empty_files_state.clone(); let shared_broken_files_state = gui_data.shared_broken_files_state.clone(); let tree_view_big_files_finder = gui_data.main_notebook.tree_view_big_files_finder.clone(); let tree_view_broken_files = gui_data.main_notebook.tree_view_broken_files.clone(); let tree_view_invalid_symlinks = gui_data.main_notebook.tree_view_invalid_symlinks.clone(); let shared_big_files_state = gui_data.shared_big_files_state.clone(); let shared_same_invalid_symlinks = gui_data.shared_same_invalid_symlinks.clone(); let tree_view_temporary_files_finder = gui_data.main_notebook.tree_view_temporary_files_finder.clone(); let shared_temporary_files_state = gui_data.shared_temporary_files_state.clone(); let shared_similar_images_state = gui_data.shared_similar_images_state.clone(); let shared_similar_videos_state = gui_data.shared_similar_videos_state.clone(); let tree_view_same_music_finder = gui_data.main_notebook.tree_view_same_music_finder.clone(); let shared_same_music_state = gui_data.shared_same_music_state.clone(); let buttons_names = gui_data.bottom_buttons.buttons_names.clone(); let window_progress = gui_data.progress_window.window_progress.clone(); let taskbar_state = gui_data.taskbar_state.clone(); let notebook_upper = gui_data.upper_notebook.notebook_upper.clone(); let button_settings = gui_data.header.button_settings.clone(); let button_app_info = gui_data.header.button_app_info.clone(); let main_context = glib::MainContext::default(); let _guard = main_context.acquire().unwrap(); glib_stop_receiver.attach(None, move |msg| { buttons_search.show(); notebook_main.set_sensitive(true); notebook_upper.set_sensitive(true); button_settings.set_sensitive(true); button_app_info.set_sensitive(true); window_progress.hide(); taskbar_state.borrow().hide(); let hash_size_index = combo_box_image_hash_size.active().unwrap() as usize; let hash_size = IMAGES_HASH_SIZE_COMBO_BOX[hash_size_index] as u8; match msg { Message::Duplicates(df) => { if df.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = df.get_information(); let text_messages = df.get_text_messages(); let duplicates_number: usize; let duplicates_size: u64; let duplicates_group: usize; let fl_found = fl!("compute_found"); let fl_groups = fl!("compute_groups"); let fl_groups_which_took = fl!("compute_groups_which_took"); let fl_duplicated_files_in = fl!("compute_duplicated_files_in"); match df.get_check_method() { CheckingMethod::Name => { duplicates_number = information.number_of_duplicated_files_by_name; // duplicates_size = 0; duplicates_group = information.number_of_groups_by_name; entry_info.set_text(format!("{} {} {} {} {}", fl_found, duplicates_number, fl_duplicated_files_in, duplicates_group, fl_groups).as_str()); } CheckingMethod::Hash => { duplicates_number = information.number_of_duplicated_files_by_hash; duplicates_size = information.lost_space_by_hash; duplicates_group = information.number_of_groups_by_hash; entry_info.set_text( format!( "{} {} {} {} {} {}.", fl_found, duplicates_number, fl_duplicated_files_in, duplicates_group, fl_groups_which_took, duplicates_size.file_size(options::BINARY).unwrap() ) .as_str(), ); } CheckingMethod::Size => { duplicates_number = information.number_of_duplicated_files_by_size; duplicates_size = information.lost_space_by_size; duplicates_group = information.number_of_groups_by_size; entry_info.set_text( format!( "{} {} {} {} {} {}.", fl_found, duplicates_number, fl_duplicated_files_in, duplicates_group, fl_groups_which_took, duplicates_size.file_size(options::BINARY).unwrap() ) .as_str(), ); } CheckingMethod::None => { panic!(); } } // Create GUI { let list_store = get_list_store(&tree_view_duplicate_finder); match df.get_check_method() { CheckingMethod::Name => { let btreemap = df.get_files_sorted_by_names(); for (name, vector) in btreemap.iter().rev() { // Sort let vector = if vector.len() >= 2 { let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vector } else { vector.clone() }; let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &false), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &name), (ColumnsDuplicates::Path as u32, (&(format!("{} results", vector.len())))), (ColumnsDuplicates::Modification as u32, (&"".to_string())), // No text in 3 column (ColumnsDuplicates::ModificationAsSecs as u32, (&(0))), // Not used here (ColumnsDuplicates::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); for entry in vector { let (directory, file) = split_path(&entry.path); let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &true), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &file), (ColumnsDuplicates::Path as u32, &directory), ( ColumnsDuplicates::Modification as u32, &(format!("{} - ({})", NaiveDateTime::from_timestamp(entry.modified_date as i64, 0), entry.size.file_size(options::BINARY).unwrap())), ), (ColumnsDuplicates::ModificationAsSecs as u32, &(entry.modified_date)), (ColumnsDuplicates::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } } CheckingMethod::Hash => { let btreemap = df.get_files_sorted_by_hash(); for (size, vectors_vector) in btreemap.iter().rev() { for vector in vectors_vector { // Sort let vector = if vector.len() >= 2 { let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vector } else { vector.clone() }; let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &false), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &(format!("{} x {} ({} {})", vector.len(), size.file_size(options::BINARY).unwrap(), size, fl!("general_bytes")))), ( ColumnsDuplicates::Path as u32, &(format!( "{} ({} {}) {}", ((vector.len() - 1) as u64 * *size as u64).file_size(options::BINARY).unwrap(), (vector.len() - 1) as u64 * *size as u64, fl!("general_bytes"), fl!("general_lost") )), ), (ColumnsDuplicates::Modification as u32, &"".to_string()), // No text in 3 column (ColumnsDuplicates::ModificationAsSecs as u32, &(0)), (ColumnsDuplicates::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); for entry in vector { let (directory, file) = split_path(&entry.path); let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &true), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &file), (ColumnsDuplicates::Path as u32, &directory), (ColumnsDuplicates::Modification as u32, &(NaiveDateTime::from_timestamp(entry.modified_date as i64, 0).to_string())), (ColumnsDuplicates::ModificationAsSecs as u32, &(entry.modified_date)), (ColumnsDuplicates::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } } } CheckingMethod::Size => { let btreemap = df.get_files_sorted_by_size(); for (size, vector) in btreemap.iter().rev() { // Sort let vector = if vector.len() >= 2 { let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vector } else { vector.clone() }; let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &false), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &(format!("{} x {} ({} {})", vector.len(), size.file_size(options::BINARY).unwrap(), size, fl!("general_bytes")))), ( ColumnsDuplicates::Path as u32, &(format!( "{} ({} {}) {}", ((vector.len() - 1) as u64 * *size as u64).file_size(options::BINARY).unwrap(), (vector.len() - 1) as u64 * *size as u64, fl!("general_bytes"), fl!("general_lost") )), ), (ColumnsDuplicates::Modification as u32, &"".to_string()), // No text in 3 column (ColumnsDuplicates::ModificationAsSecs as u32, &(0)), // Not used here (ColumnsDuplicates::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); for entry in vector { let (directory, file) = split_path(&entry.path); let values: [(u32, &dyn ToValue); 8] = [ (ColumnsDuplicates::ActivatableSelectButton as u32, &true), (ColumnsDuplicates::SelectionButton as u32, &false), (ColumnsDuplicates::Name as u32, &file), (ColumnsDuplicates::Path as u32, &directory), (ColumnsDuplicates::Modification as u32, &(NaiveDateTime::from_timestamp(entry.modified_date as i64, 0).to_string())), (ColumnsDuplicates::ModificationAsSecs as u32, &(entry.modified_date)), (ColumnsDuplicates::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsDuplicates::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } } CheckingMethod::None => { panic!(); } } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_duplication_state.borrow_mut() = df; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::Duplicate, &["save", "delete", "select", "symlink", "hardlink", "move"], duplicates_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::Duplicate).unwrap(), &buttons_array, &buttons_names); } } } Message::EmptyFolders(ef) => { if ef.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = ef.get_information(); let text_messages = ef.get_text_messages(); let empty_folder_number: usize = information.number_of_empty_folders; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), empty_folder_number, fl!("compute_empty_folders")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_empty_folder_finder); let hashmap = ef.get_empty_folder_list(); let mut vector = hashmap.keys().cloned().collect::<Vec<PathBuf>>(); vector.sort_by_key(|e| { let t = split_path(e.as_path()); (t.0, t.1) }); for path in vector { let (directory, file) = split_path(&path); let values: [(u32, &dyn ToValue); 5] = [ (ColumnsEmptyFolders::SelectionButton as u32, &false), (ColumnsEmptyFolders::Name as u32, &file), (ColumnsEmptyFolders::Path as u32, &directory), (ColumnsEmptyFolders::Modification as u32, &(NaiveDateTime::from_timestamp(hashmap.get(&path).unwrap().modified_date as i64, 0).to_string())), (ColumnsEmptyFolders::ModificationAsSecs as u32, &(hashmap.get(&path).unwrap().modified_date as u64)), ]; list_store.set(&list_store.append(), &values); } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_empty_folders_state.borrow_mut() = ef; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::EmptyDirectories, &["save", "delete", "select", "move"], empty_folder_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::EmptyDirectories).unwrap(), &buttons_array, &buttons_names); } } } Message::EmptyFiles(vf) => { if vf.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = vf.get_information(); let text_messages = vf.get_text_messages(); let empty_files_number: usize = information.number_of_empty_files; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), empty_files_number, fl!("compute_empty_files")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_empty_files_finder); let vector = vf.get_empty_files(); // Sort let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); for file_entry in vector { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 5] = [ (ColumnsEmptyFiles::SelectionButton as u32, &false), (ColumnsEmptyFiles::Name as u32, &file), (ColumnsEmptyFiles::Path as u32, &directory), (ColumnsEmptyFiles::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsEmptyFiles::ModificationAsSecs as u32, &(file_entry.modified_date as i64)), ]; list_store.set(&list_store.append(), &values); } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_empty_files_state.borrow_mut() = vf; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::EmptyFiles, &["save", "delete", "select", "move"], empty_files_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::EmptyFiles).unwrap(), &buttons_array, &buttons_names); } } } Message::BigFiles(bf) => { if bf.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = bf.get_information(); let text_messages = bf.get_text_messages(); let biggest_files_number: usize = information.number_of_real_files; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), biggest_files_number, fl!("compute_biggest_files")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_big_files_finder); let btreemap = bf.get_big_files(); for (size, vector) in btreemap.iter().rev() { let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); for file_entry in vector { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 7] = [ (ColumnsBigFiles::SelectionButton as u32, &false), (ColumnsBigFiles::Size as u32, &(format!("{} ({} {})", size.file_size(options::BINARY).unwrap(), size, fl!("general_bytes")))), (ColumnsBigFiles::Name as u32, &file), (ColumnsBigFiles::Path as u32, &directory), (ColumnsBigFiles::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsBigFiles::ModificationAsSecs as u32, &(file_entry.modified_date as i64)), (ColumnsBigFiles::SizeAsBytes as u32, &(size)), ]; list_store.set(&list_store.append(), &values); } } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_big_files_state.borrow_mut() = bf; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::BigFiles, &["save", "delete", "select", "move"], biggest_files_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::BigFiles).unwrap(), &buttons_array, &buttons_names); } } } Message::Temporary(tf) => { if tf.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = tf.get_information(); let text_messages = tf.get_text_messages(); let temporary_files_number: usize = information.number_of_temporary_files; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), temporary_files_number, fl!("compute_temporary_files")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_temporary_files_finder); let vector = tf.get_temporary_files(); // Sort let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); for file_entry in vector { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 5] = [ (ColumnsTemporaryFiles::SelectionButton as u32, &false), (ColumnsTemporaryFiles::Name as u32, &file), (ColumnsTemporaryFiles::Path as u32, &directory), (ColumnsTemporaryFiles::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsTemporaryFiles::ModificationAsSecs as u32, &(file_entry.modified_date as i64)), ]; list_store.set(&list_store.append(), &values); } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_temporary_files_state.borrow_mut() = tf; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::Temporary, &["save", "delete", "select", "move"], temporary_files_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::Temporary).unwrap(), &buttons_array, &buttons_names); } } } Message::SimilarImages(sf) => { if sf.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { //let information = sf.get_information(); let text_messages = sf.get_text_messages(); let base_images_size = sf.get_similar_images().len(); entry_info.set_text(format!("{} {} {} {}.", fl!("compute_found"), fl!("compute_duplicates_for"), base_images_size, fl!("compute_similar_image")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_similar_images_finder); let vec_struct_similar = sf.get_similar_images(); for vec_file_entry in vec_struct_similar.iter() { // Sort let vec_file_entry = if vec_file_entry.len() >= 2 { let mut vec_file_entry = vec_file_entry.clone(); vec_file_entry.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vec_file_entry } else { vec_file_entry.clone() }; // Header let values: [(u32, &dyn ToValue); 12] = [ (ColumnsSimilarImages::ActivatableSelectButton as u32, &false), (ColumnsSimilarImages::SelectionButton as u32, &false), (ColumnsSimilarImages::Similarity as u32, &"".to_string()), (ColumnsSimilarImages::Size as u32, &"".to_string()), (ColumnsSimilarImages::SizeAsBytes as u32, &(0)), (ColumnsSimilarImages::Dimensions as u32, &"".to_string()), (ColumnsSimilarImages::Name as u32, &"".to_string()), (ColumnsSimilarImages::Path as u32, &"".to_string()), (ColumnsSimilarImages::Modification as u32, &"".to_string()), (ColumnsSimilarImages::ModificationAsSecs as u32, &(0)), (ColumnsSimilarImages::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsSimilarImages::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); // Meat for file_entry in vec_file_entry.iter() { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 12] = [ (ColumnsSimilarImages::ActivatableSelectButton as u32, &true), (ColumnsSimilarImages::SelectionButton as u32, &false), (ColumnsSimilarImages::Similarity as u32, &(similar_images::get_string_from_similarity(&file_entry.similarity, hash_size).to_string())), (ColumnsSimilarImages::Size as u32, &file_entry.size.file_size(options::BINARY).unwrap()), (ColumnsSimilarImages::SizeAsBytes as u32, &file_entry.size), (ColumnsSimilarImages::Dimensions as u32, &file_entry.dimensions), (ColumnsSimilarImages::Name as u32, &file), (ColumnsSimilarImages::Path as u32, &directory), (ColumnsSimilarImages::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsSimilarImages::ModificationAsSecs as u32, &(file_entry.modified_date)), (ColumnsSimilarImages::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsSimilarImages::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_similar_images_state.borrow_mut() = sf; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::SimilarImages, &["save", "delete", "select", "symlink", "hardlink", "move"], base_images_size > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::SimilarImages).unwrap(), &buttons_array, &buttons_names); } } } Message::SimilarVideos(ff) => { if ff.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { //let information = ff.get_information(); let text_messages = ff.get_text_messages(); let base_videos_size = ff.get_similar_videos().len(); entry_info.set_text(format!("{} {} {} {}.", fl!("compute_found"), fl!("compute_duplicates_for"), base_videos_size, fl!("compute_similar_videos")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_similar_videos_finder); let vec_struct_similar = ff.get_similar_videos(); for vec_file_entry in vec_struct_similar.iter() { // Sort let vec_file_entry = if vec_file_entry.len() >= 2 { let mut vec_file_entry = vec_file_entry.clone(); vec_file_entry.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vec_file_entry } else { vec_file_entry.clone() }; // Header let values: [(u32, &dyn ToValue); 10] = [ (ColumnsSimilarVideos::ActivatableSelectButton as u32, &false), (ColumnsSimilarVideos::SelectionButton as u32, &false), (ColumnsSimilarVideos::Size as u32, &"".to_string()), (ColumnsSimilarVideos::SizeAsBytes as u32, &(0)), (ColumnsSimilarVideos::Name as u32, &"".to_string()), (ColumnsSimilarVideos::Path as u32, &"".to_string()), (ColumnsSimilarVideos::Modification as u32, &"".to_string()), (ColumnsSimilarVideos::ModificationAsSecs as u32, &(0)), (ColumnsSimilarVideos::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsSimilarVideos::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); // Meat for file_entry in vec_file_entry.iter() { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 10] = [ (ColumnsSimilarVideos::ActivatableSelectButton as u32, &true), (ColumnsSimilarVideos::SelectionButton as u32, &false), (ColumnsSimilarVideos::Size as u32, &file_entry.size.file_size(options::BINARY).unwrap()), (ColumnsSimilarVideos::SizeAsBytes as u32, &file_entry.size), (ColumnsSimilarVideos::Name as u32, &file), (ColumnsSimilarVideos::Path as u32, &directory), (ColumnsSimilarVideos::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsSimilarVideos::ModificationAsSecs as u32, &(file_entry.modified_date)), (ColumnsSimilarVideos::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsSimilarVideos::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_similar_videos_state.borrow_mut() = ff; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::SimilarVideos, &["save", "delete", "select", "symlink", "hardlink", "move"], base_videos_size > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::SimilarVideos).unwrap(), &buttons_array, &buttons_names); } } } Message::SameMusic(mf) => { if mf.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = mf.get_information(); let text_messages = mf.get_text_messages(); let same_music_number: usize = information.number_of_duplicates_music_files; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), same_music_number, fl!("compute_music_files")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_same_music_finder); let vector = mf.get_duplicated_music_entries(); let music_similarity = *mf.get_music_similarity(); let is_title = (MusicSimilarity::TITLE & music_similarity) != MusicSimilarity::NONE; let is_artist = (MusicSimilarity::ARTIST & music_similarity) != MusicSimilarity::NONE; let is_album_title = (MusicSimilarity::ALBUM_TITLE & music_similarity) != MusicSimilarity::NONE; let is_album_artist = (MusicSimilarity::ALBUM_ARTIST & music_similarity) != MusicSimilarity::NONE; let is_year = (MusicSimilarity::YEAR & music_similarity) != MusicSimilarity::NONE; let text: String = "-----".to_string(); for vec_file_entry in vector { // Sort let vec_file_entry = if vec_file_entry.len() >= 2 { let mut vec_file_entry = vec_file_entry.clone(); vec_file_entry.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); vec_file_entry } else { vec_file_entry.clone() }; let values: [(u32, &dyn ToValue); 15] = [ (ColumnsSameMusic::ActivatableSelectButton as u32, &false), (ColumnsSameMusic::SelectionButton as u32, &false), (ColumnsSameMusic::Size as u32, &"".to_string()), (ColumnsSameMusic::SizeAsBytes as u32, &(0)), (ColumnsSameMusic::Name as u32, &"".to_string()), (ColumnsSameMusic::Path as u32, &"".to_string()), ( ColumnsSameMusic::Title as u32, &(match is_title { true => text.clone(), false => "".to_string(), }), ), ( ColumnsSameMusic::Artist as u32, &(match is_artist { true => text.clone(), false => "".to_string(), }), ), ( ColumnsSameMusic::AlbumTitle as u32, &(match is_album_title { true => text.clone(), false => "".to_string(), }), ), ( ColumnsSameMusic::AlbumArtist as u32, &(match is_album_artist { true => text.clone(), false => "".to_string(), }), ), ( ColumnsSameMusic::Year as u32, &(match is_year { true => text.clone(), false => "".to_string(), }), ), (ColumnsSameMusic::Modification as u32, &"".to_string()), (ColumnsSameMusic::ModificationAsSecs as u32, &(0)), (ColumnsSameMusic::Color as u32, &(HEADER_ROW_COLOR.to_string())), (ColumnsSameMusic::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); for file_entry in vec_file_entry { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 15] = [ (ColumnsSameMusic::ActivatableSelectButton as u32, &true), (ColumnsSameMusic::SelectionButton as u32, &false), (ColumnsSameMusic::Size as u32, &file_entry.size.file_size(options::BINARY).unwrap()), (ColumnsSameMusic::SizeAsBytes as u32, &file_entry.size), (ColumnsSameMusic::Name as u32, &file), (ColumnsSameMusic::Path as u32, &directory), (ColumnsSameMusic::Title as u32, &file_entry.title), (ColumnsSameMusic::Artist as u32, &file_entry.artist), (ColumnsSameMusic::AlbumTitle as u32, &file_entry.album_title), (ColumnsSameMusic::AlbumArtist as u32, &file_entry.album_artist), (ColumnsSameMusic::Year as u32, &file_entry.year.to_string()), (ColumnsSameMusic::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsSameMusic::ModificationAsSecs as u32, &(file_entry.modified_date)), (ColumnsSameMusic::Color as u32, &(MAIN_ROW_COLOR.to_string())), (ColumnsSameMusic::TextColor as u32, &(TEXT_COLOR.to_string())), ]; list_store.set(&list_store.append(), &values); } } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_same_music_state.borrow_mut() = mf; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::SameMusic, &["save", "delete", "select", "symlink", "hardlink", "move"], same_music_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::SameMusic).unwrap(), &buttons_array, &buttons_names); } } } Message::InvalidSymlinks(ifs) => { if ifs.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = ifs.get_information(); let text_messages = ifs.get_text_messages(); let invalid_symlinks: usize = information.number_of_invalid_symlinks; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), invalid_symlinks, fl!("compute_symlinks")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_invalid_symlinks); let vector = ifs.get_invalid_symlinks(); // Sort let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.symlink_path.as_path()); (t.0, t.1) }); for file_entry in vector { let (directory, file) = split_path(&file_entry.symlink_path); let values: [(u32, &dyn ToValue); 7] = [ (ColumnsInvalidSymlinks::SelectionButton as u32, &false), (ColumnsInvalidSymlinks::Name as u32, &file), (ColumnsInvalidSymlinks::Path as u32, &directory), (ColumnsInvalidSymlinks::DestinationPath as u32, &file_entry.destination_path.to_string_lossy().to_string()), (ColumnsInvalidSymlinks::TypeOfError as u32, &get_text_from_invalid_symlink_cause(&file_entry.type_of_error)), (ColumnsInvalidSymlinks::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsInvalidSymlinks::ModificationAsSecs as u32, &(file_entry.modified_date as i64)), ]; list_store.set(&list_store.append(), &values); } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_same_invalid_symlinks.borrow_mut() = ifs; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::Symlinks, &["save", "delete", "select", "move"], invalid_symlinks > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::Symlinks).unwrap(), &buttons_array, &buttons_names); } } } Message::BrokenFiles(br) => { if br.get_stopped_search() { entry_info.set_text(&fl!("compute_stopped_by_user")); } else { let information = br.get_information(); let text_messages = br.get_text_messages(); let broken_files_number: usize = information.number_of_broken_files; entry_info.set_text(format!("{} {} {}.", fl!("compute_found"), broken_files_number, fl!("compute_broken_files")).as_str()); // Create GUI { let list_store = get_list_store(&tree_view_broken_files); let vector = br.get_broken_files(); // Sort let mut vector = vector.clone(); vector.sort_by_key(|e| { let t = split_path(e.path.as_path()); (t.0, t.1) }); for file_entry in vector { let (directory, file) = split_path(&file_entry.path); let values: [(u32, &dyn ToValue); 6] = [ (ColumnsBrokenFiles::SelectionButton as u32, &false), (ColumnsBrokenFiles::Name as u32, &file), (ColumnsBrokenFiles::Path as u32, &directory), (ColumnsBrokenFiles::ErrorType as u32, &file_entry.error_string), (ColumnsBrokenFiles::Modification as u32, &(NaiveDateTime::from_timestamp(file_entry.modified_date as i64, 0).to_string())), (ColumnsBrokenFiles::ModificationAsSecs as u32, &(file_entry.modified_date as i64)), ]; list_store.set(&list_store.append(), &values); } print_text_messages_to_text_view(text_messages, &text_view_errors); } // Set state { *shared_broken_files_state.borrow_mut() = br; set_specific_buttons_as_active(&shared_buttons, &NotebookMainEnum::BrokenFiles, &["save", "delete", "select", "move"], broken_files_number > 0); set_buttons(&mut *shared_buttons.borrow_mut().get_mut(&NotebookMainEnum::BrokenFiles).unwrap(), &buttons_array, &buttons_names); } } } } // Returning false here would close the receiver and have senders fail glib::Continue(true) }); } fn set_specific_buttons_as_active(buttons_array: &Rc<RefCell<HashMap<NotebookMainEnum, HashMap<String, bool>>>>, notebook_enum: &NotebookMainEnum, buttons: &[&str], value_to_set: bool) { for i in buttons { *buttons_array.borrow_mut().get_mut(notebook_enum).unwrap().get_mut(*i).unwrap() = value_to_set; } }
59.244444
192
0.455045
d7c2b6f4d6899f62bb135ccc5b35f01885b8cfce
275
use std::{thread, time::Duration}; use terminal_spinners::{SpinnerBuilder, BALLOON2}; fn main() { let text = "Loading unicorns"; let handle = SpinnerBuilder::new().spinner(&BALLOON2).text(text).start(); thread::sleep(Duration::from_secs(3)); handle.done(); }
30.555556
77
0.68
fff4ae36180060309c3aa2af2d49945c156dc0b5
15,456
// Copyright 2018 The Frown Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! Aggregated Signature functions used in the creation of Frown transactions. //! This module interfaces into the underlying //! [Rust Aggsig library](https://github.com/mimblewimble/rust-secp256k1-zkp/blob/master/src/aggsig.rs) use crate::keychain::{BlindingFactor, Identifier, Keychain}; use crate::libtx::error::{Error, ErrorKind}; use crate::util::secp::key::{PublicKey, SecretKey}; use crate::util::secp::pedersen::Commitment; use crate::util::secp::{self, aggsig, Message, Secp256k1, Signature}; /// Creates a new secure nonce (as a SecretKey), guaranteed to be usable during /// aggsig creation. /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Signing /// /// # Example /// /// ``` /// # extern crate frown_core as core; /// # extern crate frown_util as util; /// use core::libtx::aggsig; /// use util::secp::{ContextFlag, Secp256k1}; /// let secp = Secp256k1::with_caps(ContextFlag::SignOnly); /// let secret_nonce = aggsig::create_secnonce(&secp).unwrap(); /// ``` /// # Remarks /// /// The resulting SecretKey is guaranteed to have Jacobi symbol 1. pub fn create_secnonce(secp: &Secp256k1) -> Result<SecretKey, Error> { let nonce = aggsig::export_secnonce_single(secp)?; Ok(nonce) } /// Calculates a partial signature given the signer's secure key, /// the sum of all public nonces and (optionally) the sum of all public keys. /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Signing /// * `sec_key` - The signer's secret key /// * `sec_nonce` - The signer's secret nonce (the public version of which /// was added to the `nonce_sum` total) /// * `nonce_sum` - The sum of the public nonces of all signers participating /// in the full signature. This value is encoded in e. /// * `pubkey_sum` - (Optional) The sum of the public keys of all signers participating /// in the full signature. If included, this value is encoded in e. /// * `msg` - The message to sign. /// /// # Example /// /// ``` /// # extern crate frown_core as core; /// # extern crate frown_util as util; /// # extern crate rand; /// use rand::thread_rng; /// use core::libtx::aggsig; /// use util::secp::key::{PublicKey, SecretKey}; /// use util::secp::{ContextFlag, Secp256k1, Message}; /// /// let secp = Secp256k1::with_caps(ContextFlag::SignOnly); /// let secret_nonce = aggsig::create_secnonce(&secp).unwrap(); /// let secret_key = SecretKey::new(&secp, &mut thread_rng()); /// let pub_nonce_sum = PublicKey::from_secret_key(&secp, &secret_nonce).unwrap(); /// // ... Add all other participating nonces /// let pub_key_sum = PublicKey::from_secret_key(&secp, &secret_key).unwrap(); /// // ... Add all other participating keys /// let mut msg_bytes = [0; 32]; /// // ... Encode message /// let message = Message::from_slice(&msg_bytes).unwrap(); /// let sig_part = aggsig::calculate_partial_sig( /// &secp, /// &secret_key, /// &secret_nonce, /// &pub_nonce_sum, /// Some(&pub_key_sum), /// &message, ///).unwrap(); /// ``` pub fn calculate_partial_sig( secp: &Secp256k1, sec_key: &SecretKey, sec_nonce: &SecretKey, nonce_sum: &PublicKey, pubkey_sum: Option<&PublicKey>, msg: &secp::Message, ) -> Result<Signature, Error> { //Now calculate signature using message M=fee, nonce in e=nonce_sum let sig = aggsig::sign_single( secp, &msg, sec_key, Some(sec_nonce), None, Some(nonce_sum), pubkey_sum, Some(nonce_sum), )?; Ok(sig) } /// Verifies a partial signature from a public key. All nonce and public /// key sum values must be identical to those provided in the call to /// [`calculate_partial_sig`](fn.calculate_partial_sig.html). Returns /// `Result::Ok` if the signature is valid, or a Signature /// [ErrorKind](../enum.ErrorKind.html) otherwise /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Validation /// * `sig` - The signature to validate, created via a call to /// [`calculate_partial_sig`](fn.calculate_partial_sig.html) /// * `pub_nonce_sum` - The sum of the public nonces of all signers participating /// in the full signature. This value is encoded in e. /// * `pubkey` - Corresponding Public Key of the private key used to sign the message. /// * `pubkey_sum` - (Optional) The sum of the public keys of all signers participating /// in the full signature. If included, this value is encoded in e. /// * `msg` - The message to verify. /// /// # Example /// /// ``` /// # extern crate frown_core as core; /// # extern crate frown_util as util; /// # extern crate rand; /// use rand::thread_rng; /// use core::libtx::aggsig; /// use util::secp::key::{PublicKey, SecretKey}; /// use util::secp::{ContextFlag, Secp256k1, Message}; /// /// let secp = Secp256k1::with_caps(ContextFlag::Full); /// let secret_nonce = aggsig::create_secnonce(&secp).unwrap(); /// let secret_key = SecretKey::new(&secp, &mut thread_rng()); /// let pub_nonce_sum = PublicKey::from_secret_key(&secp, &secret_nonce).unwrap(); /// // ... Add all other participating nonces /// let pub_key_sum = PublicKey::from_secret_key(&secp, &secret_key).unwrap(); /// // ... Add all other participating keys /// let mut msg_bytes = [0; 32]; /// // ... Encode message /// let message = Message::from_slice(&msg_bytes).unwrap(); /// let sig_part = aggsig::calculate_partial_sig( /// &secp, /// &secret_key, /// &secret_nonce, /// &pub_nonce_sum, /// Some(&pub_key_sum), /// &message, ///).unwrap(); /// /// // Now verify the signature, ensuring the same values used to create /// // the signature are provided: /// let public_key = PublicKey::from_secret_key(&secp, &secret_key).unwrap(); /// /// let result = aggsig::verify_partial_sig( /// &secp, /// &sig_part, /// &pub_nonce_sum, /// &public_key, /// Some(&pub_key_sum), /// &message, ///); /// ``` pub fn verify_partial_sig( secp: &Secp256k1, sig: &Signature, pub_nonce_sum: &PublicKey, pubkey: &PublicKey, pubkey_sum: Option<&PublicKey>, msg: &secp::Message, ) -> Result<(), Error> { if !verify_single( secp, sig, &msg, Some(&pub_nonce_sum), pubkey, pubkey_sum, true, ) { Err(ErrorKind::Signature( "Signature validation error".to_string(), ))? } Ok(()) } /// Creates a single-signer aggsig signature from a key id. Generally, /// this function is used to create transaction kernel signatures for /// coinbase outputs. /// Returns `Ok(Signature)` if the signature is valid, or a Signature /// [ErrorKind](../enum.ErrorKind.html) otherwise /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Signing /// * `k` - The Keychain implementation being used /// * `msg` - The message to sign (fee|lockheight). /// * `key_id` - The keychain key id corresponding to the private key /// with which to sign the message /// * `blind_sum` - (Optional) The sum of all blinding factors in the transaction /// in the case of a coinbase transaction this will simply be the corresponding /// public key. /// /// # Example /// /// ``` /// # extern crate frown_util as util; /// # extern crate frown_core as core; /// # extern crate frown_keychain as keychain; /// use core::consensus::reward; /// use util::secp::key::{PublicKey, SecretKey}; /// use util::secp::{ContextFlag, Secp256k1}; /// use core::libtx::{aggsig, proof}; /// use core::core::transaction::{kernel_sig_msg, KernelFeatures}; /// use core::core::{Output, OutputFeatures}; /// use keychain::{Keychain, ExtKeychain}; /// /// let secp = Secp256k1::with_caps(ContextFlag::Commit); /// let keychain = ExtKeychain::from_random_seed(false).unwrap(); /// let fees = 10_000; /// let value = reward(fees); /// let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0); /// let commit = keychain.commit(value, &key_id).unwrap(); /// let rproof = proof::create(&keychain, value, &key_id, commit, None).unwrap(); /// let output = Output { /// features: OutputFeatures::Coinbase, /// commit: commit, /// proof: rproof, /// }; /// let height = 20; /// let over_commit = secp.commit_value(reward(fees)).unwrap(); /// let out_commit = output.commitment(); /// let msg = kernel_sig_msg(0, height, KernelFeatures::HeightLocked).unwrap(); /// let excess = secp.commit_sum(vec![out_commit], vec![over_commit]).unwrap(); /// let pubkey = excess.to_pubkey(&secp).unwrap(); /// let sig = aggsig::sign_from_key_id(&secp, &keychain, &msg, value, &key_id, Some(&pubkey)).unwrap(); /// ``` pub fn sign_from_key_id<K>( secp: &Secp256k1, k: &K, msg: &Message, value: u64, key_id: &Identifier, blind_sum: Option<&PublicKey>, ) -> Result<Signature, Error> where K: Keychain, { let skey = k.derive_key(value, key_id)?; let sig = aggsig::sign_single(secp, &msg, &skey, None, None, None, blind_sum, None)?; Ok(sig) } /// Simple verification a single signature from a commitment. The public /// key used to verify the signature is derived from the commit. /// Returns `Ok(())` if the signature is valid, or a Signature /// [ErrorKind](../enum.ErrorKind.html) otherwise /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Verification /// * `sig` - The Signature to verify /// * `msg` - The message to sign (fee|lockheight). /// * `commit` - The commitment to verify. The actual public key used /// during verification is derived from this commit. /// /// # Example /// /// ``` /// # extern crate frown_util as util; /// # extern crate frown_core as core; /// # extern crate frown_keychain as keychain; /// use core::consensus::reward; /// use core::libtx::{aggsig, proof}; /// use util::secp::key::{PublicKey, SecretKey}; /// use util::secp::{ContextFlag, Secp256k1}; /// use core::core::transaction::{kernel_sig_msg, KernelFeatures}; /// use core::core::{Output, OutputFeatures}; /// use keychain::{Keychain, ExtKeychain}; /// /// // Create signature /// let secp = Secp256k1::with_caps(ContextFlag::Commit); /// let keychain = ExtKeychain::from_random_seed(false).unwrap(); /// let fees = 10_000; /// let value = reward(fees); /// let key_id = ExtKeychain::derive_key_id(1, 1, 0, 0, 0); /// let commit = keychain.commit(value, &key_id).unwrap(); /// let rproof = proof::create(&keychain, value, &key_id, commit, None).unwrap(); /// let output = Output { /// features: OutputFeatures::Coinbase, /// commit: commit, /// proof: rproof, /// }; /// let height = 20; /// let over_commit = secp.commit_value(reward(fees)).unwrap(); /// let out_commit = output.commitment(); /// let msg = kernel_sig_msg(0, height, KernelFeatures::HeightLocked).unwrap(); /// let excess = secp.commit_sum(vec![out_commit], vec![over_commit]).unwrap(); /// let pubkey = excess.to_pubkey(&secp).unwrap(); /// let sig = aggsig::sign_from_key_id(&secp, &keychain, &msg, value, &key_id, Some(&pubkey)).unwrap(); /// /// // Verify the signature from the excess commit /// let sig_verifies = /// aggsig::verify_single_from_commit(&keychain.secp(), &sig, &msg, &excess); /// assert!(!sig_verifies.is_err()); /// ``` pub fn verify_single_from_commit( secp: &Secp256k1, sig: &Signature, msg: &Message, commit: &Commitment, ) -> Result<(), Error> { let pubkey = commit.to_pubkey(secp)?; if !verify_single(secp, sig, msg, None, &pubkey, Some(&pubkey), false) { Err(ErrorKind::Signature( "Signature validation error".to_string(), ))? } Ok(()) } /// Verifies a completed (summed) signature, which must include the message /// and pubkey sum values that are used during signature creation time /// to create 'e' /// Returns `Ok(())` if the signature is valid, or a Signature /// [ErrorKind](../enum.ErrorKind.html) otherwise /// /// # Arguments /// /// * `secp` - A Secp256k1 Context initialized for Verification /// * `sig` - The Signature to verify /// * `pubkey` - Corresponding Public Key of the private key used to sign the message. /// * `pubkey_sum` - (Optional) The sum of the public keys of all signers participating /// in the full signature. If included, this value is encoded in e. Must be the same /// value as when the signature was created to verify correctly. /// * `msg` - The message to verify (fee|lockheight). /// /// # Example /// /// ``` /// # extern crate frown_core as core; /// # extern crate frown_util as util; /// # extern crate rand; /// use rand::thread_rng; /// use core::libtx::aggsig; /// use util::secp::key::{PublicKey, SecretKey}; /// use util::secp::{ContextFlag, Secp256k1, Message}; /// /// let secp = Secp256k1::with_caps(ContextFlag::Full); /// let secret_nonce = aggsig::create_secnonce(&secp).unwrap(); /// let secret_key = SecretKey::new(&secp, &mut thread_rng()); /// let pub_nonce_sum = PublicKey::from_secret_key(&secp, &secret_nonce).unwrap(); /// // ... Add all other participating nonces /// let pub_key_sum = PublicKey::from_secret_key(&secp, &secret_key).unwrap(); /// // ... Add all other participating keys /// let mut msg_bytes = [0; 32]; /// // ... Encode message /// let message = Message::from_slice(&msg_bytes).unwrap(); /// let sig_part = aggsig::calculate_partial_sig( /// &secp, /// &secret_key, /// &secret_nonce, /// &pub_nonce_sum, /// Some(&pub_key_sum), /// &message, /// ).unwrap(); /// // ... Verify above, once all signatures have been added together /// let sig_verifies = aggsig::verify_completed_sig( /// &secp, /// &sig_part, /// &pub_key_sum, /// Some(&pub_key_sum), /// &message, /// ); /// assert!(!sig_verifies.is_err()); /// ``` pub fn verify_completed_sig( secp: &Secp256k1, sig: &Signature, pubkey: &PublicKey, pubkey_sum: Option<&PublicKey>, msg: &secp::Message, ) -> Result<(), Error> { if !verify_single(secp, sig, msg, None, pubkey, pubkey_sum, true) { Err(ErrorKind::Signature( "Signature validation error".to_string(), ))? } Ok(()) } /// Adds signatures pub fn add_signatures( secp: &Secp256k1, part_sigs: Vec<&Signature>, nonce_sum: &PublicKey, ) -> Result<Signature, Error> { // Add public nonces kR*G + kS*G let sig = aggsig::add_signatures_single(&secp, part_sigs, &nonce_sum)?; Ok(sig) } /// Just a simple sig, creates its own nonce, etc pub fn sign_single( secp: &Secp256k1, msg: &Message, skey: &SecretKey, pubkey_sum: Option<&PublicKey>, ) -> Result<Signature, Error> { let sig = aggsig::sign_single(secp, &msg, skey, None, None, None, pubkey_sum, None)?; Ok(sig) } /// Verifies an aggsig signature pub fn verify_single( secp: &Secp256k1, sig: &Signature, msg: &Message, pubnonce: Option<&PublicKey>, pubkey: &PublicKey, pubkey_sum: Option<&PublicKey>, is_partial: bool, ) -> bool { aggsig::verify_single( secp, sig, msg, pubnonce, pubkey, pubkey_sum, None, is_partial, ) } /// Just a simple sig, creates its own nonce, etc pub fn sign_with_blinding( secp: &Secp256k1, msg: &Message, blinding: &BlindingFactor, pubkey_sum: Option<&PublicKey>, ) -> Result<Signature, Error> { let skey = &blinding.secret_key(&secp)?; //let pubkey_sum = PublicKey::from_secret_key(&secp, &skey)?; let sig = aggsig::sign_single(secp, &msg, skey, None, None, None, pubkey_sum, None)?; Ok(sig) }
33.454545
103
0.678766
d959bb4ec8e32787b4fa1e906109f43d45b8b4a8
13,841
// Copyright (c) 2017-present PyO3 Project and Contributors //! Python Sequence Interface //! Trait and support implementation for implementing sequence use crate::callback::{BoolCallbackConverter, LenResultConverter, PyObjectCallbackConverter}; use crate::err::{PyErr, PyResult}; use crate::exceptions; use crate::ffi; use crate::objectprotocol::ObjectProtocol; use crate::type_object::PyTypeInfo; use crate::types::PyObjectRef; use crate::Python; use crate::{FromPyObject, IntoPyObject}; use std::os::raw::c_int; /// Sequece interface #[allow(unused_variables)] pub trait PySequenceProtocol<'p>: PyTypeInfo + Sized { fn __len__(&'p self) -> Self::Result where Self: PySequenceLenProtocol<'p>, { unimplemented!() } fn __getitem__(&'p self, key: isize) -> Self::Result where Self: PySequenceGetItemProtocol<'p>, { unimplemented!() } fn __setitem__(&'p mut self, key: isize, value: Self::Value) -> Self::Result where Self: PySequenceSetItemProtocol<'p>, { unimplemented!() } fn __delitem__(&'p mut self, key: isize) -> Self::Result where Self: PySequenceDelItemProtocol<'p>, { unimplemented!() } fn __contains__(&'p self, item: Self::Item) -> Self::Result where Self: PySequenceContainsProtocol<'p>, { unimplemented!() } fn __concat__(&'p self, other: Self::Other) -> Self::Result where Self: PySequenceConcatProtocol<'p>, { unimplemented!() } fn __repeat__(&'p self, count: isize) -> Self::Result where Self: PySequenceRepeatProtocol<'p>, { unimplemented!() } fn __inplace_concat__(&'p mut self, other: Self::Other) -> Self::Result where Self: PySequenceInplaceConcatProtocol<'p>, { unimplemented!() } fn __inplace_repeat__(&'p mut self, count: isize) -> Self::Result where Self: PySequenceInplaceRepeatProtocol<'p>, { unimplemented!() } } // The following are a bunch of marker traits used to detect // the existance of a slotted method. pub trait PySequenceLenProtocol<'p>: PySequenceProtocol<'p> { type Result: Into<PyResult<usize>>; } pub trait PySequenceGetItemProtocol<'p>: PySequenceProtocol<'p> { type Success: IntoPyObject; type Result: Into<PyResult<Self::Success>>; } pub trait PySequenceSetItemProtocol<'p>: PySequenceProtocol<'p> { type Value: FromPyObject<'p>; type Result: Into<PyResult<()>>; } pub trait PySequenceDelItemProtocol<'p>: PySequenceProtocol<'p> { type Result: Into<PyResult<()>>; } pub trait PySequenceContainsProtocol<'p>: PySequenceProtocol<'p> { type Item: FromPyObject<'p>; type Result: Into<PyResult<bool>>; } pub trait PySequenceConcatProtocol<'p>: PySequenceProtocol<'p> { type Other: FromPyObject<'p>; type Success: IntoPyObject; type Result: Into<PyResult<Self::Success>>; } pub trait PySequenceRepeatProtocol<'p>: PySequenceProtocol<'p> { type Success: IntoPyObject; type Result: Into<PyResult<Self::Success>>; } pub trait PySequenceInplaceConcatProtocol<'p>: PySequenceProtocol<'p> + IntoPyObject { type Other: FromPyObject<'p>; type Result: Into<PyResult<Self>>; } pub trait PySequenceInplaceRepeatProtocol<'p>: PySequenceProtocol<'p> + IntoPyObject { type Result: Into<PyResult<Self>>; } #[doc(hidden)] pub trait PySequenceProtocolImpl { fn tp_as_sequence() -> Option<ffi::PySequenceMethods> { None } } impl<T> PySequenceProtocolImpl for T {} impl<'p, T> PySequenceProtocolImpl for T where T: PySequenceProtocol<'p>, { fn tp_as_sequence() -> Option<ffi::PySequenceMethods> { #[cfg(Py_3)] return Some(ffi::PySequenceMethods { sq_length: Self::sq_length(), sq_concat: Self::sq_concat(), sq_repeat: Self::sq_repeat(), sq_item: Self::sq_item(), was_sq_slice: ::std::ptr::null_mut(), sq_ass_item: sq_ass_item_impl::sq_ass_item::<Self>(), was_sq_ass_slice: ::std::ptr::null_mut(), sq_contains: Self::sq_contains(), sq_inplace_concat: Self::sq_inplace_concat(), sq_inplace_repeat: Self::sq_inplace_repeat(), }); #[cfg(not(Py_3))] return Some(ffi::PySequenceMethods { sq_length: Self::sq_length(), sq_concat: Self::sq_concat(), sq_repeat: Self::sq_repeat(), sq_item: Self::sq_item(), sq_slice: None, sq_ass_item: sq_ass_item_impl::sq_ass_item::<Self>(), sq_ass_slice: None, sq_contains: Self::sq_contains(), sq_inplace_concat: Self::sq_inplace_concat(), sq_inplace_repeat: Self::sq_inplace_repeat(), }); } } trait PySequenceLenProtocolImpl { fn sq_length() -> Option<ffi::lenfunc> { None } } impl<'p, T> PySequenceLenProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceLenProtocolImpl for T where T: for<'p> PySequenceLenProtocol<'p>, { fn sq_length() -> Option<ffi::lenfunc> { py_len_func!(PySequenceLenProtocol, T::__len__, LenResultConverter) } } trait PySequenceGetItemProtocolImpl { fn sq_item() -> Option<ffi::ssizeargfunc> { None } } impl<'p, T> PySequenceGetItemProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceGetItemProtocolImpl for T where T: for<'p> PySequenceGetItemProtocol<'p>, { fn sq_item() -> Option<ffi::ssizeargfunc> { py_ssizearg_func!( PySequenceGetItemProtocol, T::__getitem__, T::Success, PyObjectCallbackConverter ) } } trait PySequenceSetItemProtocolImpl { fn sq_ass_item() -> Option<ffi::ssizeobjargproc> { None } } impl<'p, T> PySequenceSetItemProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceSetItemProtocolImpl for T where T: for<'p> PySequenceSetItemProtocol<'p>, { fn sq_ass_item() -> Option<ffi::ssizeobjargproc> { unsafe extern "C" fn wrap<T>( slf: *mut ffi::PyObject, key: ffi::Py_ssize_t, value: *mut ffi::PyObject, ) -> c_int where T: for<'p> PySequenceSetItemProtocol<'p>, { let _pool = crate::GILPool::new(); let py = Python::assume_gil_acquired(); let slf = py.mut_from_borrowed_ptr::<T>(slf); let result = if value.is_null() { Err(PyErr::new::<exceptions::NotImplementedError, _>(format!( "Item deletion not supported by {:?}", stringify!(T) ))) } else { let value = py.from_borrowed_ptr::<PyObjectRef>(value); match value.extract() { Ok(value) => slf.__setitem__(key as isize, value).into(), Err(e) => Err(e), } }; match result { Ok(_) => 0, Err(e) => { e.restore(py); -1 } } } Some(wrap::<T>) } } /// It can be possible to delete and set items (PySequenceSetItemProtocol and /// PySequenceDelItemProtocol implemented), only to delete (PySequenceDelItemProtocol implemented) /// or no deleting or setting is possible mod sq_ass_item_impl { use super::*; /// ssizeobjargproc PySequenceMethods.sq_ass_item /// /// This function is used by PySequence_SetItem() and has the same signature. It is also used /// by PyObject_SetItem() and PyObject_DelItem(), after trying the item assignment and deletion /// via the mp_ass_subscript slot. This slot may be left to NULL if the object does not support /// item assignment and deletion. pub(super) fn sq_ass_item<'p, T>() -> Option<ffi::ssizeobjargproc> where T: PySequenceProtocol<'p>, { if let Some(del_set_item) = T::del_set_item() { Some(del_set_item) } else if let Some(del_item) = T::del_item() { Some(del_item) } else { None } } trait DelItem { fn del_item() -> Option<ffi::ssizeobjargproc> { None } } impl<'p, T> DelItem for T where T: PySequenceProtocol<'p> {} impl<T> DelItem for T where T: for<'p> PySequenceDelItemProtocol<'p>, { fn del_item() -> Option<ffi::ssizeobjargproc> { unsafe extern "C" fn wrap<T>( slf: *mut ffi::PyObject, key: ffi::Py_ssize_t, value: *mut ffi::PyObject, ) -> c_int where T: for<'p> PySequenceDelItemProtocol<'p>, { let _pool = crate::GILPool::new(); let py = Python::assume_gil_acquired(); let slf = py.mut_from_borrowed_ptr::<T>(slf); let result = if value.is_null() { slf.__delitem__(key as isize).into() } else { Err(PyErr::new::<exceptions::NotImplementedError, _>(format!( "Item assignment not supported by {:?}", stringify!(T) ))) }; match result { Ok(_) => 0, Err(e) => { e.restore(py); -1 } } } Some(wrap::<T>) } } trait DelSetItem { fn del_set_item() -> Option<ffi::ssizeobjargproc> { None } } impl<'p, T> DelSetItem for T where T: PySequenceProtocol<'p> {} impl<T> DelSetItem for T where T: for<'p> PySequenceSetItemProtocol<'p> + for<'p> PySequenceDelItemProtocol<'p>, { fn del_set_item() -> Option<ffi::ssizeobjargproc> { unsafe extern "C" fn wrap<T>( slf: *mut ffi::PyObject, key: ffi::Py_ssize_t, value: *mut ffi::PyObject, ) -> c_int where T: for<'p> PySequenceSetItemProtocol<'p> + for<'p> PySequenceDelItemProtocol<'p>, { let _pool = crate::GILPool::new(); let py = Python::assume_gil_acquired(); let slf = py.mut_from_borrowed_ptr::<T>(slf); let result = if value.is_null() { slf.__delitem__(key as isize).into() } else { let value = py.from_borrowed_ptr::<PyObjectRef>(value); match value.extract() { Ok(value) => slf.__setitem__(key as isize, value).into(), Err(e) => Err(e), } }; match result { Ok(_) => 0, Err(e) => { e.restore(py); -1 } } } Some(wrap::<T>) } } } trait PySequenceContainsProtocolImpl { fn sq_contains() -> Option<ffi::objobjproc> { None } } impl<'p, T> PySequenceContainsProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceContainsProtocolImpl for T where T: for<'p> PySequenceContainsProtocol<'p>, { fn sq_contains() -> Option<ffi::objobjproc> { py_binary_func!( PySequenceContainsProtocol, T::__contains__, bool, BoolCallbackConverter, c_int ) } } trait PySequenceConcatProtocolImpl { fn sq_concat() -> Option<ffi::binaryfunc> { None } } impl<'p, T> PySequenceConcatProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceConcatProtocolImpl for T where T: for<'p> PySequenceConcatProtocol<'p>, { fn sq_concat() -> Option<ffi::binaryfunc> { py_binary_func!( PySequenceConcatProtocol, T::__concat__, T::Success, PyObjectCallbackConverter ) } } trait PySequenceRepeatProtocolImpl { fn sq_repeat() -> Option<ffi::ssizeargfunc> { None } } impl<'p, T> PySequenceRepeatProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceRepeatProtocolImpl for T where T: for<'p> PySequenceRepeatProtocol<'p>, { fn sq_repeat() -> Option<ffi::ssizeargfunc> { py_ssizearg_func!( PySequenceRepeatProtocol, T::__repeat__, T::Success, PyObjectCallbackConverter ) } } trait PySequenceInplaceConcatProtocolImpl { fn sq_inplace_concat() -> Option<ffi::binaryfunc> { None } } impl<'p, T> PySequenceInplaceConcatProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceInplaceConcatProtocolImpl for T where T: for<'p> PySequenceInplaceConcatProtocol<'p>, { fn sq_inplace_concat() -> Option<ffi::binaryfunc> { py_binary_func!( PySequenceInplaceConcatProtocol, T::__inplace_concat__, T, PyObjectCallbackConverter ) } } trait PySequenceInplaceRepeatProtocolImpl { fn sq_inplace_repeat() -> Option<ffi::ssizeargfunc> { None } } impl<'p, T> PySequenceInplaceRepeatProtocolImpl for T where T: PySequenceProtocol<'p> {} impl<T> PySequenceInplaceRepeatProtocolImpl for T where T: for<'p> PySequenceInplaceRepeatProtocol<'p>, { fn sq_inplace_repeat() -> Option<ffi::ssizeargfunc> { py_ssizearg_func!( PySequenceInplaceRepeatProtocol, T::__inplace_repeat__, T, PyObjectCallbackConverter ) } }
28.246939
99
0.577343
18ea207284a03232a4ead660ab5f5c2db4f59e0d
1,073
use crate::templates; use criterion; pub fn big_table(b: &mut criterion::Bencher<'_>, size: &usize) { let mut table = Vec::with_capacity(*size); for _ in 0..*size { let mut inner = Vec::with_capacity(*size); for i in 0..*size { inner.push(i); } table.push(inner); } b.iter(|| { let mut buf = Vec::new(); templates::big_table(&mut buf, &table).unwrap(); }); } pub fn teams(b: &mut criterion::Bencher<'_>, _: &usize) { let year = 2015; let teams = vec![ Team { name: "Jiangsu".into(), score: 43, }, Team { name: "Beijing".into(), score: 27, }, Team { name: "Guangzhou".into(), score: 22, }, Team { name: "Shandong".into(), score: 12, }, ]; b.iter(|| { let mut buf = Vec::new(); templates::teams(&mut buf, year, &teams).unwrap(); }); } pub struct Team { pub name: String, pub score: u8, }
21.897959
64
0.459459
26082017ca97c5ce04e4c93308106f1d8274f62a
726
use napi::bindgen_prelude::*; #[napi] fn get_buffer() -> Buffer { String::from("Hello world").as_bytes().into() } #[napi] fn append_buffer(buf: Buffer) -> Buffer { let mut buf = Vec::<u8>::from(buf); buf.push(b'!'); buf.into() } #[napi] fn convert_u32_array(input: Uint32Array) -> Vec<u32> { input.to_vec() } #[napi] fn create_external_typed_array() -> Uint32Array { Uint32Array::new(vec![1, 2, 3, 4, 5]) } #[napi] fn mutate_typed_array(mut input: Float32Array) { for item in input.as_mut() { *item *= 2.0; } } #[napi] fn deref_uint8_array(a: Uint8Array, b: Uint8ClampedArray) -> u32 { (a.len() + b.len()) as u32 } #[napi] async fn buffer_pass_through(buf: Buffer) -> Result<Buffer> { Ok(buf) }
17.707317
66
0.636364
09fa5ddfea6bb990baf9b455e3b769d325ef8f11
6,273
use crate::{ cmd::*, keypair::{Keypair, PublicKey}, result::Result, traits::{TxnEnvelope, TxnFee, TxnSign, B64}, }; use helium_api::accounts; use serde_json::json; #[derive(Debug, StructOpt)] /// Create or Redeem from an HTLC address pub enum Cmd { Create(Create), Redeem(Redeem), } #[derive(Debug, StructOpt)] /// Creates a new HTLC address with a specified hashlock and timelock (in block height), and transfers a value of tokens to it. /// The transaction is not submitted to the system unless the '--commit' option is given. pub struct Create { /// The address of the intended payee for this HTLC payee: PublicKey, /// Number of hnt to send #[structopt(long)] hnt: Hnt, /// A hex encoded SHA256 digest of a secret value (called a preimage) that locks this contract #[structopt(long = "hashlock")] hashlock: String, /// A specific blockheight after which the payer (you) can redeem their tokens #[structopt(long = "timelock")] timelock: u64, /// Commit the payment to the API #[structopt(long)] commit: bool, } #[derive(Debug, StructOpt)] /// Redeem the balance from an HTLC address with the specified preimage for the hashlock pub struct Redeem { /// Address of the HTLC contract to redeem from address: PublicKey, /// The preimage used to create the hashlock for this contract address #[structopt(short = "p", long = "preimage")] preimage: String, /// Only output the submitted transaction hash. #[structopt(long)] hash: bool, /// Commit the payment to the API #[structopt(long)] commit: bool, } impl Cmd { pub async fn run(&self, opts: Opts) -> Result { match self { Cmd::Create(cmd) => cmd.run(opts).await, Cmd::Redeem(cmd) => cmd.run(opts).await, } } } impl Create { pub async fn run(&self, opts: Opts) -> Result { let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let client = Client::new_with_base_url(api_url(wallet.public_key.network)); let keypair = wallet.decrypt(password.as_bytes())?; let wallet_address = keypair.public_key(); let account = accounts::get(&client, &wallet_address.to_string()).await?; let address = Keypair::generate(wallet_address.tag()); let mut txn = BlockchainTxnCreateHtlcV1 { amount: u64::from(self.hnt), fee: 0, payee: self.payee.to_vec(), payer: wallet_address.to_vec(), address: address.public_key().to_vec(), hashlock: hex::decode(self.hashlock.clone()).unwrap(), timelock: self.timelock, nonce: account.speculative_nonce + 1, signature: Vec::new(), }; txn.fee = txn.txn_fee(&get_txn_fees(&client).await?)?; txn.signature = txn.sign(&keypair)?; let envelope = txn.in_envelope(); let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_create_txn(&txn, &envelope, &status, opts.format) } } fn print_create_txn( txn: &BlockchainTxnCreateHtlcV1, envelope: &BlockchainTxn, status: &Option<PendingTxnStatus>, format: OutputFormat, ) -> Result { match format { OutputFormat::Table => { ptable!( ["Key", "Value"], ["Address", PublicKey::from_bytes(&txn.address)?.to_string()], ["Payee", PublicKey::from_bytes(&txn.payee)?.to_string()], ["Amount (HNT)", Hnt::from(txn.amount)], ["Fee (DC)", txn.fee], ["Hashlock", hex::encode(&txn.hashlock)], ["Timelock", txn.timelock], ["Nonce", txn.nonce], ["Hash", status_str(status)] ); print_footer(status) } OutputFormat::Json => { let table = json!({ "address": PublicKey::from_bytes(&txn.address)?.to_string(), "payee": PublicKey::from_bytes(&txn.payee)?.to_string(), "amount": txn.amount, "fee": txn.fee, "hashlock": hex::encode(&txn.hashlock), "timelock": txn.timelock, "nonce": txn.nonce, "hash": status_json(status), "txn": envelope.to_b64()?, }); print_json(&table) } } } impl Redeem { pub async fn run(&self, opts: Opts) -> Result { let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let keypair = wallet.decrypt(password.as_bytes())?; let client = Client::new_with_base_url(api_url(wallet.public_key.network)); let mut txn = BlockchainTxnRedeemHtlcV1 { fee: 0, payee: keypair.public_key().to_vec(), address: self.address.to_vec(), preimage: self.preimage.clone().into_bytes(), signature: Vec::new(), }; txn.fee = txn.txn_fee(&get_txn_fees(&client).await?)?; txn.signature = txn.sign(&keypair)?; let envelope = txn.in_envelope(); let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_redeem_txn(&txn, &envelope, &status, opts.format) } } fn print_redeem_txn( txn: &BlockchainTxnRedeemHtlcV1, envelope: &BlockchainTxn, status: &Option<PendingTxnStatus>, format: OutputFormat, ) -> Result { match format { OutputFormat::Table => { ptable!( ["Key", "Value"], ["Payee", PublicKey::from_bytes(&txn.payee)?.to_string()], ["Address", PublicKey::from_bytes(&txn.address)?.to_string()], ["Preimage", std::str::from_utf8(&txn.preimage)?], ["Hash", status_str(status)] ); print_footer(status) } OutputFormat::Json => { let table = json!({ "address": PublicKey::from_bytes(&txn.address)?.to_string(), "payee": PublicKey::from_bytes(&txn.payee)?.to_string(), "hash": status_json(status), "txn": envelope.to_b64()?, }); print_json(&table) } } }
33.190476
127
0.573729
f8240c89056b4ca69aed69aa6b5ee38b83133203
143,913
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. //! Declaration of built-in (scalar) functions. //! This module contains built-in functions' enumeration and metadata. //! //! Generally, a function has: //! * a signature //! * a return type, that is a function of the incoming argument's types //! * the computation, that must accept each valid signature //! //! * Signature: see `Signature` //! * Return type: a function `(arg_types) -> return_type`. E.g. for sqrt, ([f32]) -> f32, ([f64]) -> f64. //! //! This module also has a set of coercion rules to improve user experience: if an argument i32 is passed //! to a function that supports f64, it is coerced to f64. use super::{ type_coercion::{coerce, data_types}, ColumnarValue, PhysicalExpr, }; use crate::execution::context::ExecutionContextState; use crate::physical_plan::array_expressions; use crate::physical_plan::datetime_expressions; use crate::physical_plan::expressions::{ cast_column, nullif_func, DEFAULT_DATAFUSION_CAST_OPTIONS, SUPPORTED_NULLIF_TYPES, }; use crate::physical_plan::math_expressions; use crate::physical_plan::string_expressions; use crate::{ error::{DataFusionError, Result}, scalar::ScalarValue, }; use arrow::{ array::{ArrayRef, NullArray}, compute::kernels::length::{bit_length, length}, datatypes::TimeUnit, datatypes::{DataType, Field, Int32Type, Int64Type, Schema}, record_batch::RecordBatch, }; use fmt::{Debug, Formatter}; use std::convert::From; use std::{any::Any, fmt, str::FromStr, sync::Arc}; use serde::{Deserialize, Serialize}; /// A function's type signature, which defines the function's supported argument types. #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub enum TypeSignature { /// arbitrary number of arguments of an common type out of a list of valid types // A function such as `concat` is `Variadic(vec![DataType::Utf8, DataType::LargeUtf8])` Variadic(Vec<DataType>), /// arbitrary number of arguments of an arbitrary but equal type // A function such as `array` is `VariadicEqual` // The first argument decides the type used for coercion VariadicEqual, /// fixed number of arguments of an arbitrary but equal type out of a list of valid types // A function of one argument of f64 is `Uniform(1, vec![DataType::Float64])` // A function of one argument of f64 or f32 is `Uniform(1, vec![DataType::Float32, DataType::Float64])` Uniform(usize, Vec<DataType>), /// exact number of arguments of an exact type Exact(Vec<DataType>), /// fixed number of arguments of arbitrary types Any(usize), /// One of a list of signatures OneOf(Vec<TypeSignature>), } ///The Signature of a function defines its supported input types as well as its volatility. #[derive(Debug, Clone, PartialEq, PartialOrd)] pub struct Signature { /// type_signature - The types that the function accepts. See [TypeSignature] for more information. pub type_signature: TypeSignature, /// volatility - The volatility of the function. See [Volatility] for more information. pub volatility: Volatility, } impl Signature { /// new - Creates a new Signature from any type signature and the volatility. pub fn new(type_signature: TypeSignature, volatility: Volatility) -> Self { Signature { type_signature, volatility, } } /// variadic - Creates a variadic signature that represents an arbitrary number of arguments all from a type in common_types. pub fn variadic(common_types: Vec<DataType>, volatility: Volatility) -> Self { Self { type_signature: TypeSignature::Variadic(common_types), volatility, } } /// variadic_equal - Creates a variadic signature that represents an arbitrary number of arguments of the same type. pub fn variadic_equal(volatility: Volatility) -> Self { Self { type_signature: TypeSignature::VariadicEqual, volatility, } } /// uniform - Creates a function with a fixed number of arguments of the same type, which must be from valid_types. pub fn uniform( arg_count: usize, valid_types: Vec<DataType>, volatility: Volatility, ) -> Self { Self { type_signature: TypeSignature::Uniform(arg_count, valid_types), volatility, } } /// exact - Creates a signture which must match the types in exact_types in order. pub fn exact(exact_types: Vec<DataType>, volatility: Volatility) -> Self { Signature { type_signature: TypeSignature::Exact(exact_types), volatility, } } /// any - Creates a signature which can a be made of any type but of a specified number pub fn any(arg_count: usize, volatility: Volatility) -> Self { Signature { type_signature: TypeSignature::Any(arg_count), volatility, } } /// one_of Creates a signature which can match any of the [TypeSignature]s which are passed in. pub fn one_of(type_signatures: Vec<TypeSignature>, volatility: Volatility) -> Self { Signature { type_signature: TypeSignature::OneOf(type_signatures), volatility, } } } ///A function's volatility, which defines the functions eligibility for certain optimizations #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] pub enum Volatility { /// Immutable - An immutable function will always return the same output when given the same input. An example of this is [BuiltinScalarFunction::Cos]. Immutable, /// Stable - A stable function may return different values given the same input accross different queries but must return the same value for a given input within a query. An example of this is [BuiltinScalarFunction::Now]. Stable, /// Volatile - A volatile function may change the return value from evaluation to evaluation. Mutiple invocations of a volatile function may return different results when used in the same query. An example of this is [BuiltinScalarFunction::Random]. Volatile, } /// Scalar function /// /// The Fn param is the wrapped function but be aware that the function will /// be passed with the slice / vec of columnar values (either scalar or array) /// with the exception of zero param function, where a singular element vec /// will be passed. In that case the single element is a null array to indicate /// the batch's row count (so that the generative zero-argument function can know /// the result array size). pub type ScalarFunctionImplementation = Arc<dyn Fn(&[ColumnarValue]) -> Result<ColumnarValue> + Send + Sync>; /// A function's return type pub type ReturnTypeFunction = Arc<dyn Fn(&[DataType]) -> Result<Arc<DataType>> + Send + Sync>; /// Enum of all built-in scalar functions #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Serialize, Deserialize)] pub enum BuiltinScalarFunction { // math functions /// abs Abs, /// acos Acos, /// asin Asin, /// atan Atan, /// ceil Ceil, /// cos Cos, /// Digest Digest, /// exp Exp, /// floor Floor, /// ln, Natural logarithm Ln, /// log, same as log10 Log, /// log10 Log10, /// log2 Log2, /// round Round, /// signum Signum, /// sin Sin, /// sqrt Sqrt, /// tan Tan, /// trunc Trunc, // string functions /// construct an array from columns Array, /// ascii Ascii, /// bit_length BitLength, /// btrim Btrim, /// character_length CharacterLength, /// chr Chr, /// concat Concat, /// concat_ws ConcatWithSeparator, /// date_part DatePart, /// date_trunc DateTrunc, /// initcap InitCap, /// left Left, /// lpad Lpad, /// lower Lower, /// ltrim Ltrim, /// md5 MD5, /// nullif NullIf, /// octet_length OctetLength, /// random Random, /// regexp_replace RegexpReplace, /// repeat Repeat, /// replace Replace, /// reverse Reverse, /// right Right, /// rpad Rpad, /// rtrim Rtrim, /// sha224 SHA224, /// sha256 SHA256, /// sha384 SHA384, /// Sha512 SHA512, /// split_part SplitPart, /// starts_with StartsWith, /// strpos Strpos, /// substr Substr, /// to_hex ToHex, /// to_timestamp ToTimestamp, /// to_timestamp_millis ToTimestampMillis, /// to_timestamp_micros ToTimestampMicros, /// to_timestamp_seconds ToTimestampSeconds, ///now Now, /// translate Translate, /// trim Trim, /// upper Upper, /// regexp_match RegexpMatch, } #[cfg(feature = "unicode_expressions")] macro_rules! invoke_if_unicode_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => {{ use crate::physical_plan::unicode_expressions; unicode_expressions::$FUNC::<$T> }}; } #[cfg(not(feature = "unicode_expressions"))] macro_rules! invoke_if_unicode_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => { |_: &[ArrayRef]| -> Result<ArrayRef> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: unicode_expressions.", $NAME ))) } }; } #[cfg(feature = "crypto_expressions")] macro_rules! invoke_if_crypto_expressions_feature_flag { ($FUNC:ident, $NAME:expr) => {{ use crate::physical_plan::crypto_expressions; crypto_expressions::$FUNC }}; } #[cfg(not(feature = "crypto_expressions"))] macro_rules! invoke_if_crypto_expressions_feature_flag { ($FUNC:ident, $NAME:expr) => { |_: &[ColumnarValue]| -> Result<ColumnarValue> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: crypto_expressions.", $NAME ))) } }; } #[cfg(feature = "regex_expressions")] macro_rules! invoke_if_regex_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => {{ use crate::physical_plan::regex_expressions; regex_expressions::$FUNC::<$T> }}; } #[cfg(not(feature = "regex_expressions"))] macro_rules! invoke_if_regex_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => { |_: &[ArrayRef]| -> Result<ArrayRef> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: regex_expressions.", $NAME ))) } }; } impl BuiltinScalarFunction { fn to_func(&self, args: &Vec<Arc<dyn PhysicalExpr>>, input_schema: &Schema) -> Result<ScalarFunctionImplementation> { let fun_expr: ScalarFunctionImplementation = match self { // These functions need args and input schema to pick an implementation // Unlike the string functions, which actually figure out the function to use with each array, // here we return either a cast fn or string timestamp translation based on the expression data type // so we don't have to pay a per-array/batch cost. BuiltinScalarFunction::ToTimestamp => { Arc::new(match args[0].data_type(input_schema) { Ok(DataType::Int64) | Ok(DataType::Timestamp(_, None)) => { |col_values: &[ColumnarValue]| { cast_column( &col_values[0], &DataType::Timestamp(TimeUnit::Nanosecond, None), &DEFAULT_DATAFUSION_CAST_OPTIONS, ) } } Ok(DataType::Utf8) => datetime_expressions::to_timestamp, other => { return Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function to_timestamp", other, ))) } }) } BuiltinScalarFunction::ToTimestampMillis => { Arc::new(match args[0].data_type(input_schema) { Ok(DataType::Int64) | Ok(DataType::Timestamp(_, None)) => { |col_values: &[ColumnarValue]| { cast_column( &col_values[0], &DataType::Timestamp(TimeUnit::Millisecond, None), &DEFAULT_DATAFUSION_CAST_OPTIONS, ) } } Ok(DataType::Utf8) => datetime_expressions::to_timestamp_millis, other => { return Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function to_timestamp_millis", other, ))) } }) } BuiltinScalarFunction::ToTimestampMicros => { Arc::new(match args[0].data_type(input_schema) { Ok(DataType::Int64) | Ok(DataType::Timestamp(_, None)) => { |col_values: &[ColumnarValue]| { cast_column( &col_values[0], &DataType::Timestamp(TimeUnit::Microsecond, None), &DEFAULT_DATAFUSION_CAST_OPTIONS, ) } } Ok(DataType::Utf8) => datetime_expressions::to_timestamp_micros, other => { return Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function to_timestamp_micros", other, ))) } }) } BuiltinScalarFunction::ToTimestampSeconds => Arc::new({ match args[0].data_type(input_schema) { Ok(DataType::Int64) | Ok(DataType::Timestamp(_, None)) => { |col_values: &[ColumnarValue]| { cast_column( &col_values[0], &DataType::Timestamp(TimeUnit::Second, None), &DEFAULT_DATAFUSION_CAST_OPTIONS, ) } } Ok(DataType::Utf8) => datetime_expressions::to_timestamp_seconds, other => { return Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function to_timestamp_seconds", other, ))) } } }), // These don't need args and input schema _ => create_physical_fun(self)?, }; Ok(fun_expr) } /// an allowlist of functions to take zero arguments, so that they will get special treatment /// while executing. fn supports_zero_argument(&self) -> bool { matches!( self, BuiltinScalarFunction::Random | BuiltinScalarFunction::Now ) } /// Returns the [Volatility] of the builtin function. pub fn volatility(&self) -> Volatility { match self { //Immutable scalar builtins BuiltinScalarFunction::Abs => Volatility::Immutable, BuiltinScalarFunction::Acos => Volatility::Immutable, BuiltinScalarFunction::Asin => Volatility::Immutable, BuiltinScalarFunction::Atan => Volatility::Immutable, BuiltinScalarFunction::Ceil => Volatility::Immutable, BuiltinScalarFunction::Cos => Volatility::Immutable, BuiltinScalarFunction::Exp => Volatility::Immutable, BuiltinScalarFunction::Floor => Volatility::Immutable, BuiltinScalarFunction::Ln => Volatility::Immutable, BuiltinScalarFunction::Log => Volatility::Immutable, BuiltinScalarFunction::Log10 => Volatility::Immutable, BuiltinScalarFunction::Log2 => Volatility::Immutable, BuiltinScalarFunction::Round => Volatility::Immutable, BuiltinScalarFunction::Signum => Volatility::Immutable, BuiltinScalarFunction::Sin => Volatility::Immutable, BuiltinScalarFunction::Sqrt => Volatility::Immutable, BuiltinScalarFunction::Tan => Volatility::Immutable, BuiltinScalarFunction::Trunc => Volatility::Immutable, BuiltinScalarFunction::Array => Volatility::Immutable, BuiltinScalarFunction::Ascii => Volatility::Immutable, BuiltinScalarFunction::BitLength => Volatility::Immutable, BuiltinScalarFunction::Btrim => Volatility::Immutable, BuiltinScalarFunction::CharacterLength => Volatility::Immutable, BuiltinScalarFunction::Chr => Volatility::Immutable, BuiltinScalarFunction::Concat => Volatility::Immutable, BuiltinScalarFunction::ConcatWithSeparator => Volatility::Immutable, BuiltinScalarFunction::DatePart => Volatility::Immutable, BuiltinScalarFunction::DateTrunc => Volatility::Immutable, BuiltinScalarFunction::InitCap => Volatility::Immutable, BuiltinScalarFunction::Left => Volatility::Immutable, BuiltinScalarFunction::Lpad => Volatility::Immutable, BuiltinScalarFunction::Lower => Volatility::Immutable, BuiltinScalarFunction::Ltrim => Volatility::Immutable, BuiltinScalarFunction::MD5 => Volatility::Immutable, BuiltinScalarFunction::NullIf => Volatility::Immutable, BuiltinScalarFunction::OctetLength => Volatility::Immutable, BuiltinScalarFunction::RegexpReplace => Volatility::Immutable, BuiltinScalarFunction::Repeat => Volatility::Immutable, BuiltinScalarFunction::Replace => Volatility::Immutable, BuiltinScalarFunction::Reverse => Volatility::Immutable, BuiltinScalarFunction::Right => Volatility::Immutable, BuiltinScalarFunction::Rpad => Volatility::Immutable, BuiltinScalarFunction::Rtrim => Volatility::Immutable, BuiltinScalarFunction::SHA224 => Volatility::Immutable, BuiltinScalarFunction::SHA256 => Volatility::Immutable, BuiltinScalarFunction::SHA384 => Volatility::Immutable, BuiltinScalarFunction::SHA512 => Volatility::Immutable, BuiltinScalarFunction::Digest => Volatility::Immutable, BuiltinScalarFunction::SplitPart => Volatility::Immutable, BuiltinScalarFunction::StartsWith => Volatility::Immutable, BuiltinScalarFunction::Strpos => Volatility::Immutable, BuiltinScalarFunction::Substr => Volatility::Immutable, BuiltinScalarFunction::ToHex => Volatility::Immutable, BuiltinScalarFunction::ToTimestamp => Volatility::Immutable, BuiltinScalarFunction::ToTimestampMillis => Volatility::Immutable, BuiltinScalarFunction::ToTimestampMicros => Volatility::Immutable, BuiltinScalarFunction::ToTimestampSeconds => Volatility::Immutable, BuiltinScalarFunction::Translate => Volatility::Immutable, BuiltinScalarFunction::Trim => Volatility::Immutable, BuiltinScalarFunction::Upper => Volatility::Immutable, BuiltinScalarFunction::RegexpMatch => Volatility::Immutable, //Stable builtin functions BuiltinScalarFunction::Now => Volatility::Stable, //Volatile builtin functions BuiltinScalarFunction::Random => Volatility::Volatile, } } } impl fmt::Display for BuiltinScalarFunction { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // lowercase of the debug. write!(f, "{}", format!("{:?}", self).to_lowercase()) } } impl FromStr for BuiltinScalarFunction { type Err = DataFusionError; fn from_str(name: &str) -> Result<BuiltinScalarFunction> { Ok(match name { // math functions "abs" => BuiltinScalarFunction::Abs, "acos" => BuiltinScalarFunction::Acos, "asin" => BuiltinScalarFunction::Asin, "atan" => BuiltinScalarFunction::Atan, "ceil" => BuiltinScalarFunction::Ceil, "cos" => BuiltinScalarFunction::Cos, "exp" => BuiltinScalarFunction::Exp, "floor" => BuiltinScalarFunction::Floor, "ln" => BuiltinScalarFunction::Ln, "log" => BuiltinScalarFunction::Log, "log10" => BuiltinScalarFunction::Log10, "log2" => BuiltinScalarFunction::Log2, "round" => BuiltinScalarFunction::Round, "signum" => BuiltinScalarFunction::Signum, "sin" => BuiltinScalarFunction::Sin, "sqrt" => BuiltinScalarFunction::Sqrt, "tan" => BuiltinScalarFunction::Tan, "trunc" => BuiltinScalarFunction::Trunc, // string functions "array" => BuiltinScalarFunction::Array, "ascii" => BuiltinScalarFunction::Ascii, "bit_length" => BuiltinScalarFunction::BitLength, "btrim" => BuiltinScalarFunction::Btrim, "char_length" => BuiltinScalarFunction::CharacterLength, "character_length" => BuiltinScalarFunction::CharacterLength, "concat" => BuiltinScalarFunction::Concat, "concat_ws" => BuiltinScalarFunction::ConcatWithSeparator, "chr" => BuiltinScalarFunction::Chr, "date_part" | "datepart" => BuiltinScalarFunction::DatePart, "date_trunc" | "datetrunc" => BuiltinScalarFunction::DateTrunc, "initcap" => BuiltinScalarFunction::InitCap, "left" => BuiltinScalarFunction::Left, "length" => BuiltinScalarFunction::CharacterLength, "lower" => BuiltinScalarFunction::Lower, "lpad" => BuiltinScalarFunction::Lpad, "ltrim" => BuiltinScalarFunction::Ltrim, "md5" => BuiltinScalarFunction::MD5, "nullif" => BuiltinScalarFunction::NullIf, "octet_length" => BuiltinScalarFunction::OctetLength, "random" => BuiltinScalarFunction::Random, "regexp_replace" => BuiltinScalarFunction::RegexpReplace, "repeat" => BuiltinScalarFunction::Repeat, "replace" => BuiltinScalarFunction::Replace, "reverse" => BuiltinScalarFunction::Reverse, "right" => BuiltinScalarFunction::Right, "rpad" => BuiltinScalarFunction::Rpad, "rtrim" => BuiltinScalarFunction::Rtrim, "sha224" => BuiltinScalarFunction::SHA224, "sha256" => BuiltinScalarFunction::SHA256, "sha384" => BuiltinScalarFunction::SHA384, "sha512" => BuiltinScalarFunction::SHA512, "digest" => BuiltinScalarFunction::Digest, "split_part" => BuiltinScalarFunction::SplitPart, "starts_with" => BuiltinScalarFunction::StartsWith, "strpos" => BuiltinScalarFunction::Strpos, "substr" => BuiltinScalarFunction::Substr, "to_hex" => BuiltinScalarFunction::ToHex, "to_timestamp" => BuiltinScalarFunction::ToTimestamp, "to_timestamp_millis" => BuiltinScalarFunction::ToTimestampMillis, "to_timestamp_micros" => BuiltinScalarFunction::ToTimestampMicros, "to_timestamp_seconds" => BuiltinScalarFunction::ToTimestampSeconds, "now" => BuiltinScalarFunction::Now, "translate" => BuiltinScalarFunction::Translate, "trim" => BuiltinScalarFunction::Trim, "upper" => BuiltinScalarFunction::Upper, "regexp_match" => BuiltinScalarFunction::RegexpMatch, _ => { return Err(DataFusionError::Plan(format!( "There is no built-in function named {}", name ))) } }) } } macro_rules! make_utf8_to_return_type { ($FUNC:ident, $largeUtf8Type:expr, $utf8Type:expr) => { fn $FUNC(arg_type: &DataType, name: &str) -> Result<DataType> { Ok(match arg_type { DataType::LargeUtf8 => $largeUtf8Type, DataType::Utf8 => $utf8Type, _ => { // this error is internal as `data_types` should have captured this. return Err(DataFusionError::Internal(format!( "The {:?} function can only accept strings.", name ))); } }) } }; } make_utf8_to_return_type!(utf8_to_str_type, DataType::LargeUtf8, DataType::Utf8); make_utf8_to_return_type!(utf8_to_int_type, DataType::Int64, DataType::Int32); make_utf8_to_return_type!(utf8_to_binary_type, DataType::Binary, DataType::Binary); /// Returns the datatype of the scalar function pub fn return_type( fun: &BuiltinScalarFunction, input_expr_types: &[DataType], ) -> Result<DataType> { // Note that this function *must* return the same type that the respective physical expression returns // or the execution panics. if input_expr_types.is_empty() && !fun.supports_zero_argument() { return Err(DataFusionError::Internal(format!( "Builtin scalar function {} does not support empty arguments", fun ))); } // verify that this is a valid set of data types for this function data_types(input_expr_types, &signature(fun))?; // the return type of the built in function. // Some built-in functions' return type depends on the incoming type. match fun { BuiltinScalarFunction::Array => Ok(DataType::FixedSizeList( Box::new(Field::new("item", input_expr_types[0].clone(), true)), input_expr_types.len() as i32, )), BuiltinScalarFunction::Ascii => Ok(DataType::Int32), BuiltinScalarFunction::BitLength => { utf8_to_int_type(&input_expr_types[0], "bit_length") } BuiltinScalarFunction::Btrim => utf8_to_str_type(&input_expr_types[0], "btrim"), BuiltinScalarFunction::CharacterLength => { utf8_to_int_type(&input_expr_types[0], "character_length") } BuiltinScalarFunction::Chr => Ok(DataType::Utf8), BuiltinScalarFunction::Concat => Ok(DataType::Utf8), BuiltinScalarFunction::ConcatWithSeparator => Ok(DataType::Utf8), BuiltinScalarFunction::DatePart => Ok(DataType::Int32), BuiltinScalarFunction::DateTrunc => { Ok(DataType::Timestamp(TimeUnit::Nanosecond, None)) } BuiltinScalarFunction::InitCap => { utf8_to_str_type(&input_expr_types[0], "initcap") } BuiltinScalarFunction::Left => utf8_to_str_type(&input_expr_types[0], "left"), BuiltinScalarFunction::Lower => utf8_to_str_type(&input_expr_types[0], "lower"), BuiltinScalarFunction::Lpad => utf8_to_str_type(&input_expr_types[0], "lpad"), BuiltinScalarFunction::Ltrim => utf8_to_str_type(&input_expr_types[0], "ltrim"), BuiltinScalarFunction::MD5 => utf8_to_str_type(&input_expr_types[0], "md5"), BuiltinScalarFunction::NullIf => { // NULLIF has two args and they might get coerced, get a preview of this let coerced_types = data_types(input_expr_types, &signature(fun)); coerced_types.map(|typs| typs[0].clone()) } BuiltinScalarFunction::OctetLength => { utf8_to_int_type(&input_expr_types[0], "octet_length") } BuiltinScalarFunction::Random => Ok(DataType::Float64), BuiltinScalarFunction::RegexpReplace => { utf8_to_str_type(&input_expr_types[0], "regex_replace") } BuiltinScalarFunction::Repeat => utf8_to_str_type(&input_expr_types[0], "repeat"), BuiltinScalarFunction::Replace => { utf8_to_str_type(&input_expr_types[0], "replace") } BuiltinScalarFunction::Reverse => { utf8_to_str_type(&input_expr_types[0], "reverse") } BuiltinScalarFunction::Right => utf8_to_str_type(&input_expr_types[0], "right"), BuiltinScalarFunction::Rpad => utf8_to_str_type(&input_expr_types[0], "rpad"), BuiltinScalarFunction::Rtrim => utf8_to_str_type(&input_expr_types[0], "rtrimp"), BuiltinScalarFunction::SHA224 => { utf8_to_binary_type(&input_expr_types[0], "sha224") } BuiltinScalarFunction::SHA256 => { utf8_to_binary_type(&input_expr_types[0], "sha256") } BuiltinScalarFunction::SHA384 => { utf8_to_binary_type(&input_expr_types[0], "sha384") } BuiltinScalarFunction::SHA512 => { utf8_to_binary_type(&input_expr_types[0], "sha512") } BuiltinScalarFunction::Digest => { utf8_to_binary_type(&input_expr_types[0], "digest") } BuiltinScalarFunction::SplitPart => { utf8_to_str_type(&input_expr_types[0], "split_part") } BuiltinScalarFunction::StartsWith => Ok(DataType::Boolean), BuiltinScalarFunction::Strpos => utf8_to_int_type(&input_expr_types[0], "strpos"), BuiltinScalarFunction::Substr => utf8_to_str_type(&input_expr_types[0], "substr"), BuiltinScalarFunction::ToHex => Ok(match input_expr_types[0] { DataType::Int8 | DataType::Int16 | DataType::Int32 | DataType::Int64 => { DataType::Utf8 } _ => { // this error is internal as `data_types` should have captured this. return Err(DataFusionError::Internal( "The to_hex function can only accept integers.".to_string(), )); } }), BuiltinScalarFunction::ToTimestamp => { Ok(DataType::Timestamp(TimeUnit::Nanosecond, None)) } BuiltinScalarFunction::ToTimestampMillis => { Ok(DataType::Timestamp(TimeUnit::Millisecond, None)) } BuiltinScalarFunction::ToTimestampMicros => { Ok(DataType::Timestamp(TimeUnit::Microsecond, None)) } BuiltinScalarFunction::ToTimestampSeconds => { Ok(DataType::Timestamp(TimeUnit::Second, None)) } BuiltinScalarFunction::Now => Ok(DataType::Timestamp( TimeUnit::Nanosecond, Some("UTC".to_owned()), )), BuiltinScalarFunction::Translate => { utf8_to_str_type(&input_expr_types[0], "translate") } BuiltinScalarFunction::Trim => utf8_to_str_type(&input_expr_types[0], "trim"), BuiltinScalarFunction::Upper => utf8_to_str_type(&input_expr_types[0], "upper"), BuiltinScalarFunction::RegexpMatch => Ok(match input_expr_types[0] { DataType::LargeUtf8 => { DataType::List(Box::new(Field::new("item", DataType::LargeUtf8, true))) } DataType::Utf8 => { DataType::List(Box::new(Field::new("item", DataType::Utf8, true))) } _ => { // this error is internal as `data_types` should have captured this. return Err(DataFusionError::Internal( "The regexp_extract function can only accept strings.".to_string(), )); } }), BuiltinScalarFunction::Abs | BuiltinScalarFunction::Acos | BuiltinScalarFunction::Asin | BuiltinScalarFunction::Atan | BuiltinScalarFunction::Ceil | BuiltinScalarFunction::Cos | BuiltinScalarFunction::Exp | BuiltinScalarFunction::Floor | BuiltinScalarFunction::Log | BuiltinScalarFunction::Ln | BuiltinScalarFunction::Log10 | BuiltinScalarFunction::Log2 | BuiltinScalarFunction::Round | BuiltinScalarFunction::Signum | BuiltinScalarFunction::Sin | BuiltinScalarFunction::Sqrt | BuiltinScalarFunction::Tan | BuiltinScalarFunction::Trunc => match input_expr_types[0] { DataType::Float32 => Ok(DataType::Float32), _ => Ok(DataType::Float64), }, } } #[cfg(feature = "crypto_expressions")] macro_rules! invoke_if_crypto_expressions_feature_flag { ($FUNC:ident, $NAME:expr) => {{ use crate::physical_plan::crypto_expressions; crypto_expressions::$FUNC }}; } #[cfg(not(feature = "crypto_expressions"))] macro_rules! invoke_if_crypto_expressions_feature_flag { ($FUNC:ident, $NAME:expr) => { |_: &[ColumnarValue]| -> Result<ColumnarValue> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: crypto_expressions.", $NAME ))) } }; } #[cfg(feature = "regex_expressions")] macro_rules! invoke_if_regex_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => {{ use crate::physical_plan::regex_expressions; regex_expressions::$FUNC::<$T> }}; } #[cfg(not(feature = "regex_expressions"))] macro_rules! invoke_if_regex_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => { |_: &[ArrayRef]| -> Result<ArrayRef> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: regex_expressions.", $NAME ))) } }; } #[cfg(feature = "unicode_expressions")] macro_rules! invoke_if_unicode_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => {{ use crate::physical_plan::unicode_expressions; unicode_expressions::$FUNC::<$T> }}; } #[cfg(not(feature = "unicode_expressions"))] macro_rules! invoke_if_unicode_expressions_feature_flag { ($FUNC:ident, $T:tt, $NAME:expr) => { |_: &[ArrayRef]| -> Result<ArrayRef> { Err(DataFusionError::Internal(format!( "function {} requires compilation with feature flag: unicode_expressions.", $NAME ))) } }; } /// Create a physical scalar function. pub fn create_physical_fun( fun: &BuiltinScalarFunction ) -> Result<ScalarFunctionImplementation> { Ok(match fun { // math functions BuiltinScalarFunction::Abs => Arc::new(math_expressions::abs), BuiltinScalarFunction::Acos => Arc::new(math_expressions::acos), BuiltinScalarFunction::Asin => Arc::new(math_expressions::asin), BuiltinScalarFunction::Atan => Arc::new(math_expressions::atan), BuiltinScalarFunction::Ceil => Arc::new(math_expressions::ceil), BuiltinScalarFunction::Cos => Arc::new(math_expressions::cos), BuiltinScalarFunction::Exp => Arc::new(math_expressions::exp), BuiltinScalarFunction::Floor => Arc::new(math_expressions::floor), BuiltinScalarFunction::Log => Arc::new(math_expressions::log10), BuiltinScalarFunction::Ln => Arc::new(math_expressions::ln), BuiltinScalarFunction::Log10 => Arc::new(math_expressions::log10), BuiltinScalarFunction::Log2 => Arc::new(math_expressions::log2), BuiltinScalarFunction::Random => Arc::new(math_expressions::random), BuiltinScalarFunction::Round => Arc::new(math_expressions::round), BuiltinScalarFunction::Signum => Arc::new(math_expressions::signum), BuiltinScalarFunction::Sin => Arc::new(math_expressions::sin), BuiltinScalarFunction::Sqrt => Arc::new(math_expressions::sqrt), BuiltinScalarFunction::Tan => Arc::new(math_expressions::tan), BuiltinScalarFunction::Trunc => Arc::new(math_expressions::trunc), // string functions BuiltinScalarFunction::Array => Arc::new(array_expressions::array), BuiltinScalarFunction::Ascii => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::ascii::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::ascii::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function ascii", other, ))), }), BuiltinScalarFunction::BitLength => Arc::new(|args| match &args[0] { ColumnarValue::Array(v) => Ok(ColumnarValue::Array(bit_length(v.as_ref())?)), ColumnarValue::Scalar(v) => match v { ScalarValue::Utf8(v) => Ok(ColumnarValue::Scalar(ScalarValue::Int32( v.as_ref().map(|x| (x.len() * 8) as i32), ))), ScalarValue::LargeUtf8(v) => Ok(ColumnarValue::Scalar( ScalarValue::Int64(v.as_ref().map(|x| (x.len() * 8) as i64)), )), _ => unreachable!(), }, }), BuiltinScalarFunction::Btrim => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::btrim::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::btrim::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function btrim", other, ))), }), BuiltinScalarFunction::CharacterLength => { Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!( character_length, Int32Type, "character_length" ); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!( character_length, Int64Type, "character_length" ); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function character_length", other, ))), }) } BuiltinScalarFunction::Chr => { Arc::new(|args| make_scalar_function(string_expressions::chr)(args)) } BuiltinScalarFunction::Concat => Arc::new(string_expressions::concat), BuiltinScalarFunction::ConcatWithSeparator => { Arc::new(|args| make_scalar_function(string_expressions::concat_ws)(args)) } BuiltinScalarFunction::DatePart => Arc::new(datetime_expressions::date_part), BuiltinScalarFunction::DateTrunc => Arc::new(datetime_expressions::date_trunc), BuiltinScalarFunction::Now => { // bind value for now at plan time Arc::new(datetime_expressions::make_now( chrono::Utc::now(), )) } BuiltinScalarFunction::InitCap => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::initcap::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::initcap::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function initcap", other, ))), }), BuiltinScalarFunction::Left => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(left, i32, "left"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(left, i64, "left"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function left", other, ))), }), BuiltinScalarFunction::Lower => Arc::new(string_expressions::lower), BuiltinScalarFunction::Lpad => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(lpad, i32, "lpad"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(lpad, i64, "lpad"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function lpad", other, ))), }), BuiltinScalarFunction::Ltrim => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::ltrim::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::ltrim::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function ltrim", other, ))), }), BuiltinScalarFunction::MD5 => { Arc::new(invoke_if_crypto_expressions_feature_flag!(md5, "md5")) } BuiltinScalarFunction::Digest => { Arc::new(invoke_if_crypto_expressions_feature_flag!(digest, "digest")) } BuiltinScalarFunction::NullIf => Arc::new(nullif_func), BuiltinScalarFunction::OctetLength => Arc::new(|args| match &args[0] { ColumnarValue::Array(v) => Ok(ColumnarValue::Array(length(v.as_ref())?)), ColumnarValue::Scalar(v) => match v { ScalarValue::Utf8(v) => Ok(ColumnarValue::Scalar(ScalarValue::Int32( v.as_ref().map(|x| x.len() as i32), ))), ScalarValue::LargeUtf8(v) => Ok(ColumnarValue::Scalar( ScalarValue::Int64(v.as_ref().map(|x| x.len() as i64)), )), _ => unreachable!(), }, }), BuiltinScalarFunction::RegexpMatch => { Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_regex_expressions_feature_flag!( regexp_match, i32, "regexp_match" ); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_regex_expressions_feature_flag!( regexp_match, i64, "regexp_match" ); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function regexp_match", other ))), }) } BuiltinScalarFunction::RegexpReplace => { Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_regex_expressions_feature_flag!( regexp_replace, i32, "regexp_replace" ); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_regex_expressions_feature_flag!( regexp_replace, i64, "regexp_replace" ); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function regexp_replace", other, ))), }) } BuiltinScalarFunction::Repeat => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::repeat::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::repeat::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function repeat", other, ))), }), BuiltinScalarFunction::Replace => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::replace::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::replace::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function replace", other, ))), }), BuiltinScalarFunction::Reverse => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(reverse, i32, "reverse"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(reverse, i64, "reverse"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function reverse", other, ))), }), BuiltinScalarFunction::Right => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(right, i32, "right"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(right, i64, "right"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function right", other, ))), }), BuiltinScalarFunction::Rpad => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(rpad, i32, "rpad"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(rpad, i64, "rpad"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function rpad", other, ))), }), BuiltinScalarFunction::Rtrim => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::rtrim::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::rtrim::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function rtrim", other, ))), }), BuiltinScalarFunction::SHA224 => { Arc::new(invoke_if_crypto_expressions_feature_flag!(sha224, "sha224")) } BuiltinScalarFunction::SHA256 => { Arc::new(invoke_if_crypto_expressions_feature_flag!(sha256, "sha256")) } BuiltinScalarFunction::SHA384 => { Arc::new(invoke_if_crypto_expressions_feature_flag!(sha384, "sha384")) } BuiltinScalarFunction::SHA512 => { Arc::new(invoke_if_crypto_expressions_feature_flag!(sha512, "sha512")) } BuiltinScalarFunction::SplitPart => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::split_part::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::split_part::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function split_part", other, ))), }), BuiltinScalarFunction::StartsWith => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::starts_with::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::starts_with::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function starts_with", other, ))), }), BuiltinScalarFunction::Strpos => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!( strpos, Int32Type, "strpos" ); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!( strpos, Int64Type, "strpos" ); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function strpos", other, ))), }), BuiltinScalarFunction::Substr => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!(substr, i32, "substr"); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!(substr, i64, "substr"); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function substr", other, ))), }), BuiltinScalarFunction::ToHex => Arc::new(|args| match args[0].data_type() { DataType::Int32 => { make_scalar_function(string_expressions::to_hex::<Int32Type>)(args) } DataType::Int64 => { make_scalar_function(string_expressions::to_hex::<Int64Type>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function to_hex", other, ))), }), BuiltinScalarFunction::Translate => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { let func = invoke_if_unicode_expressions_feature_flag!( translate, i32, "translate" ); make_scalar_function(func)(args) } DataType::LargeUtf8 => { let func = invoke_if_unicode_expressions_feature_flag!( translate, i64, "translate" ); make_scalar_function(func)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function translate", other, ))), }), BuiltinScalarFunction::Trim => Arc::new(|args| match args[0].data_type() { DataType::Utf8 => { make_scalar_function(string_expressions::btrim::<i32>)(args) } DataType::LargeUtf8 => { make_scalar_function(string_expressions::btrim::<i64>)(args) } other => Err(DataFusionError::Internal(format!( "Unsupported data type {:?} for function trim", other, ))), }), BuiltinScalarFunction::Upper => Arc::new(string_expressions::upper), _ => { return Err(DataFusionError::Internal(format!( "create_physical_fun: Unsupported scalar function {:?}", fun ))) } }) } /// Create a physical (function) expression. /// This function errors when `args`' can't be coerced to a valid argument type of the function. pub fn create_physical_expr( fun: &BuiltinScalarFunction, input_phy_exprs: &[Arc<dyn PhysicalExpr>], input_schema: &Schema, ctx_state: &ExecutionContextState, ) -> Result<Arc<dyn PhysicalExpr>> { let coerced_phy_exprs = coerce(input_phy_exprs, input_schema, &signature(fun))?; let coerced_expr_types = coerced_phy_exprs .iter() .map(|e| e.data_type(input_schema)) .collect::<Result<Vec<_>>>()?; let data_type = return_type(fun, &coerced_expr_types)?; Ok(Arc::new(ScalarFunctionExpr::new( &format!("{}", fun), fun.clone(), coerced_phy_exprs, &data_type, ))) } /// the signatures supported by the function `fun`. fn signature(fun: &BuiltinScalarFunction) -> Signature { // note: the physical expression must accept the type returned by this function or the execution panics. // for now, the list is small, as we do not have many built-in functions. match fun { BuiltinScalarFunction::Array => Signature::variadic( array_expressions::SUPPORTED_ARRAY_TYPES.to_vec(), fun.volatility(), ), BuiltinScalarFunction::Concat | BuiltinScalarFunction::ConcatWithSeparator => { Signature::variadic(vec![DataType::Utf8], fun.volatility()) } BuiltinScalarFunction::Ascii | BuiltinScalarFunction::BitLength | BuiltinScalarFunction::CharacterLength | BuiltinScalarFunction::InitCap | BuiltinScalarFunction::Lower | BuiltinScalarFunction::MD5 | BuiltinScalarFunction::OctetLength | BuiltinScalarFunction::Reverse | BuiltinScalarFunction::SHA224 | BuiltinScalarFunction::SHA256 | BuiltinScalarFunction::SHA384 | BuiltinScalarFunction::SHA512 | BuiltinScalarFunction::Trim | BuiltinScalarFunction::Upper => Signature::uniform( 1, vec![DataType::Utf8, DataType::LargeUtf8], fun.volatility(), ), BuiltinScalarFunction::Btrim | BuiltinScalarFunction::Ltrim | BuiltinScalarFunction::Rtrim => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8]), TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]), ], fun.volatility(), ), BuiltinScalarFunction::Chr | BuiltinScalarFunction::ToHex => { Signature::uniform(1, vec![DataType::Int64], fun.volatility()) } BuiltinScalarFunction::Lpad | BuiltinScalarFunction::Rpad => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Int64, DataType::Utf8, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::Int64, DataType::Utf8, ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Int64, DataType::LargeUtf8, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::Int64, DataType::LargeUtf8, ]), ], fun.volatility(), ), BuiltinScalarFunction::Left | BuiltinScalarFunction::Repeat | BuiltinScalarFunction::Right => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]), ], fun.volatility(), ), BuiltinScalarFunction::ToTimestamp => Signature::uniform( 1, vec![ DataType::Utf8, DataType::Int64, DataType::Timestamp(TimeUnit::Millisecond, None), DataType::Timestamp(TimeUnit::Microsecond, None), DataType::Timestamp(TimeUnit::Second, None), ], fun.volatility(), ), BuiltinScalarFunction::ToTimestampMillis => Signature::uniform( 1, vec![ DataType::Utf8, DataType::Int64, DataType::Timestamp(TimeUnit::Nanosecond, None), DataType::Timestamp(TimeUnit::Microsecond, None), DataType::Timestamp(TimeUnit::Second, None), ], fun.volatility(), ), BuiltinScalarFunction::ToTimestampMicros => Signature::uniform( 1, vec![ DataType::Utf8, DataType::Int64, DataType::Timestamp(TimeUnit::Nanosecond, None), DataType::Timestamp(TimeUnit::Millisecond, None), DataType::Timestamp(TimeUnit::Second, None), ], fun.volatility(), ), BuiltinScalarFunction::ToTimestampSeconds => Signature::uniform( 1, vec![ DataType::Utf8, DataType::Int64, DataType::Timestamp(TimeUnit::Nanosecond, None), DataType::Timestamp(TimeUnit::Microsecond, None), DataType::Timestamp(TimeUnit::Millisecond, None), ], fun.volatility(), ), BuiltinScalarFunction::Digest => { Signature::exact(vec![DataType::Utf8, DataType::Utf8], fun.volatility()) } BuiltinScalarFunction::DateTrunc => Signature::exact( vec![ DataType::Utf8, DataType::Timestamp(TimeUnit::Nanosecond, None), ], fun.volatility(), ), BuiltinScalarFunction::DatePart => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Date32]), TypeSignature::Exact(vec![DataType::Utf8, DataType::Date64]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Timestamp(TimeUnit::Second, None), ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Timestamp(TimeUnit::Microsecond, None), ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Timestamp(TimeUnit::Millisecond, None), ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Timestamp(TimeUnit::Nanosecond, None), ]), ], fun.volatility(), ), BuiltinScalarFunction::SplitPart => Signature::one_of( vec![ TypeSignature::Exact(vec![ DataType::Utf8, DataType::Utf8, DataType::Int64, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::Utf8, DataType::Int64, ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::LargeUtf8, DataType::Int64, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::LargeUtf8, DataType::Int64, ]), ], fun.volatility(), ), BuiltinScalarFunction::Strpos | BuiltinScalarFunction::StartsWith => { Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]), TypeSignature::Exact(vec![DataType::Utf8, DataType::LargeUtf8]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::LargeUtf8]), ], fun.volatility(), ) } BuiltinScalarFunction::Substr => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Int64]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Int64]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Int64, DataType::Int64, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::Int64, DataType::Int64, ]), ], fun.volatility(), ), BuiltinScalarFunction::Replace | BuiltinScalarFunction::Translate => { Signature::one_of( vec![TypeSignature::Exact(vec![ DataType::Utf8, DataType::Utf8, DataType::Utf8, ])], fun.volatility(), ) } BuiltinScalarFunction::RegexpReplace => Signature::one_of( vec![ TypeSignature::Exact(vec![ DataType::Utf8, DataType::Utf8, DataType::Utf8, ]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Utf8, DataType::Utf8, DataType::Utf8, ]), ], fun.volatility(), ), BuiltinScalarFunction::NullIf => { Signature::uniform(2, SUPPORTED_NULLIF_TYPES.to_vec(), fun.volatility()) } BuiltinScalarFunction::RegexpMatch => Signature::one_of( vec![ TypeSignature::Exact(vec![DataType::Utf8, DataType::Utf8]), TypeSignature::Exact(vec![DataType::LargeUtf8, DataType::Utf8]), TypeSignature::Exact(vec![ DataType::Utf8, DataType::Utf8, DataType::Utf8, ]), TypeSignature::Exact(vec![ DataType::LargeUtf8, DataType::Utf8, DataType::Utf8, ]), ], fun.volatility(), ), BuiltinScalarFunction::Random => Signature::exact(vec![], fun.volatility()), // math expressions expect 1 argument of type f64 or f32 // priority is given to f64 because e.g. `sqrt(1i32)` is in IR (real numbers) and thus we // return the best approximation for it (in f64). // We accept f32 because in this case it is clear that the best approximation // will be as good as the number of digits in the number _ => Signature::uniform( 1, vec![DataType::Float64, DataType::Float32], fun.volatility(), ), } } /// Physical expression of a scalar function #[derive(Serialize, Deserialize)] pub struct ScalarFunctionExpr { fun: BuiltinScalarFunction, name: String, args: Vec<Arc<dyn PhysicalExpr>>, return_type: DataType, } impl Debug for ScalarFunctionExpr { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("ScalarFunctionExpr") .field("fun", &"<FUNC>") .field("name", &self.name) .field("args", &self.args) .field("return_type", &self.return_type) .finish() } } impl ScalarFunctionExpr { /// Create a new Scalar function pub fn new( name: &str, fun: BuiltinScalarFunction, args: Vec<Arc<dyn PhysicalExpr>>, return_type: &DataType, ) -> Self { Self { fun, name: name.to_owned(), args, return_type: return_type.clone(), } } /// Get the scalar function implementation pub fn fun(&self) -> &BuiltinScalarFunction { &self.fun } /// The name for this expression pub fn name(&self) -> &str { &self.name } /// Input arguments pub fn args(&self) -> &[Arc<dyn PhysicalExpr>] { &self.args } /// Data type produced by this expression pub fn return_type(&self) -> &DataType { &self.return_type } } impl fmt::Display for ScalarFunctionExpr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}({})", self.name, self.args .iter() .map(|e| format!("{}", e)) .collect::<Vec<String>>() .join(", ") ) } } /// null columnar values are implemented as a null array in order to pass batch /// num_rows type NullColumnarValue = ColumnarValue; impl From<&RecordBatch> for NullColumnarValue { fn from(batch: &RecordBatch) -> Self { let num_rows = batch.num_rows(); ColumnarValue::Array(Arc::new(NullArray::new(num_rows))) } } #[typetag::serde(name = "scalar_function_expr")] impl PhysicalExpr for ScalarFunctionExpr { /// Return a reference to Any that can be used for downcasting fn as_any(&self) -> &dyn Any { self } fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { Ok(self.return_type.clone()) } fn nullable(&self, _input_schema: &Schema) -> Result<bool> { Ok(true) } fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { // evaluate the arguments, if there are no arguments we'll instead pass in a null array // indicating the batch size (as a convention) let inputs = match (self.args.len(), self.name.parse::<BuiltinScalarFunction>()) { (0, Ok(scalar_fun)) if scalar_fun.supports_zero_argument() => { vec![NullColumnarValue::from(batch)] } _ => self .args .iter() .map(|e| e.evaluate(batch)) .collect::<Result<Vec<_>>>()?, }; // evaluate the function let fun = self.fun.to_func(&self.args, &batch.schema())?; (fun)(&inputs) } } /// decorates a function to handle [`ScalarValue`]s by converting them to arrays before calling the function /// and vice-versa after evaluation. pub fn make_scalar_function<F>(inner: F) -> ScalarFunctionImplementation where F: Fn(&[ArrayRef]) -> Result<ArrayRef> + Sync + Send + 'static, { Arc::new(move |args: &[ColumnarValue]| { // first, identify if any of the arguments is an Array. If yes, store its `len`, // as any scalar will need to be converted to an array of len `len`. let len = args .iter() .fold(Option::<usize>::None, |acc, arg| match arg { ColumnarValue::Scalar(_) => acc, ColumnarValue::Array(a) => Some(a.len()), }); // to array let args = if let Some(len) = len { args.iter() .map(|arg| arg.clone().into_array(len)) .collect::<Vec<ArrayRef>>() } else { args.iter() .map(|arg| arg.clone().into_array(1)) .collect::<Vec<ArrayRef>>() }; let result = (inner)(&args); // maybe back to scalar if len.is_some() { result.map(ColumnarValue::Array) } else { ScalarValue::try_from_array(&result?, 0).map(ColumnarValue::Scalar) } }) } #[cfg(test)] mod tests { use super::*; use crate::{ error::Result, physical_plan::expressions::{col, lit}, scalar::ScalarValue, }; use arrow::{ array::{ Array, ArrayRef, BinaryArray, BooleanArray, FixedSizeListArray, Float32Array, Float64Array, Int32Array, StringArray, UInt32Array, UInt64Array, }, datatypes::Field, record_batch::RecordBatch, }; /// $FUNC function to test /// $ARGS arguments (vec) to pass to function /// $EXPECTED a Result<Option<$EXPECTED_TYPE>> where Result allows testing errors and Option allows testing Null /// $EXPECTED_TYPE is the expected value type /// $DATA_TYPE is the function to test result type /// $ARRAY_TYPE is the column type after function applied macro_rules! test_function { ($FUNC:ident, $ARGS:expr, $EXPECTED:expr, $EXPECTED_TYPE:ty, $DATA_TYPE: ident, $ARRAY_TYPE:ident) => { // used to provide type annotation let expected: Result<Option<$EXPECTED_TYPE>> = $EXPECTED; let ctx_state = ExecutionContextState::new(); // any type works here: we evaluate against a literal of `value` let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); let columns: Vec<ArrayRef> = vec![Arc::new(Int32Array::from(vec![1]))]; let expr = create_physical_expr(&BuiltinScalarFunction::$FUNC, $ARGS, &schema, &ctx_state)?; // type is correct assert_eq!(expr.data_type(&schema)?, DataType::$DATA_TYPE); let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?; match expected { Ok(expected) => { let result = expr.evaluate(&batch)?; let result = result.into_array(batch.num_rows()); let result = result.as_any().downcast_ref::<$ARRAY_TYPE>().unwrap(); // value is correct match expected { Some(v) => assert_eq!(result.value(0), v), None => assert!(result.is_null(0)), }; } Err(expected_error) => { // evaluate is expected error - cannot use .expect_err() due to Debug not being implemented match expr.evaluate(&batch) { Ok(_) => assert!(false, "expected error"), Err(error) => { assert_eq!(error.to_string(), expected_error.to_string()); } } } }; }; } #[test] fn test_functions() -> Result<()> { test_function!( Ascii, &[lit(ScalarValue::Utf8(Some("x".to_string())))], Ok(Some(120)), i32, Int32, Int32Array ); test_function!( Ascii, &[lit(ScalarValue::Utf8(Some("ésoj".to_string())))], Ok(Some(233)), i32, Int32, Int32Array ); test_function!( Ascii, &[lit(ScalarValue::Utf8(Some("💯".to_string())))], Ok(Some(128175)), i32, Int32, Int32Array ); test_function!( Ascii, &[lit(ScalarValue::Utf8(Some("💯a".to_string())))], Ok(Some(128175)), i32, Int32, Int32Array ); test_function!( Ascii, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(0)), i32, Int32, Int32Array ); test_function!( Ascii, &[lit(ScalarValue::Utf8(None))], Ok(None), i32, Int32, Int32Array ); test_function!( BitLength, &[lit(ScalarValue::Utf8(Some("chars".to_string())))], Ok(Some(40)), i32, Int32, Int32Array ); test_function!( BitLength, &[lit(ScalarValue::Utf8(Some("josé".to_string())))], Ok(Some(40)), i32, Int32, Int32Array ); test_function!( BitLength, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(0)), i32, Int32, Int32Array ); test_function!( Btrim, &[lit(ScalarValue::Utf8(Some(" trim ".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Btrim, &[lit(ScalarValue::Utf8(Some(" trim".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Btrim, &[lit(ScalarValue::Utf8(Some("trim ".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Btrim, &[lit(ScalarValue::Utf8(Some("\n trim \n".to_string())))], Ok(Some("\n trim \n")), &str, Utf8, StringArray ); test_function!( Btrim, &[ lit(ScalarValue::Utf8(Some("xyxtrimyyx".to_string()))), lit(ScalarValue::Utf8(Some("xyz".to_string()))), ], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Btrim, &[ lit(ScalarValue::Utf8(Some("\nxyxtrimyyx\n".to_string()))), lit(ScalarValue::Utf8(Some("xyz\n".to_string()))), ], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Btrim, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("xyz".to_string()))), ], Ok(None), &str, Utf8, StringArray ); test_function!( Btrim, &[ lit(ScalarValue::Utf8(Some("xyxtrimyyx".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( CharacterLength, &[lit(ScalarValue::Utf8(Some("chars".to_string())))], Ok(Some(5)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( CharacterLength, &[lit(ScalarValue::Utf8(Some("josé".to_string())))], Ok(Some(4)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( CharacterLength, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(0)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( CharacterLength, &[lit(ScalarValue::Utf8(None))], Ok(None), i32, Int32, Int32Array ); #[cfg(not(feature = "unicode_expressions"))] test_function!( CharacterLength, &[lit(ScalarValue::Utf8(Some("josé".to_string())))], Err(DataFusionError::Internal( "function character_length requires compilation with feature flag: unicode_expressions.".to_string() )), i32, Int32, Int32Array ); test_function!( Chr, &[lit(ScalarValue::Int64(Some(128175)))], Ok(Some("💯")), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(None))], Ok(None), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(Some(120)))], Ok(Some("x")), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(Some(128175)))], Ok(Some("💯")), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(None))], Ok(None), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(Some(0)))], Err(DataFusionError::Execution( "null character not permitted.".to_string(), )), &str, Utf8, StringArray ); test_function!( Chr, &[lit(ScalarValue::Int64(Some(i64::MAX)))], Err(DataFusionError::Execution( "requested character too large for encoding.".to_string(), )), &str, Utf8, StringArray ); test_function!( Concat, &[ lit(ScalarValue::Utf8(Some("aa".to_string()))), lit(ScalarValue::Utf8(Some("bb".to_string()))), lit(ScalarValue::Utf8(Some("cc".to_string()))), ], Ok(Some("aabbcc")), &str, Utf8, StringArray ); test_function!( Concat, &[ lit(ScalarValue::Utf8(Some("aa".to_string()))), lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("cc".to_string()))), ], Ok(Some("aacc")), &str, Utf8, StringArray ); test_function!( Concat, &[lit(ScalarValue::Utf8(None))], Ok(Some("")), &str, Utf8, StringArray ); test_function!( ConcatWithSeparator, &[ lit(ScalarValue::Utf8(Some("|".to_string()))), lit(ScalarValue::Utf8(Some("aa".to_string()))), lit(ScalarValue::Utf8(Some("bb".to_string()))), lit(ScalarValue::Utf8(Some("cc".to_string()))), ], Ok(Some("aa|bb|cc")), &str, Utf8, StringArray ); test_function!( ConcatWithSeparator, &[ lit(ScalarValue::Utf8(Some("|".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(Some("")), &str, Utf8, StringArray ); test_function!( ConcatWithSeparator, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("aa".to_string()))), lit(ScalarValue::Utf8(Some("bb".to_string()))), lit(ScalarValue::Utf8(Some("cc".to_string()))), ], Ok(None), &str, Utf8, StringArray ); test_function!( ConcatWithSeparator, &[ lit(ScalarValue::Utf8(Some("|".to_string()))), lit(ScalarValue::Utf8(Some("aa".to_string()))), lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("cc".to_string()))), ], Ok(Some("aa|cc")), &str, Utf8, StringArray ); test_function!( Exp, &[lit(ScalarValue::Int32(Some(1)))], Ok(Some((1.0_f64).exp())), f64, Float64, Float64Array ); test_function!( Exp, &[lit(ScalarValue::UInt32(Some(1)))], Ok(Some((1.0_f64).exp())), f64, Float64, Float64Array ); test_function!( Exp, &[lit(ScalarValue::UInt64(Some(1)))], Ok(Some((1.0_f64).exp())), f64, Float64, Float64Array ); test_function!( Exp, &[lit(ScalarValue::Float64(Some(1.0)))], Ok(Some((1.0_f64).exp())), f64, Float64, Float64Array ); test_function!( Exp, &[lit(ScalarValue::Float32(Some(1.0)))], Ok(Some((1.0_f32).exp())), f32, Float32, Float32Array ); test_function!( InitCap, &[lit(ScalarValue::Utf8(Some("hi THOMAS".to_string())))], Ok(Some("Hi Thomas")), &str, Utf8, StringArray ); test_function!( InitCap, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some("")), &str, Utf8, StringArray ); test_function!( InitCap, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some("")), &str, Utf8, StringArray ); test_function!( InitCap, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int8(Some(2))), ], Ok(Some("ab")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(200))), ], Ok(Some("abcde")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(-2))), ], Ok(Some("abc")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(-200))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(2))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some("joséé")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(-3))), ], Ok(Some("joséé")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Left, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int8(Some(2))), ], Err(DataFusionError::Internal( "function left requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some(" josé")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some(" hi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(5))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(Some("xyxhi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(21))), lit(ScalarValue::Utf8(Some("abcdef".to_string()))), ], Ok(Some("abcdefabcdefabcdefahi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some(" ".to_string()))), ], Ok(Some(" hi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("".to_string()))), ], Ok(Some("hi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(None)), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(10))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(Some("xyxyxyjosé")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(10))), lit(ScalarValue::Utf8(Some("éñ".to_string()))), ], Ok(Some("éñéñéñjosé")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Lpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Err(DataFusionError::Internal( "function lpad requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(Some(" trim".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(Some(" trim ".to_string())))], Ok(Some("trim ")), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(Some("trim ".to_string())))], Ok(Some("trim ")), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(Some("trim".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(Some("\n trim ".to_string())))], Ok(Some("\n trim ")), &str, Utf8, StringArray ); test_function!( Ltrim, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "crypto_expressions")] test_function!( MD5, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Ok(Some("34b7da764b21d298ef307d04d8152dc5")), &str, Utf8, StringArray ); #[cfg(feature = "crypto_expressions")] test_function!( MD5, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some("d41d8cd98f00b204e9800998ecf8427e")), &str, Utf8, StringArray ); #[cfg(feature = "crypto_expressions")] test_function!( MD5, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); #[cfg(not(feature = "crypto_expressions"))] test_function!( MD5, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Err(DataFusionError::Internal( "function md5 requires compilation with feature flag: crypto_expressions.".to_string() )), &str, Utf8, StringArray ); test_function!( OctetLength, &[lit(ScalarValue::Utf8(Some("chars".to_string())))], Ok(Some(5)), i32, Int32, Int32Array ); test_function!( OctetLength, &[lit(ScalarValue::Utf8(Some("josé".to_string())))], Ok(Some(5)), i32, Int32, Int32Array ); test_function!( OctetLength, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(0)), i32, Int32, Int32Array ); test_function!( OctetLength, &[lit(ScalarValue::Utf8(None))], Ok(None), i32, Int32, Int32Array ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("Thomas".to_string()))), lit(ScalarValue::Utf8(Some(".[mN]a.".to_string()))), lit(ScalarValue::Utf8(Some("M".to_string()))), ], Ok(Some("ThM")), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b..".to_string()))), lit(ScalarValue::Utf8(Some("X".to_string()))), ], Ok(Some("fooXbaz")), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b..".to_string()))), lit(ScalarValue::Utf8(Some("X".to_string()))), lit(ScalarValue::Utf8(Some("g".to_string()))), ], Ok(Some("fooXX")), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b(..)".to_string()))), lit(ScalarValue::Utf8(Some("X\\1Y".to_string()))), lit(ScalarValue::Utf8(Some("g".to_string()))), ], Ok(Some("fooXarYXazY")), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("b(..)".to_string()))), lit(ScalarValue::Utf8(Some("X\\1Y".to_string()))), lit(ScalarValue::Utf8(Some("g".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("X\\1Y".to_string()))), lit(ScalarValue::Utf8(Some("g".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b(..)".to_string()))), lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("g".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b(..)".to_string()))), lit(ScalarValue::Utf8(Some("X\\1Y".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("ABCabcABC".to_string()))), lit(ScalarValue::Utf8(Some("(abc)".to_string()))), lit(ScalarValue::Utf8(Some("X".to_string()))), lit(ScalarValue::Utf8(Some("gi".to_string()))), ], Ok(Some("XXX")), &str, Utf8, StringArray ); #[cfg(feature = "regex_expressions")] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("ABCabcABC".to_string()))), lit(ScalarValue::Utf8(Some("(abc)".to_string()))), lit(ScalarValue::Utf8(Some("X".to_string()))), lit(ScalarValue::Utf8(Some("i".to_string()))), ], Ok(Some("XabcABC")), &str, Utf8, StringArray ); #[cfg(not(feature = "regex_expressions"))] test_function!( RegexpReplace, &[ lit(ScalarValue::Utf8(Some("foobarbaz".to_string()))), lit(ScalarValue::Utf8(Some("b..".to_string()))), lit(ScalarValue::Utf8(Some("X".to_string()))), ], Err(DataFusionError::Internal( "function regexp_replace requires compilation with feature flag: regex_expressions.".to_string() )), &str, Utf8, StringArray ); test_function!( Repeat, &[ lit(ScalarValue::Utf8(Some("Pg".to_string()))), lit(ScalarValue::Int64(Some(4))), ], Ok(Some("PgPgPgPg")), &str, Utf8, StringArray ); test_function!( Repeat, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(4))), ], Ok(None), &str, Utf8, StringArray ); test_function!( Repeat, &[ lit(ScalarValue::Utf8(Some("Pg".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Reverse, &[lit(ScalarValue::Utf8(Some("abcde".to_string())))], Ok(Some("edcba")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Reverse, &[lit(ScalarValue::Utf8(Some("loẅks".to_string())))], Ok(Some("skẅol")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Reverse, &[lit(ScalarValue::Utf8(Some("loẅks".to_string())))], Ok(Some("skẅol")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Reverse, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Reverse, &[lit(ScalarValue::Utf8(Some("abcde".to_string())))], Err(DataFusionError::Internal( "function reverse requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int8(Some(2))), ], Ok(Some("de")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(200))), ], Ok(Some("abcde")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(-2))), ], Ok(Some("cde")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(-200))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(2))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some("éésoj")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(-3))), ], Ok(Some("éésoj")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Right, &[ lit(ScalarValue::Utf8(Some("abcde".to_string()))), lit(ScalarValue::Int8(Some(2))), ], Err(DataFusionError::Internal( "function right requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some("josé ")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some("hi ")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(5))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(Some("hixyx")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(21))), lit(ScalarValue::Utf8(Some("abcdef".to_string()))), ], Ok(Some("hiabcdefabcdefabcdefa")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some(" ".to_string()))), ], Ok(Some("hi ")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("".to_string()))), ], Ok(Some("hi")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(None)), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("hi".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Utf8(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(10))), lit(ScalarValue::Utf8(Some("xy".to_string()))), ], Ok(Some("joséxyxyxy")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(10))), lit(ScalarValue::Utf8(Some("éñ".to_string()))), ], Ok(Some("josééñéñéñ")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Rpad, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Err(DataFusionError::Internal( "function rpad requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(Some("trim ".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(Some(" trim ".to_string())))], Ok(Some(" trim")), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(Some(" trim \n".to_string())))], Ok(Some(" trim \n")), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(Some(" trim".to_string())))], Ok(Some(" trim")), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(Some("trim".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Rtrim, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA224, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Ok(Some(&[ 11u8, 246u8, 203u8, 98u8, 100u8, 156u8, 66u8, 169u8, 174u8, 56u8, 118u8, 171u8, 111u8, 109u8, 146u8, 173u8, 54u8, 203u8, 84u8, 20u8, 228u8, 149u8, 248u8, 135u8, 50u8, 146u8, 190u8, 77u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA224, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(&[ 209u8, 74u8, 2u8, 140u8, 42u8, 58u8, 43u8, 201u8, 71u8, 97u8, 2u8, 187u8, 40u8, 130u8, 52u8, 196u8, 21u8, 162u8, 176u8, 31u8, 130u8, 142u8, 166u8, 42u8, 197u8, 179u8, 228u8, 47u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA224, &[lit(ScalarValue::Utf8(None))], Ok(None), &[u8], Binary, BinaryArray ); #[cfg(not(feature = "crypto_expressions"))] test_function!( SHA224, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Err(DataFusionError::Internal( "function sha224 requires compilation with feature flag: crypto_expressions.".to_string() )), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA256, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Ok(Some(&[ 225u8, 96u8, 143u8, 117u8, 197u8, 215u8, 129u8, 63u8, 61u8, 64u8, 49u8, 203u8, 48u8, 191u8, 183u8, 134u8, 80u8, 125u8, 152u8, 19u8, 117u8, 56u8, 255u8, 142u8, 18u8, 138u8, 111u8, 247u8, 78u8, 132u8, 230u8, 67u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA256, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(&[ 227u8, 176u8, 196u8, 66u8, 152u8, 252u8, 28u8, 20u8, 154u8, 251u8, 244u8, 200u8, 153u8, 111u8, 185u8, 36u8, 39u8, 174u8, 65u8, 228u8, 100u8, 155u8, 147u8, 76u8, 164u8, 149u8, 153u8, 27u8, 120u8, 82u8, 184u8, 85u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA256, &[lit(ScalarValue::Utf8(None))], Ok(None), &[u8], Binary, BinaryArray ); #[cfg(not(feature = "crypto_expressions"))] test_function!( SHA256, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Err(DataFusionError::Internal( "function sha256 requires compilation with feature flag: crypto_expressions.".to_string() )), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA384, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Ok(Some(&[ 9u8, 111u8, 91u8, 104u8, 170u8, 119u8, 132u8, 142u8, 79u8, 223u8, 92u8, 28u8, 11u8, 53u8, 13u8, 226u8, 219u8, 250u8, 214u8, 15u8, 253u8, 124u8, 37u8, 217u8, 234u8, 7u8, 198u8, 193u8, 155u8, 138u8, 77u8, 85u8, 169u8, 24u8, 126u8, 177u8, 23u8, 197u8, 87u8, 136u8, 63u8, 88u8, 193u8, 109u8, 250u8, 195u8, 227u8, 67u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA384, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(&[ 56u8, 176u8, 96u8, 167u8, 81u8, 172u8, 150u8, 56u8, 76u8, 217u8, 50u8, 126u8, 177u8, 177u8, 227u8, 106u8, 33u8, 253u8, 183u8, 17u8, 20u8, 190u8, 7u8, 67u8, 76u8, 12u8, 199u8, 191u8, 99u8, 246u8, 225u8, 218u8, 39u8, 78u8, 222u8, 191u8, 231u8, 111u8, 101u8, 251u8, 213u8, 26u8, 210u8, 241u8, 72u8, 152u8, 185u8, 91u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA384, &[lit(ScalarValue::Utf8(None))], Ok(None), &[u8], Binary, BinaryArray ); #[cfg(not(feature = "crypto_expressions"))] test_function!( SHA384, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Err(DataFusionError::Internal( "function sha384 requires compilation with feature flag: crypto_expressions.".to_string() )), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA512, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Ok(Some(&[ 110u8, 27u8, 155u8, 63u8, 232u8, 64u8, 104u8, 14u8, 55u8, 5u8, 31u8, 122u8, 213u8, 233u8, 89u8, 214u8, 243u8, 154u8, 208u8, 248u8, 136u8, 93u8, 133u8, 81u8, 102u8, 245u8, 92u8, 101u8, 148u8, 105u8, 211u8, 200u8, 183u8, 129u8, 24u8, 196u8, 74u8, 42u8, 73u8, 199u8, 45u8, 219u8, 72u8, 28u8, 214u8, 216u8, 115u8, 16u8, 52u8, 225u8, 28u8, 192u8, 48u8, 7u8, 11u8, 168u8, 67u8, 169u8, 11u8, 52u8, 149u8, 203u8, 141u8, 62u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA512, &[lit(ScalarValue::Utf8(Some("".to_string())))], Ok(Some(&[ 207u8, 131u8, 225u8, 53u8, 126u8, 239u8, 184u8, 189u8, 241u8, 84u8, 40u8, 80u8, 214u8, 109u8, 128u8, 7u8, 214u8, 32u8, 228u8, 5u8, 11u8, 87u8, 21u8, 220u8, 131u8, 244u8, 169u8, 33u8, 211u8, 108u8, 233u8, 206u8, 71u8, 208u8, 209u8, 60u8, 93u8, 133u8, 242u8, 176u8, 255u8, 131u8, 24u8, 210u8, 135u8, 126u8, 236u8, 47u8, 99u8, 185u8, 49u8, 189u8, 71u8, 65u8, 122u8, 129u8, 165u8, 56u8, 50u8, 122u8, 249u8, 39u8, 218u8, 62u8 ])), &[u8], Binary, BinaryArray ); #[cfg(feature = "crypto_expressions")] test_function!( SHA512, &[lit(ScalarValue::Utf8(None))], Ok(None), &[u8], Binary, BinaryArray ); #[cfg(not(feature = "crypto_expressions"))] test_function!( SHA512, &[lit(ScalarValue::Utf8(Some("tom".to_string())))], Err(DataFusionError::Internal( "function sha512 requires compilation with feature flag: crypto_expressions.".to_string() )), &[u8], Binary, BinaryArray ); test_function!( SplitPart, &[ lit(ScalarValue::Utf8(Some("abc~@~def~@~ghi".to_string()))), lit(ScalarValue::Utf8(Some("~@~".to_string()))), lit(ScalarValue::Int64(Some(2))), ], Ok(Some("def")), &str, Utf8, StringArray ); test_function!( SplitPart, &[ lit(ScalarValue::Utf8(Some("abc~@~def~@~ghi".to_string()))), lit(ScalarValue::Utf8(Some("~@~".to_string()))), lit(ScalarValue::Int64(Some(20))), ], Ok(Some("")), &str, Utf8, StringArray ); test_function!( SplitPart, &[ lit(ScalarValue::Utf8(Some("abc~@~def~@~ghi".to_string()))), lit(ScalarValue::Utf8(Some("~@~".to_string()))), lit(ScalarValue::Int64(Some(-1))), ], Err(DataFusionError::Execution( "field position must be greater than zero".to_string(), )), &str, Utf8, StringArray ); test_function!( StartsWith, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Utf8(Some("alph".to_string()))), ], Ok(Some(true)), bool, Boolean, BooleanArray ); test_function!( StartsWith, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Utf8(Some("blph".to_string()))), ], Ok(Some(false)), bool, Boolean, BooleanArray ); test_function!( StartsWith, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("alph".to_string()))), ], Ok(None), bool, Boolean, BooleanArray ); test_function!( StartsWith, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(None), bool, Boolean, BooleanArray ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("abc".to_string()))), lit(ScalarValue::Utf8(Some("c".to_string()))), ], Ok(Some(3)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("josé".to_string()))), lit(ScalarValue::Utf8(Some("é".to_string()))), ], Ok(Some(4)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Utf8(Some("so".to_string()))), ], Ok(Some(6)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Utf8(Some("abc".to_string()))), ], Ok(Some(0)), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("abc".to_string()))), ], Ok(None), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(None), i32, Int32, Int32Array ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Strpos, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Utf8(None)), ], Err(DataFusionError::Internal( "function strpos requires compilation with feature flag: unicode_expressions.".to_string() )), i32, Int32, Int32Array ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Ok(Some("alphabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(5))), ], Ok(Some("ésoj")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(1))), ], Ok(Some("alphabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(2))), ], Ok(Some("lphabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(3))), ], Ok(Some("phabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(-3))), ], Ok(Some("alphabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(30))), ], Ok(Some("")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(3))), lit(ScalarValue::Int64(Some(2))), ], Ok(Some("ph")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(3))), lit(ScalarValue::Int64(Some(20))), ], Ok(Some("phabet")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(None)), lit(ScalarValue::Int64(Some(20))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(3))), lit(ScalarValue::Int64(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(1))), lit(ScalarValue::Int64(Some(-1))), ], Err(DataFusionError::Execution( "negative substring length not allowed".to_string(), )), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("joséésoj".to_string()))), lit(ScalarValue::Int64(Some(5))), lit(ScalarValue::Int64(Some(2))), ], Ok(Some("és")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Substr, &[ lit(ScalarValue::Utf8(Some("alphabet".to_string()))), lit(ScalarValue::Int64(Some(0))), ], Err(DataFusionError::Internal( "function substr requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Translate, &[ lit(ScalarValue::Utf8(Some("12345".to_string()))), lit(ScalarValue::Utf8(Some("143".to_string()))), lit(ScalarValue::Utf8(Some("ax".to_string()))), ], Ok(Some("a2x5")), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Translate, &[ lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("143".to_string()))), lit(ScalarValue::Utf8(Some("ax".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Translate, &[ lit(ScalarValue::Utf8(Some("12345".to_string()))), lit(ScalarValue::Utf8(None)), lit(ScalarValue::Utf8(Some("ax".to_string()))), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Translate, &[ lit(ScalarValue::Utf8(Some("12345".to_string()))), lit(ScalarValue::Utf8(Some("143".to_string()))), lit(ScalarValue::Utf8(None)), ], Ok(None), &str, Utf8, StringArray ); #[cfg(feature = "unicode_expressions")] test_function!( Translate, &[ lit(ScalarValue::Utf8(Some("é2íñ5".to_string()))), lit(ScalarValue::Utf8(Some("éñí".to_string()))), lit(ScalarValue::Utf8(Some("óü".to_string()))), ], Ok(Some("ó2ü5")), &str, Utf8, StringArray ); #[cfg(not(feature = "unicode_expressions"))] test_function!( Translate, &[ lit(ScalarValue::Utf8(Some("12345".to_string()))), lit(ScalarValue::Utf8(Some("143".to_string()))), lit(ScalarValue::Utf8(Some("ax".to_string()))), ], Err(DataFusionError::Internal( "function translate requires compilation with feature flag: unicode_expressions.".to_string() )), &str, Utf8, StringArray ); test_function!( Trim, &[lit(ScalarValue::Utf8(Some(" trim ".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Trim, &[lit(ScalarValue::Utf8(Some("trim ".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Trim, &[lit(ScalarValue::Utf8(Some(" trim".to_string())))], Ok(Some("trim")), &str, Utf8, StringArray ); test_function!( Trim, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); test_function!( Upper, &[lit(ScalarValue::Utf8(Some("upper".to_string())))], Ok(Some("UPPER")), &str, Utf8, StringArray ); test_function!( Upper, &[lit(ScalarValue::Utf8(Some("UPPER".to_string())))], Ok(Some("UPPER")), &str, Utf8, StringArray ); test_function!( Upper, &[lit(ScalarValue::Utf8(None))], Ok(None), &str, Utf8, StringArray ); Ok(()) } #[test] fn test_empty_arguments_error() -> Result<()> { let ctx_state = ExecutionContextState::new(); let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); // pick some arbitrary functions to test let funs = [ BuiltinScalarFunction::Concat, BuiltinScalarFunction::ToTimestamp, BuiltinScalarFunction::Abs, BuiltinScalarFunction::Repeat, ]; for fun in funs.iter() { let expr = create_physical_expr(fun, &[], &schema, &ctx_state); match expr { Ok(..) => { return Err(DataFusionError::Plan(format!( "Builtin scalar function {} does not support empty arguments", fun ))); } Err(DataFusionError::Internal(err)) => { if err != format!( "Builtin scalar function {} does not support empty arguments", fun ) { return Err(DataFusionError::Internal(format!( "Builtin scalar function {} didn't got the right error message with empty arguments", fun))); } } Err(..) => { return Err(DataFusionError::Internal(format!( "Builtin scalar function {} didn't got the right error with empty arguments", fun))); } } } Ok(()) } #[test] fn test_empty_arguments() -> Result<()> { let ctx_state = ExecutionContextState::new(); let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); let funs = [BuiltinScalarFunction::Now, BuiltinScalarFunction::Random]; for fun in funs.iter() { create_physical_expr(fun, &[], &schema, &ctx_state)?; } Ok(()) } fn generic_test_array( value1: ArrayRef, value2: ArrayRef, expected_type: DataType, expected: &str, ) -> Result<()> { // any type works here: we evaluate against a literal of `value` let schema = Schema::new(vec![ Field::new("a", value1.data_type().clone(), false), Field::new("b", value2.data_type().clone(), false), ]); let columns: Vec<ArrayRef> = vec![value1, value2]; let ctx_state = ExecutionContextState::new(); let expr = create_physical_expr( &BuiltinScalarFunction::Array, &[col("a", &schema)?, col("b", &schema)?], &schema, &ctx_state, )?; // type is correct assert_eq!( expr.data_type(&schema)?, // type equals to a common coercion DataType::FixedSizeList(Box::new(Field::new("item", expected_type, true)), 2) ); // evaluate works let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?; let result = expr.evaluate(&batch)?.into_array(batch.num_rows()); // downcast works let result = result .as_any() .downcast_ref::<FixedSizeListArray>() .unwrap(); // value is correct assert_eq!(format!("{:?}", result.value(0)), expected); Ok(()) } #[test] fn test_array() -> Result<()> { generic_test_array( Arc::new(StringArray::from(vec!["aa"])), Arc::new(StringArray::from(vec!["bb"])), DataType::Utf8, "StringArray\n[\n \"aa\",\n \"bb\",\n]", )?; // different types, to validate that casting happens generic_test_array( Arc::new(UInt32Array::from(vec![1u32])), Arc::new(UInt64Array::from(vec![1u64])), DataType::UInt64, "PrimitiveArray<UInt64>\n[\n 1,\n 1,\n]", )?; // different types (another order), to validate that casting happens generic_test_array( Arc::new(UInt64Array::from(vec![1u64])), Arc::new(UInt32Array::from(vec![1u32])), DataType::UInt64, "PrimitiveArray<UInt64>\n[\n 1,\n 1,\n]", ) } #[test] #[cfg(feature = "regex_expressions")] fn test_regexp_match() -> Result<()> { use arrow::array::ListArray; let schema = Schema::new(vec![Field::new("a", DataType::Utf8, false)]); let ctx_state = ExecutionContextState::new(); let col_value: ArrayRef = Arc::new(StringArray::from(vec!["aaa-555"])); let pattern = lit(ScalarValue::Utf8(Some(r".*-(\d*)".to_string()))); let columns: Vec<ArrayRef> = vec![col_value]; let expr = create_physical_expr( &BuiltinScalarFunction::RegexpMatch, &[col("a", &schema)?, pattern], &schema, &ctx_state, )?; // type is correct assert_eq!( expr.data_type(&schema)?, DataType::List(Box::new(Field::new("item", DataType::Utf8, true))) ); // evaluate works let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?; let result = expr.evaluate(&batch)?.into_array(batch.num_rows()); // downcast works let result = result.as_any().downcast_ref::<ListArray>().unwrap(); let first_row = result.value(0); let first_row = first_row.as_any().downcast_ref::<StringArray>().unwrap(); // value is correct let expected = "555".to_string(); assert_eq!(first_row.value(0), expected); Ok(()) } #[test] #[cfg(feature = "regex_expressions")] fn test_regexp_match_all_literals() -> Result<()> { use arrow::array::ListArray; let schema = Schema::new(vec![Field::new("a", DataType::Int32, false)]); let ctx_state = ExecutionContextState::new(); let col_value = lit(ScalarValue::Utf8(Some("aaa-555".to_string()))); let pattern = lit(ScalarValue::Utf8(Some(r".*-(\d*)".to_string()))); let columns: Vec<ArrayRef> = vec![Arc::new(Int32Array::from(vec![1]))]; let expr = create_physical_expr( &BuiltinScalarFunction::RegexpMatch, &[col_value, pattern], &schema, &ctx_state, )?; // type is correct assert_eq!( expr.data_type(&schema)?, DataType::List(Box::new(Field::new("item", DataType::Utf8, true))) ); // evaluate works let batch = RecordBatch::try_new(Arc::new(schema.clone()), columns)?; let result = expr.evaluate(&batch)?.into_array(batch.num_rows()); // downcast works let result = result.as_any().downcast_ref::<ListArray>().unwrap(); let first_row = result.value(0); let first_row = first_row.as_any().downcast_ref::<StringArray>().unwrap(); // value is correct let expected = "555".to_string(); assert_eq!(first_row.value(0), expected); Ok(()) } }
34.611111
253
0.498322
ff52b5ca5dbf51881204c172b79f7b62b044158b
9,720
use super::*; use serde::{Deserialize, Serialize}; use std::{convert::TryFrom, fmt::Debug}; use std::str::FromStr; use strum_macros::{EnumString, ToString}; /// Filter Objects based on one of the following criteria /// # Example: /// // Get all nexuses from the node `node_id` /// let nexuses = /// MessageBus::get_nexuses(Filter::Node(node_id)).await.unwrap(); #[derive(Serialize, Deserialize, Debug, Clone, strum_macros::ToString)] // likely this ToString does not do the right thing... pub enum Filter { /// All objects None, /// Filter by Node id Node(NodeId), /// Pool filters /// /// Filter by Pool id Pool(PoolId), /// Filter by Node and Pool id NodePool(NodeId, PoolId), /// Filter by Node and Replica id NodeReplica(NodeId, ReplicaId), /// Filter by Node, Pool and Replica id NodePoolReplica(NodeId, PoolId, ReplicaId), /// Filter by Pool and Replica id PoolReplica(PoolId, ReplicaId), /// Filter by Replica id Replica(ReplicaId), /// Volume filters /// /// Filter by Node and Nexus NodeNexus(NodeId, NexusId), /// Filter by Nexus Nexus(NexusId), /// Filter by Volume Volume(VolumeId), } impl Default for Filter { fn default() -> Self { Self::None } } #[macro_export] macro_rules! bus_impl_string_id_inner { ($Name:ident, $Doc:literal) => { #[doc = $Doc] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq, Hash)] pub struct $Name(String); impl std::fmt::Display for $Name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl $Name { /// Build Self from a string trait id pub fn as_str<'a>(&'a self) -> &'a str { self.0.as_str() } } impl From<&str> for $Name { fn from(id: &str) -> Self { $Name::from(id) } } impl From<String> for $Name { fn from(id: String) -> Self { $Name::from(id.as_str()) } } impl From<&$Name> for $Name { fn from(id: &$Name) -> $Name { id.clone() } } impl From<$Name> for String { fn from(id: $Name) -> String { id.to_string() } } impl From<&$Name> for String { fn from(id: &$Name) -> String { id.to_string() } } }; } #[macro_export] macro_rules! bus_impl_string_id { ($Name:ident, $Doc:literal) => { bus_impl_string_id_inner!($Name, $Doc); impl Default for $Name { /// Generates new blank identifier fn default() -> Self { $Name(uuid::Uuid::default().to_string()) } } impl $Name { /// Build Self from a string trait id pub fn from<T: Into<String>>(id: T) -> Self { $Name(id.into()) } /// Generates new random identifier pub fn new() -> Self { $Name(uuid::Uuid::new_v4().to_string()) } } }; } #[macro_export] macro_rules! bus_impl_string_uuid_inner { ($Name:ident, $Doc:literal) => { #[doc = $Doc] #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub struct $Name(uuid::Uuid, String); impl Serialize for $Name { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(self.as_str()) } } impl<'de> serde::Deserialize<'de> for $Name { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let uuid = uuid::Uuid::deserialize(deserializer)?; Ok($Name(uuid, uuid.to_string())) } } impl std::ops::Deref for $Name { type Target = uuid::Uuid; fn deref(&self) -> &Self::Target { &self.0 } } impl std::fmt::Display for $Name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } impl $Name { /// Build Self from a string trait id pub fn as_str<'a>(&'a self) -> &'a str { self.1.as_str() } } impl From<&$Name> for $Name { fn from(id: &$Name) -> $Name { id.clone() } } impl From<$Name> for String { fn from(id: $Name) -> String { id.to_string() } } impl From<&$Name> for String { fn from(id: &$Name) -> String { id.to_string() } } impl From<&uuid::Uuid> for $Name { fn from(uuid: &uuid::Uuid) -> $Name { $Name(uuid.clone(), uuid.to_string()) } } impl From<uuid::Uuid> for $Name { fn from(uuid: uuid::Uuid) -> $Name { $Name::from(&uuid) } } impl From<$Name> for uuid::Uuid { fn from(src: $Name) -> uuid::Uuid { src.0 } } impl From<&$Name> for uuid::Uuid { fn from(src: &$Name) -> uuid::Uuid { src.0.clone() } } impl std::convert::TryFrom<&str> for $Name { type Error = uuid::Error; fn try_from(value: &str) -> Result<Self, Self::Error> { let uuid: uuid::Uuid = std::str::FromStr::from_str(value)?; Ok($Name::from(uuid)) } } impl std::convert::TryFrom<String> for $Name { type Error = uuid::Error; fn try_from(value: String) -> Result<Self, Self::Error> { let uuid: uuid::Uuid = std::str::FromStr::from_str(&value)?; Ok($Name::from(uuid)) } } }; } #[macro_export] macro_rules! bus_impl_string_uuid { ($Name:ident, $Doc:literal) => { bus_impl_string_uuid_inner!($Name, $Doc); impl Default for $Name { /// Generates new blank identifier fn default() -> Self { let uuid = uuid::Uuid::default(); $Name(uuid.clone(), uuid.to_string()) } } impl $Name { /// Generates new random identifier pub fn new() -> Self { let uuid = uuid::Uuid::new_v4(); $Name(uuid.clone(), uuid.to_string()) } } }; } #[macro_export] macro_rules! bus_impl_string_id_percent_decoding { ($Name:ident, $Doc:literal) => { bus_impl_string_id_inner!($Name, $Doc); impl Default for $Name { fn default() -> Self { $Name("".to_string()) } } impl $Name { /// Build Self from a string trait id pub fn from<T: Into<String>>(id: T) -> Self { let src: String = id.into(); let decoded_src = percent_decode_str(src.clone().as_str()) .decode_utf8() .unwrap_or(src.into()) .to_string(); $Name(decoded_src) } } }; } /// Indicates what protocol the bdev is shared as #[derive(Serialize, Deserialize, Debug, Copy, Clone, EnumString, ToString, Eq, PartialEq)] #[strum(serialize_all = "camelCase")] #[serde(rename_all = "camelCase")] pub enum Protocol { /// not shared by any of the variants None = 0, /// shared as NVMe-oF TCP Nvmf = 1, /// shared as iSCSI Iscsi = 2, /// shared as NBD Nbd = 3, } impl Protocol { /// Is the protocol set to be shared pub fn shared(&self) -> bool { self != &Self::None } } impl Default for Protocol { fn default() -> Self { Self::None } } impl From<i32> for Protocol { fn from(src: i32) -> Self { match src { 0 => Self::None, 1 => Self::Nvmf, 2 => Self::Iscsi, _ => Self::None, } } } /// Convert a device URI to a share Protocol /// Uses the URI scheme to determine the protocol /// Temporary WA until the share is added to the io-engine RPC impl TryFrom<&str> for Protocol { type Error = String; fn try_from(value: &str) -> Result<Self, Self::Error> { Ok(if value.is_empty() { Protocol::None } else { match url::Url::from_str(value) { Ok(url) => match url.scheme() { "nvmf" => Self::Nvmf, "iscsi" => Self::Iscsi, "nbd" => Self::Nbd, other => return Err(format!("Invalid nexus protocol: {}", other)), }, Err(error) => { tracing::error!("error parsing uri's ({}) protocol: {}", value, error); return Err(error.to_string()); } } }) } } impl From<Protocol> for models::Protocol { fn from(src: Protocol) -> Self { match src { Protocol::None => Self::None, Protocol::Nvmf => Self::Nvmf, Protocol::Iscsi => Self::Iscsi, Protocol::Nbd => Self::Nbd, } } } /// Liveness Probe #[derive(Serialize, Deserialize, Debug, Default, Clone)] pub struct Liveness {}
28.338192
126
0.480041
483514cece68eee30ae493c2afcc4b0b33c85de1
8,074
// Copyright 2019 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT // http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD // https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied, // modified, or distributed except according to those terms. Please review the Licences for the // specific language governing permissions and limitations relating to use of the SAFE Network // Software. //! Basic chat like example that demonstrates how to connect with peers and exchange data. use bytes::Bytes; use crossbeam_channel as mpmc; use quic_p2p::{Builder, Config, Event, Peer, QuicP2p}; use rand::{self, RngCore}; use rustyline::config::Configurer; use rustyline::error::ReadlineError; use rustyline::Editor; use serde_json; use std::sync::{Arc, Mutex}; use std::thread::{self, JoinHandle}; use structopt::StructOpt; use unwrap::unwrap; struct PeerList { peers: Vec<Peer>, } impl PeerList { fn new() -> Self { Self { peers: Vec::new() } } fn insert_from_json(&mut self, peer_json: &str) -> Result<(), &str> { serde_json::from_str(peer_json) .map(|v| self.insert(v)) .map_err(|_| "Error parsing JSON") } fn insert(&mut self, peer: Peer) { if !self.peers.contains(&peer) { self.peers.push(peer) } } fn remove(&mut self, peer_idx: usize) -> Result<Peer, &str> { if peer_idx < self.peers.len() { Ok(self.peers.remove(peer_idx)) } else { Err("Index out of bounds") } } fn get(&self, peer_idx: usize) -> Option<&Peer> { self.peers.get(peer_idx) } fn list(&self) { for (idx, peer) in self.peers.iter().enumerate() { println!("{:3}: {}", idx, peer.peer_addr()); } } } /// This chat app connects two machines directly without intermediate servers and allows /// to exchange messages securely. All the messages are end to end encrypted. #[derive(Debug, StructOpt)] struct CliArgs { #[structopt(flatten)] quic_p2p_opts: Config, } fn main() { let CliArgs { quic_p2p_opts } = CliArgs::from_args(); let (ev_tx, ev_rx) = mpmc::unbounded(); let mut qp2p = unwrap!(Builder::new(ev_tx).with_config(quic_p2p_opts).build()); print_logo(); println!("Type 'help' to get started."); let peerlist = Arc::new(Mutex::new(PeerList::new())); let rx_thread = handle_qp2p_events(ev_rx, peerlist.clone()); let mut rl = Editor::<()>::new(); rl.set_auto_add_history(true); 'outer: loop { match rl.readline(">> ") { Ok(line) => { let mut args = line.trim().split_whitespace(); let cmd = if let Some(cmd) = args.next() { cmd } else { continue 'outer; }; let mut peerlist = peerlist.lock().unwrap(); let result = match cmd { "ourinfo" => { print_ourinfo(&mut qp2p); Ok(()) } "addpeer" => peerlist .insert_from_json(&args.collect::<Vec<_>>().join(" ")) .and(Ok(())), "listpeers" => { peerlist.list(); Ok(()) } "delpeer" => args .next() .ok_or("Missing index argument") .and_then(|idx| idx.parse().or(Err("Invalid index argument"))) .and_then(|idx| peerlist.remove(idx)) .and(Ok(())), "send" => on_cmd_send(&mut args, &peerlist, &mut qp2p), "sendrand" => on_cmd_send_rand(&mut args, &peerlist, &mut qp2p), "quit" | "exit" => break 'outer, "help" => { println!( "Commands: ourinfo, addpeer, listpeers, delpeer, send, quit, exit, help" ); Ok(()) } _ => Err("Unknown command"), }; if let Err(msg) = result { println!("Error: {}", msg); } } Err(ReadlineError::Eof) | Err(ReadlineError::Interrupted) => break 'outer, Err(e) => { println!("Error reading line: {}", e); } } } drop(qp2p); rx_thread.join().unwrap(); } fn on_cmd_send<'a>( mut args: impl Iterator<Item = &'a str>, peer_list: &PeerList, qp2p: &mut QuicP2p, ) -> Result<(), &'static str> { args.next() .ok_or("Missing index argument") .and_then(|idx| idx.parse().or(Err("Invalid index argument"))) .and_then(|idx| peer_list.get(idx).ok_or("Index out of bounds")) .map(|peer| { let msg = Bytes::from(args.collect::<Vec<_>>().join(" ").as_bytes()); // TODO: handle tokens properly. Currently just hardcoding to 0 in example qp2p.send(peer.clone(), msg, 0); }) } /// Sends random data of given size to given peer. /// Usage: "sendrand <peer_index> <bytes> fn on_cmd_send_rand<'a>( mut args: impl Iterator<Item = &'a str>, peer_list: &PeerList, qp2p: &mut QuicP2p, ) -> Result<(), &'static str> { args.next() .ok_or("Missing index argument") .and_then(|idx| idx.parse().or(Err("Invalid index argument"))) .and_then(|idx| peer_list.get(idx).ok_or("Index out of bounds")) .and_then(|peer| { args.next() .ok_or("Missing bytes count") .and_then(|bytes| bytes.parse().or(Err("Invalid bytes count argument"))) .map(|bytes_to_send| (peer, bytes_to_send)) }) .map(|(peer, bytes_to_send)| { let data = Bytes::from(random_vec(bytes_to_send)); // TODO: handle tokens properly. Currently just hardcoding to 0 in example qp2p.send(peer.clone(), data, 0) }) } fn handle_qp2p_events( event_rx: mpmc::Receiver<Event>, peer_list: Arc<Mutex<PeerList>>, ) -> JoinHandle<()> { thread::spawn(move || { for event in event_rx.iter() { match event { Event::ConnectedTo { peer } => unwrap!(peer_list.lock()).insert(peer), Event::NewMessage { peer_addr, msg } => { if msg.len() > 512 { println!("[{}] received bytes: {}", peer_addr, msg.len()); } else { println!( "[{}] {}", peer_addr, unwrap!(String::from_utf8(msg.to_vec())) ); } } event => println!("Unexpected Crust event: {:?}", event), } } }) } fn print_ourinfo(qp2p: &mut QuicP2p) { let ourinfo: Peer = match qp2p.our_connection_info() { Ok(ourinfo) => ourinfo.into(), Err(e) => { println!("Error getting ourinfo: {}", e); return; } }; println!( "Our info:\n\n{}\n", serde_json::to_string(&ourinfo).unwrap() ); } fn print_logo() { println!( r#" _ ____ _ _ __ _ _ _(_) ___ _ __|___ \ _ __ ___| |__ __ _| |_ / _` | | | | |/ __| ____ | '_ \ __) | '_ \ / __| '_ \ / _` | __| | (_| | |_| | | (__ |____|| |_) / __/| |_) | | (__| | | | (_| | |_ \__, |\__,_|_|\___| | .__/_____| .__/ \___|_| |_|\__,_|\__| |_| |_| |_| "# ); } #[allow(unsafe_code)] fn random_vec(size: usize) -> Vec<u8> { let mut ret = Vec::with_capacity(size); unsafe { ret.set_len(size) }; rand::thread_rng().fill_bytes(&mut ret[..]); ret }
33.226337
100
0.50161
d738ae274300e78f08b6a56aeb821251ef6c1862
21,815
// Module is generated from: // spec/fixtures/generator/block_comments.x #![allow(clippy::missing_errors_doc, clippy::unreadable_literal)] use core::{fmt, fmt::Debug, ops::Deref}; // When feature alloc is turned off use static lifetime Box and Vec types. #[cfg(not(feature = "alloc"))] mod noalloc { pub mod boxed { pub type Box<T> = &'static T; } pub mod vec { pub type Vec<T> = &'static [T]; } } #[cfg(not(feature = "alloc"))] use noalloc::{boxed::Box, vec::Vec}; // When feature std is turned off, but feature alloc is turned on import the // alloc crate and use its Box and Vec types. #[cfg(all(not(feature = "std"), feature = "alloc"))] extern crate alloc; #[cfg(all(not(feature = "std"), feature = "alloc"))] use alloc::{ borrow::ToOwned, boxed::Box, string::{FromUtf8Error, String}, vec::Vec, }; #[cfg(all(feature = "std"))] use std::string::FromUtf8Error; // TODO: Add support for read/write xdr fns when std not available. #[cfg(feature = "std")] use std::{ error, io, io::{Cursor, Read, Write}, }; #[derive(Debug)] pub enum Error { Invalid, LengthExceedsMax, LengthMismatch, NonZeroPadding, Utf8Error(core::str::Utf8Error), #[cfg(feature = "std")] IO(io::Error), } #[cfg(feature = "std")] impl error::Error for Error { #[must_use] fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { Self::IO(e) => Some(e), _ => None, } } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Error::Invalid => write!(f, "xdr value invalid"), Error::LengthExceedsMax => write!(f, "xdr value max length exceeded"), Error::LengthMismatch => write!(f, "xdr value length does not match"), Error::NonZeroPadding => write!(f, "xdr padding contains non-zero bytes"), Error::Utf8Error(e) => write!(f, "{}", e), #[cfg(feature = "std")] Error::IO(e) => write!(f, "{}", e), } } } impl From<core::str::Utf8Error> for Error { #[must_use] fn from(e: core::str::Utf8Error) -> Self { Error::Utf8Error(e) } } #[cfg(feature = "alloc")] impl From<FromUtf8Error> for Error { #[must_use] fn from(e: FromUtf8Error) -> Self { Error::Utf8Error(e.utf8_error()) } } #[cfg(feature = "std")] impl From<io::Error> for Error { #[must_use] fn from(e: io::Error) -> Self { Error::IO(e) } } impl From<Error> for () { fn from(_: Error) {} } #[allow(dead_code)] type Result<T> = core::result::Result<T, Error>; pub trait ReadXdr where Self: Sized, { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self>; #[cfg(feature = "std")] fn read_xdr_into(&mut self, r: &mut impl Read) -> Result<()> { *self = Self::read_xdr(r)?; Ok(()) } #[cfg(feature = "std")] fn from_xdr<B: AsRef<[u8]>>(bytes: B) -> Result<Self> { let mut cursor = Cursor::new(bytes.as_ref()); let t = Self::read_xdr(&mut cursor)?; Ok(t) } #[cfg(feature = "std")] fn from_xdr_base64(b64: String) -> Result<Self> { let mut b64_reader = Cursor::new(b64); let mut dec = base64::read::DecoderReader::new(&mut b64_reader, base64::STANDARD); let t = Self::read_xdr(&mut dec)?; Ok(t) } } pub trait WriteXdr { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()>; #[cfg(feature = "std")] fn to_xdr(&self) -> Result<Vec<u8>> { let mut cursor = Cursor::new(vec![]); self.write_xdr(&mut cursor)?; let bytes = cursor.into_inner(); Ok(bytes) } #[cfg(feature = "std")] fn to_xdr_base64(&self) -> Result<String> { let mut enc = base64::write::EncoderStringWriter::new(base64::STANDARD); self.write_xdr(&mut enc)?; let b64 = enc.into_inner(); Ok(b64) } } /// `Pad_len` returns the number of bytes to pad an XDR value of the given /// length to make the final serialized size a multiple of 4. #[cfg(feature = "std")] fn pad_len(len: usize) -> usize { (4 - (len % 4)) % 4 } impl ReadXdr for i32 { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut b = [0u8; 4]; r.read_exact(&mut b)?; let i = i32::from_be_bytes(b); Ok(i) } } impl WriteXdr for i32 { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let b: [u8; 4] = self.to_be_bytes(); w.write_all(&b)?; Ok(()) } } impl ReadXdr for u32 { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut b = [0u8; 4]; r.read_exact(&mut b)?; let i = u32::from_be_bytes(b); Ok(i) } } impl WriteXdr for u32 { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let b: [u8; 4] = self.to_be_bytes(); w.write_all(&b)?; Ok(()) } } impl ReadXdr for i64 { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut b = [0u8; 8]; r.read_exact(&mut b)?; let i = i64::from_be_bytes(b); Ok(i) } } impl WriteXdr for i64 { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let b: [u8; 8] = self.to_be_bytes(); w.write_all(&b)?; Ok(()) } } impl ReadXdr for u64 { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut b = [0u8; 8]; r.read_exact(&mut b)?; let i = u64::from_be_bytes(b); Ok(i) } } impl WriteXdr for u64 { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let b: [u8; 8] = self.to_be_bytes(); w.write_all(&b)?; Ok(()) } } impl ReadXdr for f32 { #[cfg(feature = "std")] fn read_xdr(_r: &mut impl Read) -> Result<Self> { todo!() } } impl WriteXdr for f32 { #[cfg(feature = "std")] fn write_xdr(&self, _w: &mut impl Write) -> Result<()> { todo!() } } impl ReadXdr for f64 { #[cfg(feature = "std")] fn read_xdr(_r: &mut impl Read) -> Result<Self> { todo!() } } impl WriteXdr for f64 { #[cfg(feature = "std")] fn write_xdr(&self, _w: &mut impl Write) -> Result<()> { todo!() } } impl ReadXdr for bool { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let i = u32::read_xdr(r)?; let b = i == 1; Ok(b) } } impl WriteXdr for bool { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let i: u32 = if *self { 1 } else { 0 }; i.write_xdr(w)?; Ok(()) } } impl<T: ReadXdr> ReadXdr for Option<T> { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let i = u32::read_xdr(r)?; match i { 0 => Ok(None), 1 => { let t = T::read_xdr(r)?; Ok(Some(t)) } _ => Err(Error::Invalid), } } } impl<T: WriteXdr> WriteXdr for Option<T> { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { if let Some(t) = self { 1u32.write_xdr(w)?; t.write_xdr(w)?; } else { 0u32.write_xdr(w)?; } Ok(()) } } impl<T: ReadXdr> ReadXdr for Box<T> { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let t = T::read_xdr(r)?; Ok(Box::new(t)) } } impl<T: WriteXdr> WriteXdr for Box<T> { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { T::write_xdr(self, w)?; Ok(()) } } impl ReadXdr for () { #[cfg(feature = "std")] fn read_xdr(_r: &mut impl Read) -> Result<Self> { Ok(()) } } impl WriteXdr for () { #[cfg(feature = "std")] fn write_xdr(&self, _w: &mut impl Write) -> Result<()> { Ok(()) } } impl<const N: usize> ReadXdr for [u8; N] { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut arr = [0u8; N]; r.read_exact(&mut arr)?; let pad = &mut [0u8; 3][..pad_len(N)]; r.read_exact(pad)?; if pad.iter().any(|b| *b != 0) { return Err(Error::NonZeroPadding); } Ok(arr) } } impl<const N: usize> WriteXdr for [u8; N] { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { w.write_all(self)?; w.write_all(&[0u8; 3][..pad_len(N)])?; Ok(()) } } impl<T: ReadXdr, const N: usize> ReadXdr for [T; N] { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let mut vec = Vec::with_capacity(N); for _ in 0..N { let t = T::read_xdr(r)?; vec.push(t); } let arr: [T; N] = vec.try_into().unwrap_or_else(|_: Vec<T>| unreachable!()); Ok(arr) } } impl<T: WriteXdr, const N: usize> WriteXdr for [T; N] { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { for t in self { t.write_xdr(w)?; } Ok(()) } } #[cfg(feature = "alloc")] #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct VecM<T, const MAX: u32 = { u32::MAX }>(Vec<T>); #[cfg(not(feature = "alloc"))] #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct VecM<T, const MAX: u32 = { u32::MAX }>(Vec<T>) where T: 'static; impl<T, const MAX: u32> Deref for VecM<T, MAX> { type Target = Vec<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T, const MAX: u32> VecM<T, MAX> { pub const MAX_LEN: usize = { MAX as usize }; #[must_use] #[allow(clippy::unused_self)] pub fn max_len(&self) -> usize { Self::MAX_LEN } #[must_use] pub fn as_vec(&self) -> &Vec<T> { self.as_ref() } } impl<T: Clone, const MAX: u32> VecM<T, MAX> { #[must_use] #[cfg(feature = "alloc")] pub fn to_vec(&self) -> Vec<T> { self.into() } #[must_use] pub fn into_vec(self) -> Vec<T> { self.into() } } impl<const MAX: u32> VecM<u8, MAX> { #[cfg(feature = "alloc")] pub fn to_string(&self) -> Result<String> { self.try_into() } #[cfg(feature = "alloc")] pub fn into_string(self) -> Result<String> { self.try_into() } } impl<T, const MAX: u32> TryFrom<Vec<T>> for VecM<T, MAX> { type Error = Error; fn try_from(v: Vec<T>) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v)) } else { Err(Error::LengthExceedsMax) } } } impl<T, const MAX: u32> From<VecM<T, MAX>> for Vec<T> { #[must_use] fn from(v: VecM<T, MAX>) -> Self { v.0 } } #[cfg(feature = "alloc")] impl<T: Clone, const MAX: u32> From<&VecM<T, MAX>> for Vec<T> { #[must_use] fn from(v: &VecM<T, MAX>) -> Self { v.0.clone() } } impl<T, const MAX: u32> AsRef<Vec<T>> for VecM<T, MAX> { #[must_use] fn as_ref(&self) -> &Vec<T> { &self.0 } } #[cfg(feature = "alloc")] impl<T: Clone, const MAX: u32> TryFrom<&[T]> for VecM<T, MAX> { type Error = Error; fn try_from(v: &[T]) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.to_vec())) } else { Err(Error::LengthExceedsMax) } } } impl<T, const MAX: u32> AsRef<[T]> for VecM<T, MAX> { #[cfg(feature = "alloc")] #[must_use] fn as_ref(&self) -> &[T] { self.0.as_ref() } #[cfg(not(feature = "alloc"))] #[must_use] fn as_ref(&self) -> &[T] { self.0 } } #[cfg(feature = "alloc")] impl<T: Clone, const N: usize, const MAX: u32> TryFrom<[T; N]> for VecM<T, MAX> { type Error = Error; fn try_from(v: [T; N]) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.to_vec())) } else { Err(Error::LengthExceedsMax) } } } #[cfg(feature = "alloc")] impl<T: Clone, const N: usize, const MAX: u32> TryFrom<VecM<T, MAX>> for [T; N] { type Error = VecM<T, MAX>; fn try_from(v: VecM<T, MAX>) -> core::result::Result<Self, Self::Error> { let s: [T; N] = v.0.try_into().map_err(|v: Vec<T>| VecM::<T, MAX>(v))?; Ok(s) } } #[cfg(feature = "alloc")] impl<T: Clone, const N: usize, const MAX: u32> TryFrom<&[T; N]> for VecM<T, MAX> { type Error = Error; fn try_from(v: &[T; N]) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.to_vec())) } else { Err(Error::LengthExceedsMax) } } } #[cfg(not(feature = "alloc"))] impl<T: Clone, const N: usize, const MAX: u32> TryFrom<&'static [T; N]> for VecM<T, MAX> where T: 'static, { type Error = Error; fn try_from(v: &'static [T; N]) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v)) } else { Err(Error::LengthExceedsMax) } } } #[cfg(feature = "alloc")] impl<const MAX: u32> TryFrom<&String> for VecM<u8, MAX> { type Error = Error; fn try_from(v: &String) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.as_bytes().to_vec())) } else { Err(Error::LengthExceedsMax) } } } #[cfg(feature = "alloc")] impl<const MAX: u32> TryFrom<String> for VecM<u8, MAX> { type Error = Error; fn try_from(v: String) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.into())) } else { Err(Error::LengthExceedsMax) } } } #[cfg(feature = "alloc")] impl<const MAX: u32> TryFrom<VecM<u8, MAX>> for String { type Error = Error; fn try_from(v: VecM<u8, MAX>) -> Result<Self> { Ok(String::from_utf8(v.0)?) } } #[cfg(feature = "alloc")] impl<const MAX: u32> TryFrom<&VecM<u8, MAX>> for String { type Error = Error; fn try_from(v: &VecM<u8, MAX>) -> Result<Self> { Ok(core::str::from_utf8(v.as_ref())?.to_owned()) } } #[cfg(feature = "alloc")] impl<const MAX: u32> TryFrom<&str> for VecM<u8, MAX> { type Error = Error; fn try_from(v: &str) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.into())) } else { Err(Error::LengthExceedsMax) } } } #[cfg(not(feature = "alloc"))] impl<const MAX: u32> TryFrom<&'static str> for VecM<u8, MAX> { type Error = Error; fn try_from(v: &'static str) -> Result<Self> { let len: u32 = v.len().try_into().map_err(|_| Error::LengthExceedsMax)?; if len <= MAX { Ok(VecM(v.as_bytes())) } else { Err(Error::LengthExceedsMax) } } } impl<'a, const MAX: u32> TryFrom<&'a VecM<u8, MAX>> for &'a str { type Error = Error; fn try_from(v: &'a VecM<u8, MAX>) -> Result<Self> { Ok(core::str::from_utf8(v.as_ref())?) } } impl<const MAX: u32> ReadXdr for VecM<u8, MAX> { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let len: u32 = u32::read_xdr(r)?; if len > MAX { return Err(Error::LengthExceedsMax); } let mut vec = vec![0u8; len as usize]; r.read_exact(&mut vec)?; let pad = &mut [0u8; 3][..pad_len(len as usize)]; r.read_exact(pad)?; if pad.iter().any(|b| *b != 0) { return Err(Error::NonZeroPadding); } Ok(VecM(vec)) } } impl<const MAX: u32> WriteXdr for VecM<u8, MAX> { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let len: u32 = self.len().try_into().map_err(|_| Error::LengthExceedsMax)?; len.write_xdr(w)?; w.write_all(&self.0)?; w.write_all(&[0u8; 3][..pad_len(len as usize)])?; Ok(()) } } impl<T: ReadXdr, const MAX: u32> ReadXdr for VecM<T, MAX> { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let len = u32::read_xdr(r)?; if len > MAX { return Err(Error::LengthExceedsMax); } let mut vec = Vec::with_capacity(len as usize); for _ in 0..len { let t = T::read_xdr(r)?; vec.push(t); } Ok(VecM(vec)) } } impl<T: WriteXdr, const MAX: u32> WriteXdr for VecM<T, MAX> { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let len: u32 = self.len().try_into().map_err(|_| Error::LengthExceedsMax)?; len.write_xdr(w)?; for t in &self.0 { t.write_xdr(w)?; } Ok(()) } } #[cfg(all(test, feature = "std"))] mod tests { use std::io::Cursor; use crate::WriteXdr; use super::{Error, ReadXdr, VecM}; #[test] pub fn vec_u8_read_without_padding() { let mut buf = Cursor::new(vec![0, 0, 0, 4, 2, 2, 2, 2]); let v = VecM::<u8, 8>::read_xdr(&mut buf).unwrap(); assert_eq!(v.to_vec(), vec![2, 2, 2, 2]); } #[test] pub fn vec_u8_read_with_padding() { let mut buf = Cursor::new(vec![0, 0, 0, 1, 2, 0, 0, 0]); let v = VecM::<u8, 8>::read_xdr(&mut buf).unwrap(); assert_eq!(v.to_vec(), vec![2]); } #[test] pub fn vec_u8_read_with_insufficient_padding() { let mut buf = Cursor::new(vec![0, 0, 0, 1, 2, 0, 0]); let res = VecM::<u8, 8>::read_xdr(&mut buf); match res { Err(Error::IO(_)) => (), _ => panic!("expected IO error got {:?}", res), } } #[test] pub fn vec_u8_read_with_non_zero_padding() { let mut buf = Cursor::new(vec![0, 0, 0, 1, 2, 3, 0, 0]); let res = VecM::<u8, 8>::read_xdr(&mut buf); match res { Err(Error::NonZeroPadding) => (), _ => panic!("expected NonZeroPadding got {:?}", res), } } #[test] pub fn vec_u8_write_without_padding() { let mut buf = vec![]; let v: VecM<u8, 8> = vec![2, 2, 2, 2].try_into().unwrap(); v.write_xdr(&mut Cursor::new(&mut buf)).unwrap(); assert_eq!(buf, vec![0, 0, 0, 4, 2, 2, 2, 2]); } #[test] pub fn vec_u8_write_with_padding() { let mut buf = vec![]; let v: VecM<u8, 8> = vec![2].try_into().unwrap(); v.write_xdr(&mut Cursor::new(&mut buf)).unwrap(); assert_eq!(buf, vec![0, 0, 0, 1, 2, 0, 0, 0]); } #[test] pub fn arr_u8_read_without_padding() { let mut buf = Cursor::new(vec![2, 2, 2, 2]); let v = <[u8; 4]>::read_xdr(&mut buf).unwrap(); assert_eq!(v, [2, 2, 2, 2]); } #[test] pub fn arr_u8_read_with_padding() { let mut buf = Cursor::new(vec![2, 0, 0, 0]); let v = <[u8; 1]>::read_xdr(&mut buf).unwrap(); assert_eq!(v, [2]); } #[test] pub fn arr_u8_read_with_insufficient_padding() { let mut buf = Cursor::new(vec![2, 0, 0]); let res = <[u8; 1]>::read_xdr(&mut buf); match res { Err(Error::IO(_)) => (), _ => panic!("expected IO error got {:?}", res), } } #[test] pub fn arr_u8_read_with_non_zero_padding() { let mut buf = Cursor::new(vec![2, 3, 0, 0]); let res = <[u8; 1]>::read_xdr(&mut buf); match res { Err(Error::NonZeroPadding) => (), _ => panic!("expected NonZeroPadding got {:?}", res), } } #[test] pub fn arr_u8_write_without_padding() { let mut buf = vec![]; [2u8, 2, 2, 2] .write_xdr(&mut Cursor::new(&mut buf)) .unwrap(); assert_eq!(buf, vec![2, 2, 2, 2]); } #[test] pub fn arr_u8_write_with_padding() { let mut buf = vec![]; [2u8].write_xdr(&mut Cursor::new(&mut buf)).unwrap(); assert_eq!(buf, vec![2, 0, 0, 0]); } } // AccountFlags is an XDR Enum defines as: // // enum AccountFlags // { // masks for each flag // AUTH_REQUIRED_FLAG = 0x1 // }; // // enum #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] #[repr(i32)] pub enum AccountFlags { AuthRequiredFlag = 1, } impl TryFrom<i32> for AccountFlags { type Error = Error; fn try_from(i: i32) -> Result<Self> { let e = match i { 1 => AccountFlags::AuthRequiredFlag, #[allow(unreachable_patterns)] _ => return Err(Error::Invalid), }; Ok(e) } } impl From<AccountFlags> for i32 { #[must_use] fn from(e: AccountFlags) -> Self { e as Self } } impl ReadXdr for AccountFlags { #[cfg(feature = "std")] fn read_xdr(r: &mut impl Read) -> Result<Self> { let e = i32::read_xdr(r)?; let v: Self = e.try_into()?; Ok(v) } } impl WriteXdr for AccountFlags { #[cfg(feature = "std")] fn write_xdr(&self, w: &mut impl Write) -> Result<()> { let i: i32 = (*self).into(); i.write_xdr(w) } }
24.874572
90
0.519184
de4e8e5c6decf9b81b9c69558f384efeaf85451a
9,471
#![deny(missing_docs)] #![deny(missing_debug_implementations)] #![cfg_attr(test, deny(warnings))] #![doc(html_root_url = "https://docs.rs/reqwest/0.10.0-alpha.1")] //! # reqwest //! //! The `reqwest` crate provides a convenient, higher-level HTTP //! [`Client`][client]. //! //! It handles many of the things that most people just expect an HTTP client //! to do for them. //! //! - Async and [blocking](blocking) Clients //! - Plain bodies, [JSON](#json), [urlencoded](#forms), [multipart](multipart) //! - Customizable [redirect policy](#redirect-policies) //! - HTTP [Proxies](#proxies) //! - Uses system-native [TLS](#tls) //! - Cookies //! //! The [`reqwest::Client`][client] is asynchronous. For applications wishing //! to only make a few HTTP requests, the [`reqwest::blocking`](blocking) API //! may be more convenient. //! //! Additional learning resources include: //! //! - [The Rust Cookbook](https://rust-lang-nursery.github.io/rust-cookbook/web/clients.html) //! - [Reqwest Repository Examples](https://github.com/seanmonstar/reqwest/tree/master/examples) //! //! ## Making a GET request //! //! For a single request, you can use the [`get`][get] shortcut method. //! //! ```rust //! # async fn run() -> Result<(), reqwest::Error> { //! let body = reqwest::get("https://www.rust-lang.org") //! .await? //! .text() //! .await?; //! //! println!("body = {:?}", body); //! # Ok(()) //! # } //! ``` //! //! **NOTE**: If you plan to perform multiple requests, it is best to create a //! [`Client`][client] and reuse it, taking advantage of keep-alive connection //! pooling. //! //! ## Making POST requests (or setting request bodies) //! //! There are several ways you can set the body of a request. The basic one is //! by using the `body()` method of a [`RequestBuilder`][builder]. This lets you set the //! exact raw bytes of what the body should be. It accepts various types, //! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom //! type, you can use the `reqwest::Body` constructors. //! //! ```rust //! # use reqwest::Error; //! # //! # async fn run() -> Result<(), Error> { //! let client = reqwest::Client::new(); //! let res = client.post("http://httpbin.org/post") //! .body("the exact body that is sent") //! .send() //! .await?; //! # Ok(()) //! # } //! ``` //! //! ### Forms //! //! It's very common to want to send form data in a request body. This can be //! done with any type that can be serialized into form data. //! //! This can be an array of tuples, or a `HashMap`, or a custom type that //! implements [`Serialize`][serde]. //! //! ```rust //! # use reqwest::Error; //! # //! # async fn run() -> Result<(), Error> { //! // This will POST a body of `foo=bar&baz=quux` //! let params = [("foo", "bar"), ("baz", "quux")]; //! let client = reqwest::Client::new(); //! let res = client.post("http://httpbin.org/post") //! .form(&params) //! .send() //! .await?; //! # Ok(()) //! # } //! ``` //! //! ### JSON //! //! There is also a `json` method helper on the [`RequestBuilder`][builder] that works in //! a similar fashion the `form` method. It can take any value that can be //! serialized into JSON. The feature `json` is required. //! //! ```rust //! # use reqwest::Error; //! # use std::collections::HashMap; //! # //! # #[cfg(feature = "json")] //! # async fn run() -> Result<(), Error> { //! // This will POST a body of `{"lang":"rust","body":"json"}` //! let mut map = HashMap::new(); //! map.insert("lang", "rust"); //! map.insert("body", "json"); //! //! let client = reqwest::Client::new(); //! let res = client.post("http://httpbin.org/post") //! .json(&map) //! .send() //! .await?; //! # Ok(()) //! # } //! ``` //! //! ## Redirect Policies //! //! By default, a `Client` will automatically handle HTTP redirects, detecting //! loops, and having a maximum redirect chain of 10 hops. To customize this //! behavior, a [`RedirectPolicy`][redirect] can used with a `ClientBuilder`. //! //! ## Cookies //! //! The automatic storing and sending of session cookies can be enabled with //! the [`cookie_store`][ClientBuilder::cookie_store] method on `ClientBuilder`. //! //! ## Proxies //! //! ** NOTE ** Proxies are enabled by default. //! //! System proxies look in environment variables to set HTTP or HTTPS proxies. //! //! `HTTP_PROXY` or `http_proxy` provide http proxies for http connections while //! `HTTPS_PROXY` or `https_proxy` provide HTTPS proxies for HTTPS connections. //! //! These can be overwritten by adding a [`Proxy`](Proxy) to `ClientBuilder` //! i.e. `let proxy = reqwest::Proxy::http("https://secure.example")?;` //! or disabled by calling `ClientBuilder::no_proxy()`. //! //! ## TLS //! //! By default, a `Client` will make use of system-native transport layer //! security to connect to HTTPS destinations. This means schannel on Windows, //! Security-Framework on macOS, and OpenSSL on Linux. //! //! - Additional X509 certificates can be configured on a `ClientBuilder` with the //! [`Certificate`](Certificate) type. //! - Client certificates can be add to a `ClientBuilder` with the //! [`Identity`][Identity] type. //! - Various parts of TLS can also be configured or even disabled on the //! `ClientBuilder`. //! //! ## Optional Features //! //! The following are a list of [Cargo features][cargo-features] that can be //! enabled or disabled: //! //! - **default-tls** *(enabled by default)*: Provides TLS support via the //! `native-tls` library to connect over HTTPS. //! - **default-tls-vendored**: Enables the `vendored` feature of `native-tls`. //! - **blocking**: Provides the [blocking][] client API. //! - **cookies**: Provides cookie session support. //! - **gzip**: Provides response body gzip decompression. //! - **json**: Provides serialization and deserialization for JSON bodies. //! - **unstable-stream** *(unstable)*: Adds support for `futures::Stream`. //! //! //! [hyper]: http://hyper.rs //! [client]: ./struct.Client.html //! [response]: ./struct.Response.html //! [get]: ./fn.get.html //! [builder]: ./struct.RequestBuilder.html //! [serde]: http://serde.rs //! [redirect]: ./struct.RedirectPolicy.html //! [Proxy]: ./struct.Proxy.html //! [cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section ////! - **rustls-tls**: Provides TLS support via the `rustls` library. ////! - **socks**: Provides SOCKS5 proxy support. ////! - **trust-dns**: Enables a trust-dns async resolver instead of default ////! threadpool using `getaddrinfo`. macro_rules! if_wasm { ($($item:item)*) => {$( #[cfg(target_arch = "wasm32")] $item )*} } macro_rules! if_hyper { ($($item:item)*) => {$( #[cfg(not(target_arch = "wasm32"))] $item )*} } pub use http::header; pub use http::Method; pub use http::{StatusCode, Version}; pub use url::Url; // universal mods #[macro_use] mod error; mod into_url; pub use self::error::{Error, Result}; pub use self::into_url::IntoUrl; /// Shortcut method to quickly make a `GET` request. /// /// See also the methods on the [`reqwest::Response`](./struct.Response.html) /// type. /// /// **NOTE**: This function creates a new internal `Client` on each call, /// and so should not be used if making many requests. Create a /// [`Client`](./struct.Client.html) instead. /// /// # Examples /// /// ```rust /// # async fn run() -> Result<(), reqwest::Error> { /// let body = reqwest::get("https://www.rust-lang.org").await? /// .text().await?; /// # Ok(()) /// # } /// ``` /// /// # Errors /// /// This function fails if: /// /// - native TLS backend cannot be initialized /// - supplied `Url` cannot be parsed /// - there was an error while sending request /// - redirect loop was detected /// - redirect limit was exhausted pub async fn get<T: IntoUrl>(url: T) -> crate::Result<Response> { Client::builder().build()?.get(url).send().await } fn _assert_impls() { fn assert_send<T: Send>() {} fn assert_sync<T: Sync>() {} fn assert_clone<T: Clone>() {} assert_send::<Client>(); assert_sync::<Client>(); assert_clone::<Client>(); assert_send::<Request>(); assert_send::<RequestBuilder>(); #[cfg(not(target_arch = "wasm32"))] { assert_send::<Response>(); } assert_send::<Error>(); assert_sync::<Error>(); } if_hyper! { #[cfg(test)] #[macro_use] extern crate doc_comment; #[macro_use] extern crate lazy_static; #[cfg(test)] doctest!("../README.md"); pub use self::async_impl::{ multipart, Body, Client, ClientBuilder, Request, RequestBuilder, Response, }; pub use self::proxy::Proxy; pub use self::redirect::{RedirectAction, RedirectAttempt, RedirectPolicy}; #[cfg(feature = "tls")] pub use self::tls::{Certificate, Identity}; mod async_impl; #[cfg(feature = "blocking")] pub mod blocking; mod connect; #[cfg(feature = "cookies")] pub mod cookie; //#[cfg(feature = "trust-dns")] //mod dns; mod proxy; mod redirect; #[cfg(feature = "tls")] mod tls; #[doc(hidden)] #[deprecated(note = "types moved to top of crate")] pub mod r#async { pub use crate::async_impl::{ multipart, Body, Client, ClientBuilder, Request, RequestBuilder, Response, }; } } if_wasm! { mod wasm; pub use self::wasm::{Body, Client, ClientBuilder, Request, RequestBuilder, Response}; }
30.16242
105
0.62211
ac373a0fe88cc61ed3d40ef8384f6cc2f9df2190
786
use deku::prelude::*; use hex_literal::hex; use std::convert::TryFrom; #[derive(Debug, PartialEq, DekuRead, DekuWrite)] #[deku(id_type = "u8")] enum DekuTest { #[deku(id = "0")] VarD, #[deku(id = "1")] Var1(#[deku(bytes = "2")] u32), #[deku(id = "2")] Var2(u8, u8), #[deku(id = "3")] Var3 { field_a: u8, #[deku(count = "field_a")] field_b: Vec<u8>, }, } fn main() { let test_data = hex!("03020102").to_vec(); let deku_test = DekuTest::try_from(test_data.as_ref()).unwrap(); assert_eq!( DekuTest::Var3 { field_a: 0x02, field_b: vec![0x01, 0x02] }, deku_test ); let ret_out: Vec<u8> = deku_test.to_bytes().unwrap(); assert_eq!(test_data, ret_out); }
20.153846
68
0.530534
d5136833a11e39df501e8c8a1ee74cf59ae0eaf3
1,654
use bstr::ByteSlice; use bvh_anim::{ bvh, write::{IndentStyle, LineTerminator, WriteOptions}, }; use pretty_assertions::assert_eq; #[test] fn test_write() { const BVH_STRING: &[u8] = include_bytes!("../data/test_simple.bvh"); let bvh = bvh! { HIERARCHY ROOT Base { OFFSET 0.0 0.0 0.0 CHANNELS 6 Xposition Yposition Zposition Zrotation Xrotation Yrotation JOINT End { OFFSET 0.0 0.0 15.0 CHANNELS 3 Zrotation Xrotation Yrotation End Site { OFFSET 0.0 0.0 30.0 } } } MOTION Frames: 2 Frame Time: 0.033333333 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 }; let bvh_string = WriteOptions::new() .with_offset_significant_figures(1) .with_motion_values_significant_figures(1) .with_line_terminator(LineTerminator::native()) .with_indent(IndentStyle::with_spaces(4)) .write_to_string(&bvh); assert_eq!(bvh_string.trim(), BVH_STRING.trim()); } #[test] fn test_load_write_is_identical() { const BVH_STRING: &str = include_str!("../data/test_simple.bvh"); let bvh = bvh_anim::from_str(BVH_STRING).unwrap(); let bvh_string = WriteOptions::new() .with_indent(IndentStyle::with_spaces(4)) .with_offset_significant_figures(1) .with_motion_values_significant_figures(1) .with_line_terminator(LineTerminator::native()) .write_to_string(&bvh); assert_eq!(bvh_string, BVH_STRING); }
28.517241
82
0.591294
71fec79347a87c9103f02733fc71b0e890106917
19,749
//! Implementation of `std::os` functionality for unix systems #![allow(unused_imports)] // lots of cfg code here #[cfg(all(test, target_env = "gnu"))] mod tests; use crate::os::unix::prelude::*; use crate::error::Error as StdError; use crate::ffi::{CStr, CString, OsStr, OsString}; use crate::fmt; use crate::io; use crate::iter; use crate::mem; use crate::path::{self, PathBuf}; use crate::ptr; use crate::slice; use crate::str; use crate::sys::cvt; use crate::sys::fd; use crate::sys::memchr; use crate::sys_common::rwlock::{StaticRWLock, StaticRWLockReadGuard}; use crate::vec; use libc::{c_char, c_int, c_void}; const TMPBUF_SZ: usize = 128; cfg_if::cfg_if! { if #[cfg(target_os = "redox")] { const PATH_SEPARATOR: u8 = b';'; } else { const PATH_SEPARATOR: u8 = b':'; } } extern "C" { #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))] #[cfg_attr( any( target_os = "linux", target_os = "emscripten", target_os = "fuchsia", target_os = "l4re" ), link_name = "__errno_location" )] #[cfg_attr( any( target_os = "netbsd", target_os = "openbsd", target_os = "android", target_os = "redox", target_env = "newlib" ), link_name = "__errno" )] #[cfg_attr(any(target_os = "solaris", target_os = "illumos"), link_name = "___errno")] #[cfg_attr( any(target_os = "macos", target_os = "ios", target_os = "freebsd"), link_name = "__error" )] #[cfg_attr(target_os = "haiku", link_name = "_errnop")] fn errno_location() -> *mut c_int; } /// Returns the platform-specific value of errno #[cfg(not(any(target_os = "dragonfly", target_os = "vxworks")))] pub fn errno() -> i32 { unsafe { (*errno_location()) as i32 } } /// Sets the platform-specific value of errno #[cfg(all(not(target_os = "linux"), not(target_os = "dragonfly"), not(target_os = "vxworks")))] // needed for readdir and syscall! #[allow(dead_code)] // but not all target cfgs actually end up using it pub fn set_errno(e: i32) { unsafe { *errno_location() = e as c_int } } #[cfg(target_os = "vxworks")] pub fn errno() -> i32 { unsafe { libc::errnoGet() } } #[cfg(target_os = "dragonfly")] pub fn errno() -> i32 { extern "C" { #[thread_local] static errno: c_int; } unsafe { errno as i32 } } #[cfg(target_os = "dragonfly")] pub fn set_errno(e: i32) { extern "C" { #[thread_local] static mut errno: c_int; } unsafe { errno = e; } } /// Gets a detailed string description for the given error number. pub fn error_string(errno: i32) -> String { extern "C" { #[cfg_attr(any(target_os = "linux", target_env = "newlib"), link_name = "__xpg_strerror_r")] fn strerror_r(errnum: c_int, buf: *mut c_char, buflen: libc::size_t) -> c_int; } let mut buf = [0 as c_char; TMPBUF_SZ]; let p = buf.as_mut_ptr(); unsafe { if strerror_r(errno as c_int, p, buf.len()) < 0 { panic!("strerror_r failure"); } let p = p as *const _; str::from_utf8(CStr::from_ptr(p).to_bytes()).unwrap().to_owned() } } pub fn getcwd() -> io::Result<PathBuf> { let mut buf = Vec::with_capacity(512); loop { unsafe { let ptr = buf.as_mut_ptr() as *mut libc::c_char; if !libc::getcwd(ptr, buf.capacity()).is_null() { let len = CStr::from_ptr(buf.as_ptr() as *const libc::c_char).to_bytes().len(); buf.set_len(len); buf.shrink_to_fit(); return Ok(PathBuf::from(OsString::from_vec(buf))); } else { let error = io::Error::last_os_error(); if error.raw_os_error() != Some(libc::ERANGE) { return Err(error); } } // Trigger the internal buffer resizing logic of `Vec` by requiring // more space than the current capacity. let cap = buf.capacity(); buf.set_len(cap); buf.reserve(1); } } } pub fn chdir(p: &path::Path) -> io::Result<()> { let p: &OsStr = p.as_ref(); let p = CString::new(p.as_bytes())?; if unsafe { libc::chdir(p.as_ptr()) } != 0 { return Err(io::Error::last_os_error()); } Ok(()) } pub struct SplitPaths<'a> { iter: iter::Map<slice::Split<'a, u8, fn(&u8) -> bool>, fn(&'a [u8]) -> PathBuf>, } pub fn split_paths(unparsed: &OsStr) -> SplitPaths<'_> { fn bytes_to_path(b: &[u8]) -> PathBuf { PathBuf::from(<OsStr as OsStrExt>::from_bytes(b)) } fn is_separator(b: &u8) -> bool { *b == PATH_SEPARATOR } let unparsed = unparsed.as_bytes(); SplitPaths { iter: unparsed .split(is_separator as fn(&u8) -> bool) .map(bytes_to_path as fn(&[u8]) -> PathBuf), } } impl<'a> Iterator for SplitPaths<'a> { type Item = PathBuf; fn next(&mut self) -> Option<PathBuf> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[derive(Debug)] pub struct JoinPathsError; pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError> where I: Iterator<Item = T>, T: AsRef<OsStr>, { let mut joined = Vec::new(); for (i, path) in paths.enumerate() { let path = path.as_ref().as_bytes(); if i > 0 { joined.push(PATH_SEPARATOR) } if path.contains(&PATH_SEPARATOR) { return Err(JoinPathsError); } joined.extend_from_slice(path); } Ok(OsStringExt::from_vec(joined)) } impl fmt::Display for JoinPathsError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "path segment contains separator `{}`", char::from(PATH_SEPARATOR)) } } impl StdError for JoinPathsError { #[allow(deprecated)] fn description(&self) -> &str { "failed to join paths" } } #[cfg(any(target_os = "freebsd", target_os = "dragonfly"))] pub fn current_exe() -> io::Result<PathBuf> { unsafe { let mut mib = [ libc::CTL_KERN as c_int, libc::KERN_PROC as c_int, libc::KERN_PROC_PATHNAME as c_int, -1 as c_int, ]; let mut sz = 0; cvt(libc::sysctl( mib.as_mut_ptr(), mib.len() as libc::c_uint, ptr::null_mut(), &mut sz, ptr::null_mut(), 0, ))?; if sz == 0 { return Err(io::Error::last_os_error()); } let mut v: Vec<u8> = Vec::with_capacity(sz); cvt(libc::sysctl( mib.as_mut_ptr(), mib.len() as libc::c_uint, v.as_mut_ptr() as *mut libc::c_void, &mut sz, ptr::null_mut(), 0, ))?; if sz == 0 { return Err(io::Error::last_os_error()); } v.set_len(sz - 1); // chop off trailing NUL Ok(PathBuf::from(OsString::from_vec(v))) } } #[cfg(target_os = "netbsd")] pub fn current_exe() -> io::Result<PathBuf> { fn sysctl() -> io::Result<PathBuf> { unsafe { let mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, -1, libc::KERN_PROC_PATHNAME]; let mut path_len: usize = 0; cvt(libc::sysctl( mib.as_ptr(), mib.len() as libc::c_uint, ptr::null_mut(), &mut path_len, ptr::null(), 0, ))?; if path_len <= 1 { return Err(io::Error::new_const( io::ErrorKind::Uncategorized, &"KERN_PROC_PATHNAME sysctl returned zero-length string", )); } let mut path: Vec<u8> = Vec::with_capacity(path_len); cvt(libc::sysctl( mib.as_ptr(), mib.len() as libc::c_uint, path.as_ptr() as *mut libc::c_void, &mut path_len, ptr::null(), 0, ))?; path.set_len(path_len - 1); // chop off NUL Ok(PathBuf::from(OsString::from_vec(path))) } } fn procfs() -> io::Result<PathBuf> { let curproc_exe = path::Path::new("/proc/curproc/exe"); if curproc_exe.is_file() { return crate::fs::read_link(curproc_exe); } Err(io::Error::new_const( io::ErrorKind::Uncategorized, &"/proc/curproc/exe doesn't point to regular file.", )) } sysctl().or_else(|_| procfs()) } #[cfg(target_os = "openbsd")] pub fn current_exe() -> io::Result<PathBuf> { unsafe { let mut mib = [libc::CTL_KERN, libc::KERN_PROC_ARGS, libc::getpid(), libc::KERN_PROC_ARGV]; let mib = mib.as_mut_ptr(); let mut argv_len = 0; cvt(libc::sysctl(mib, 4, ptr::null_mut(), &mut argv_len, ptr::null_mut(), 0))?; let mut argv = Vec::<*const libc::c_char>::with_capacity(argv_len as usize); cvt(libc::sysctl(mib, 4, argv.as_mut_ptr() as *mut _, &mut argv_len, ptr::null_mut(), 0))?; argv.set_len(argv_len as usize); if argv[0].is_null() { return Err(io::Error::new_const( io::ErrorKind::Uncategorized, &"no current exe available", )); } let argv0 = CStr::from_ptr(argv[0]).to_bytes(); if argv0[0] == b'.' || argv0.iter().any(|b| *b == b'/') { crate::fs::canonicalize(OsStr::from_bytes(argv0)) } else { Ok(PathBuf::from(OsStr::from_bytes(argv0))) } } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] pub fn current_exe() -> io::Result<PathBuf> { match crate::fs::read_link("/proc/self/exe") { Err(ref e) if e.kind() == io::ErrorKind::NotFound => Err(io::Error::new_const( io::ErrorKind::Uncategorized, &"no /proc/self/exe available. Is /proc mounted?", )), other => other, } } #[cfg(any(target_os = "macos", target_os = "ios"))] pub fn current_exe() -> io::Result<PathBuf> { extern "C" { fn _NSGetExecutablePath(buf: *mut libc::c_char, bufsize: *mut u32) -> libc::c_int; } unsafe { let mut sz: u32 = 0; _NSGetExecutablePath(ptr::null_mut(), &mut sz); if sz == 0 { return Err(io::Error::last_os_error()); } let mut v: Vec<u8> = Vec::with_capacity(sz as usize); let err = _NSGetExecutablePath(v.as_mut_ptr() as *mut i8, &mut sz); if err != 0 { return Err(io::Error::last_os_error()); } v.set_len(sz as usize - 1); // chop off trailing NUL Ok(PathBuf::from(OsString::from_vec(v))) } } #[cfg(any(target_os = "solaris", target_os = "illumos"))] pub fn current_exe() -> io::Result<PathBuf> { extern "C" { fn getexecname() -> *const c_char; } unsafe { let path = getexecname(); if path.is_null() { Err(io::Error::last_os_error()) } else { let filename = CStr::from_ptr(path).to_bytes(); let path = PathBuf::from(<OsStr as OsStrExt>::from_bytes(filename)); // Prepend a current working directory to the path if // it doesn't contain an absolute pathname. if filename[0] == b'/' { Ok(path) } else { getcwd().map(|cwd| cwd.join(path)) } } } } #[cfg(target_os = "haiku")] pub fn current_exe() -> io::Result<PathBuf> { // Use Haiku's image info functions #[repr(C)] struct image_info { id: i32, type_: i32, sequence: i32, init_order: i32, init_routine: *mut libc::c_void, // function pointer term_routine: *mut libc::c_void, // function pointer device: libc::dev_t, node: libc::ino_t, name: [libc::c_char; 1024], // MAXPATHLEN text: *mut libc::c_void, data: *mut libc::c_void, text_size: i32, data_size: i32, api_version: i32, abi: i32, } unsafe { extern "C" { fn _get_next_image_info( team_id: i32, cookie: *mut i32, info: *mut image_info, size: i32, ) -> i32; } let mut info: image_info = mem::zeroed(); let mut cookie: i32 = 0; // the executable can be found at team id 0 let result = _get_next_image_info(0, &mut cookie, &mut info, mem::size_of::<image_info>() as i32); if result != 0 { use crate::io::ErrorKind; Err(io::Error::new_const(ErrorKind::Uncategorized, &"Error getting executable path")) } else { let name = CStr::from_ptr(info.name.as_ptr()).to_bytes(); Ok(PathBuf::from(OsStr::from_bytes(name))) } } } #[cfg(target_os = "redox")] pub fn current_exe() -> io::Result<PathBuf> { crate::fs::read_to_string("sys:exe").map(PathBuf::from) } #[cfg(any(target_os = "fuchsia", target_os = "l4re"))] pub fn current_exe() -> io::Result<PathBuf> { use crate::io::ErrorKind; Err(io::Error::new_const(ErrorKind::Unsupported, &"Not yet implemented!")) } #[cfg(target_os = "vxworks")] pub fn current_exe() -> io::Result<PathBuf> { #[cfg(test)] use realstd::env; #[cfg(not(test))] use crate::env; let exe_path = env::args().next().unwrap(); let path = path::Path::new(&exe_path); path.canonicalize() } pub struct Env { iter: vec::IntoIter<(OsString, OsString)>, } impl !Send for Env {} impl !Sync for Env {} impl Iterator for Env { type Item = (OsString, OsString); fn next(&mut self) -> Option<(OsString, OsString)> { self.iter.next() } fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } #[cfg(target_os = "macos")] pub unsafe fn environ() -> *mut *const *const c_char { extern "C" { fn _NSGetEnviron() -> *mut *const *const c_char; } _NSGetEnviron() } #[cfg(not(target_os = "macos"))] pub unsafe fn environ() -> *mut *const *const c_char { extern "C" { static mut environ: *const *const c_char; } ptr::addr_of_mut!(environ) } static ENV_LOCK: StaticRWLock = StaticRWLock::new(); pub fn env_read_lock() -> StaticRWLockReadGuard { ENV_LOCK.read() } /// Returns a vector of (variable, value) byte-vector pairs for all the /// environment variables of the current process. pub fn env() -> Env { unsafe { let _guard = env_read_lock(); let mut environ = *environ(); let mut result = Vec::new(); if !environ.is_null() { while !(*environ).is_null() { if let Some(key_value) = parse(CStr::from_ptr(*environ).to_bytes()) { result.push(key_value); } environ = environ.add(1); } } return Env { iter: result.into_iter() }; } fn parse(input: &[u8]) -> Option<(OsString, OsString)> { // Strategy (copied from glibc): Variable name and value are separated // by an ASCII equals sign '='. Since a variable name must not be // empty, allow variable names starting with an equals sign. Skip all // malformed lines. if input.is_empty() { return None; } let pos = memchr::memchr(b'=', &input[1..]).map(|p| p + 1); pos.map(|p| { ( OsStringExt::from_vec(input[..p].to_vec()), OsStringExt::from_vec(input[p + 1..].to_vec()), ) }) } } pub fn getenv(k: &OsStr) -> io::Result<Option<OsString>> { // environment variables with a nul byte can't be set, so their value is // always None as well let k = CString::new(k.as_bytes())?; unsafe { let _guard = env_read_lock(); let s = libc::getenv(k.as_ptr()) as *const libc::c_char; let ret = if s.is_null() { None } else { Some(OsStringExt::from_vec(CStr::from_ptr(s).to_bytes().to_vec())) }; Ok(ret) } } pub fn setenv(k: &OsStr, v: &OsStr) -> io::Result<()> { let k = CString::new(k.as_bytes())?; let v = CString::new(v.as_bytes())?; unsafe { let _guard = ENV_LOCK.write(); cvt(libc::setenv(k.as_ptr(), v.as_ptr(), 1)).map(drop) } } pub fn unsetenv(n: &OsStr) -> io::Result<()> { let nbuf = CString::new(n.as_bytes())?; unsafe { let _guard = ENV_LOCK.write(); cvt(libc::unsetenv(nbuf.as_ptr())).map(drop) } } pub fn page_size() -> usize { unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize } } pub fn temp_dir() -> PathBuf { crate::env::var_os("TMPDIR").map(PathBuf::from).unwrap_or_else(|| { if cfg!(target_os = "android") { PathBuf::from("/data/local/tmp") } else { PathBuf::from("/tmp") } }) } pub fn home_dir() -> Option<PathBuf> { return crate::env::var_os("HOME").or_else(|| unsafe { fallback() }).map(PathBuf::from); #[cfg(any( target_os = "android", target_os = "ios", target_os = "emscripten", target_os = "redox", target_os = "vxworks" ))] unsafe fn fallback() -> Option<OsString> { None } #[cfg(not(any( target_os = "android", target_os = "ios", target_os = "emscripten", target_os = "redox", target_os = "vxworks" )))] unsafe fn fallback() -> Option<OsString> { let amt = match libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) { n if n < 0 => 512 as usize, n => n as usize, }; let mut buf = Vec::with_capacity(amt); let mut passwd: libc::passwd = mem::zeroed(); let mut result = ptr::null_mut(); match libc::getpwuid_r( libc::getuid(), &mut passwd, buf.as_mut_ptr(), buf.capacity(), &mut result, ) { 0 if !result.is_null() => { let ptr = passwd.pw_dir as *const _; let bytes = CStr::from_ptr(ptr).to_bytes().to_vec(); Some(OsStringExt::from_vec(bytes)) } _ => None, } } } pub fn exit(code: i32) -> ! { unsafe { libc::exit(code as c_int) } } pub fn getpid() -> u32 { unsafe { libc::getpid() as u32 } } pub fn getppid() -> u32 { unsafe { libc::getppid() as u32 } } #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))] pub fn glibc_version() -> Option<(usize, usize)> { if let Some(Ok(version_str)) = glibc_version_cstr().map(CStr::to_str) { parse_glibc_version(version_str) } else { None } } #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))] fn glibc_version_cstr() -> Option<&'static CStr> { weak! { fn gnu_get_libc_version() -> *const libc::c_char } if let Some(f) = gnu_get_libc_version.get() { unsafe { Some(CStr::from_ptr(f())) } } else { None } } // Returns Some((major, minor)) if the string is a valid "x.y" version, // ignoring any extra dot-separated parts. Otherwise return None. #[cfg(all(target_env = "gnu", not(target_os = "vxworks")))] fn parse_glibc_version(version: &str) -> Option<(usize, usize)> { let mut parsed_ints = version.split('.').map(str::parse::<usize>).fuse(); match (parsed_ints.next(), parsed_ints.next()) { (Some(Ok(major)), Some(Ok(minor))) => Some((major, minor)), _ => None, } }
29.388393
130
0.54261
dbc7eac5b8da090d21a076f240dd3c18673b41a2
4,266
//! A one-shot, futures-aware channel. use std::future::Future; use std::pin::Pin; use std::task::{Context, Poll}; pub use futures::channel::oneshot::Canceled; use super::cell::Cell; use crate::task::LocalWaker; #[doc(hidden)] #[deprecated(since = "0.1.16", note = "Use pool::create instead")] pub use super::pool::new as pool; #[doc(hidden)] #[deprecated(since = "0.1.16", note = "Use pool::Pool instead")] pub use super::pool::Pool; #[doc(hidden)] #[deprecated(since = "0.1.16", note = "Use pool::Receiver instead")] pub use super::pool::Receiver as PReceiver; #[doc(hidden)] #[deprecated(since = "0.1.16", note = "Use pool::Sender instead")] pub use super::pool::Sender as PSender; /// Creates a new futures-aware, one-shot channel. pub fn channel<T>() -> (Sender<T>, Receiver<T>) { let inner = Cell::new(Inner { value: None, rx_task: LocalWaker::new(), }); let tx = Sender { inner: inner.clone(), }; let rx = Receiver { inner }; (tx, rx) } /// Represents the completion half of a oneshot through which the result of a /// computation is signaled. #[derive(Debug)] pub struct Sender<T> { inner: Cell<Inner<T>>, } /// A future representing the completion of a computation happening elsewhere in /// memory. #[derive(Debug)] #[must_use = "futures do nothing unless polled"] pub struct Receiver<T> { inner: Cell<Inner<T>>, } // The channels do not ever project Pin to the inner T impl<T> Unpin for Receiver<T> {} impl<T> Unpin for Sender<T> {} #[derive(Debug)] struct Inner<T> { value: Option<T>, rx_task: LocalWaker, } impl<T> Sender<T> { /// Completes this oneshot with a successful result. /// /// This function will consume `self` and indicate to the other end, the /// `Receiver`, that the error provided is the result of the computation this /// represents. /// /// If the value is successfully enqueued for the remote end to receive, /// then `Ok(())` is returned. If the receiving end was dropped before /// this function was called, however, then `Err` is returned with the value /// provided. pub fn send(self, val: T) -> Result<(), T> { if self.inner.strong_count() == 2 { let inner = self.inner.get_mut(); inner.value = Some(val); inner.rx_task.wake(); Ok(()) } else { Err(val) } } /// Tests to see whether this `Sender`'s corresponding `Receiver` /// has gone away. pub fn is_canceled(&self) -> bool { self.inner.strong_count() == 1 } } impl<T> Drop for Sender<T> { fn drop(&mut self) { self.inner.get_ref().rx_task.wake(); } } impl<T> Future for Receiver<T> { type Output = Result<T, Canceled>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); // If we've got a value, then skip the logic below as we're done. if let Some(val) = this.inner.get_mut().value.take() { return Poll::Ready(Ok(val)); } // Check if sender is dropped and return error if it is. if this.inner.strong_count() == 1 { Poll::Ready(Err(Canceled)) } else { this.inner.get_ref().rx_task.register(cx.waker()); Poll::Pending } } } #[cfg(test)] mod tests { use super::*; use futures::future::lazy; #[ntex_rt::test] async fn test_oneshot() { let (tx, rx) = channel(); tx.send("test").unwrap(); assert_eq!(rx.await.unwrap(), "test"); let (tx, rx) = channel(); assert!(!tx.is_canceled()); drop(rx); assert!(tx.is_canceled()); assert!(tx.send("test").is_err()); let (tx, rx) = channel::<&'static str>(); drop(tx); assert!(rx.await.is_err()); let (tx, mut rx) = channel::<&'static str>(); assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending); tx.send("test").unwrap(); assert_eq!(rx.await.unwrap(), "test"); let (tx, mut rx) = channel::<&'static str>(); assert_eq!(lazy(|cx| Pin::new(&mut rx).poll(cx)).await, Poll::Pending); drop(tx); assert!(rx.await.is_err()); } }
28.44
81
0.584857
759b0ccc84072eadaac926f1b747b642bed4af9d
4,722
use tide::http::{headers, Method, Request, StatusCode, Url}; use tide::Response; const TEXT: &str = concat![ "Chunk one\n", "data data\n", "\n", "Chunk two\n", "data data\n", "\n", "Chunk three\n", "data data\n", ]; const BR_COMPRESSED: &[u8] = &[ 27, 63, 0, 248, 157, 9, 118, 12, 101, 50, 101, 248, 252, 26, 229, 16, 90, 93, 43, 144, 189, 209, 105, 5, 16, 55, 58, 200, 132, 35, 141, 117, 16, 5, 199, 247, 22, 131, 0, 51, 145, 60, 128, 132, 79, 166, 110, 169, 162, 169, 129, 224, 63, 191, 0, ]; #[async_std::test] async fn brotli_compressed() { let mut app = tide::new(); app.with(tide_compress::CompressMiddleware::with_threshold(16)); app.at("/").get(|_| async { let mut res = Response::new(StatusCode::Ok); res.set_body(TEXT.to_owned()); Ok(res) }); let mut req = Request::new(Method::Get, Url::parse("http://_/").unwrap()); req.insert_header(headers::ACCEPT_ENCODING, "br"); let mut res: tide::http::Response = app.respond(req).await.unwrap(); assert_eq!(res.status(), 200); assert!(res.header(headers::CONTENT_LENGTH).is_none()); assert_eq!(res[headers::CONTENT_ENCODING], "br"); assert_eq!(res[headers::VARY], "accept-encoding"); assert_eq!(res.body_bytes().await.unwrap(), BR_COMPRESSED); } const GZIPPED: &[u8] = &[ // It should be this but miniz_oxide's gzip compression doesn't always pick the best huffman codes. // // See https://github.com/Frommi/miniz_oxide/issues/77 // // 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // gzip header // 0xff, // OS type // // Same as DEFLATE // 0x73, 0xce, 0x28, 0xcd, 0xcb, 0x56, 0xc8, 0xcf, 0x4b, 0xe5, 0x4a, 0x49, 0x2c, 0x49, 0x54, 0x00, 0x11, // 0x5c, 0x5c, 0xce, 0x60, 0xc1, 0x92, 0xf2, 0x7c, 0x2c, 0x82, 0x19, 0x45, 0xa9, 0xc8, 0x6a, 0x01, // 0xde, 0xf2, 0xd7, 0x81, // crc32 // 0x40, 0x00, 0x00, 0x00 // input size // 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // gzip header 0xff, // OS type // Same as DEFLATE // 109, 202, 177, 9, 0, 48, 8, 5, 209, 254, 79, 225, 46, 78, 34, 68, 16, 2, 10, 193, 144, 245, 67, // 82, 89, 216, 92, 241, 56, 182, 237, 147, 194, 21, 67, 82, 232, 5, 224, 143, 121, 162, 65, 91, // 90, 223, 11, 0x6d, 0xca, 0xb1, 0x09, 0x00, 0x30, 0x08, 0x05, 0xd1, 0xfe, 0x4f, 0xe1, 0x2e, 0x4e, 0x22, 0x44, 0x10, 0x02, 0x0a, 0xc1, 0x90, 0xf5, 0x43, 0x52, 0x59, 0xd8, 0x5c, 0xf1, 0x38, 0xb6, 0xed, 0x93, 0xc2, 0x15, 0x43, 0x52, 0xe8, 0x05, 0xe0, 0x8f, 0x79, 0xa2, 0x41, 0x5b, 0x5a, 0xdf, 0x0b, // 0xde, 0xf2, 0xd7, 0x81, // crc32 0x40, 0x00, 0x00, 0x00, // input size ]; #[async_std::test] async fn gzip_compressed() { let mut app = tide::new(); app.with(tide_compress::CompressMiddleware::with_threshold(16)); app.at("/").get(|_| async move { let mut res = Response::new(StatusCode::Ok); res.set_body(TEXT.to_owned()); res.insert_header(headers::CONTENT_ENCODING, "identity"); Ok(res) }); let mut req = Request::new(Method::Get, Url::parse("http://_/").unwrap()); req.insert_header(headers::ACCEPT_ENCODING, "gzip"); let mut res: tide::http::Response = app.respond(req).await.unwrap(); assert_eq!(res.status(), 200); assert!(res.header(headers::CONTENT_LENGTH).is_none()); assert_eq!(res[headers::CONTENT_ENCODING], "gzip"); assert_eq!(res[headers::VARY], "accept-encoding"); assert_eq!(res.body_bytes().await.unwrap(), GZIPPED); } #[cfg(feature = "deflate")] const DEFLATED: &'static [u8] = &[ 0x6d, 0xca, 0xb1, 0x09, 0x00, 0x30, 0x08, 0x05, 0xd1, 0xfe, 0x4f, 0xe1, 0x2e, 0x4e, 0x22, 0x44, 0x10, 0x02, 0x0a, 0xc1, 0x90, 0xf5, 0x43, 0x52, 0x59, 0xd8, 0x5c, 0xf1, 0x38, 0xb6, 0xed, 0x93, 0xc2, 0x15, 0x43, 0x52, 0xe8, 0x05, 0xe0, 0x8f, 0x79, 0xa2, 0x41, 0x5b, 0x5a, 0xdf, 0x0b, ]; #[cfg(feature = "deflate")] #[async_std::test] async fn deflate_compressed() { let mut app = tide::new(); app.with(tide_compress::CompressMiddleware::with_threshold(16)); app.at("/").get(|_| async { let mut res = Response::new(StatusCode::Ok); res.set_body(TEXT.to_owned()); Ok(res) }); let mut req = Request::new(Method::Get, Url::parse("http://_/").unwrap()); req.insert_header(headers::ACCEPT_ENCODING, "deflate"); let mut res: tide::http::Response = app.respond(req).await.unwrap(); assert_eq!(res.status(), 200); assert!(res.header(headers::CONTENT_LENGTH).is_none()); assert_eq!(res[headers::CONTENT_ENCODING], "deflate"); assert_eq!(res[headers::VARY], "accept-encoding"); assert_eq!(res.body_bytes().await.unwrap(), DEFLATED); }
39.680672
112
0.610335
87a737e2fa1d47b6f050748a3e76c6abf124193e
182
use pin_project_lite::pin_project; pin_project! { //~ ERROR E0496 pub struct Foo<'__pin, T> { //~ ERROR E0263 #[pin] field: &'__pin mut T, } } fn main() {}
16.545455
47
0.56044
29304cf26ebfbb20b99e269c7cf647f62972ce80
2,957
use aoc_template::{days::*, solver::Solver}; use std::{fmt::Debug, time::Instant}; const YEAR: &str = "_template"; #[cfg(debug_assertions)] #[global_allocator] static ALLOCATOR: dhat::DhatAlloc = dhat::DhatAlloc; macro_rules! day { ( $d:expr ) => { day!($d => None, None); }; ( $d:expr, $o1:expr ) => { day!($d => Some($o1), None); }; ( $d:expr, $o1:expr, $o2:expr ) => { day!($d => Some($o1), Some($o2)); }; ( $d:expr => $o1:expr, $o2:expr ) => { paste::expr! { solve::<_, _, [<day $d>]::[<Day $d>]>($d, $o1, $o2); } }; } fn main() { #[cfg(debug_assertions)] let _dhat = dhat::Dhat::start_heap_profiling(); println!("AOC {}", YEAR); } fn solve<O, O2, S: for<'a> Solver<'a, Output = O, Output2 = O2>>( day_number: u8, part1_output: Option<O>, part2_output: Option<O2>, ) { let input = std::fs::read_to_string(format!("input/{}/day{}.txt", YEAR, day_number)).unwrap(); let trimmed = input.trim(); let mut args = std::env::args(); if args.len() > 1 { let day_as_str = day_number.to_string(); if args.any(|x| x == day_as_str || x == "a") { bench::<S>(day_number, trimmed); } } else { run::<S>(day_number, trimmed, part1_output, part2_output); } } fn run<'a, S: Solver<'a>>( day_number: u8, input: &'a str, part1_output: Option<S::Output>, part2_output: Option<S::Output2>, ) { let start_time = Instant::now(); let parsed = S::parse(input); let end_time = Instant::now(); println!("\nDay {}:", day_number); println!("\tparser: {:?}", (end_time - start_time)); run_part(parsed.clone(), 1, S::part1, part1_output); run_part(parsed, 2, S::part2, part2_output); } fn run_part<P, O: Debug + PartialEq>( parsed: P, part_number: u8, part: impl Fn(P) -> O, expected_output: Option<O>, ) { print!("Part {}: ", part_number); let start_time = Instant::now(); let result = part(parsed); let end_time = Instant::now(); println!("{:?}", result); println!("\tsolver: {:?}", (end_time - start_time)); if let Some(expected) = expected_output { assert_eq!(expected, result); } else { println!("Not checking result!"); } } fn bench<'a, S: Solver<'a>>(day_number: u8, input: &'a str) { let mut criterion = criterion::Criterion::default().without_plots(); let mut group = criterion.benchmark_group(format!("Day {}", day_number)); group.bench_with_input("parser", &input, |b, i| { b.iter_with_large_drop(|| S::parse(i)); }); let parsed = S::parse(input); group.bench_with_input("part 1", &parsed, |b, i| { b.iter_batched(|| i.clone(), S::part1, criterion::BatchSize::SmallInput) }); group.bench_with_input("part 2", &parsed, |b, i| { b.iter_batched(|| i.clone(), S::part2, criterion::BatchSize::SmallInput) }); }
26.168142
98
0.560365
0e15d22d19602d18e751418577ec2ce28d639bcf
1,532
use cargo::core::compiler::CompileMode; use clap::arg_enum; use coveralls_api::CiService; use std::str::FromStr; use void::Void; arg_enum! { #[derive(Debug, Copy, Clone, PartialEq, Eq, Ord, PartialOrd)] pub enum RunType { Tests, Doctests, Benchmarks, Examples, } } arg_enum! { #[derive(Debug)] pub enum OutputFile { Json, Toml, Stdout, Xml, Html, Lcov, } } impl Default for OutputFile { #[inline] fn default() -> Self { OutputFile::Stdout } } pub struct Ci(pub CiService); impl From<RunType> for CompileMode { fn from(run: RunType) -> Self { match run { RunType::Tests => CompileMode::Test, RunType::Examples => CompileMode::Build, RunType::Doctests => CompileMode::Doctest, RunType::Benchmarks => CompileMode::Bench, } } } impl FromStr for Ci { /// This can never fail, so the error type is uninhabited. type Err = Void; #[inline] fn from_str(x: &str) -> Result<Ci, Self::Err> { match x { "circle-ci" => Ok(Ci(CiService::Circle)), "codeship" => Ok(Ci(CiService::Codeship)), "jenkins" => Ok(Ci(CiService::Jenkins)), "semaphore" => Ok(Ci(CiService::Semaphore)), "travis-ci" => Ok(Ci(CiService::Travis)), "travis-pro" => Ok(Ci(CiService::TravisPro)), other => Ok(Ci(CiService::Other(other.to_string()))), } } }
23.212121
65
0.54765
099a934e33cfdb515eaea41dc48819b9a7134601
12,655
//! Tool for manually assigning partitions use std::hash::{BuildHasher, Hash, Hasher}; use crc::crc64::{Digest, ISO}; use crate::api::{MonitoringApi, NakadiApiError}; use crate::nakadi_types::{ RandomFlowId, { event::publishable::{BusinessEventPub, DataChangeEventPub}, event_type::EventTypeName, partition::PartitionId, }, }; /// The default hasher used is [crc64::ISO](https://docs.rs/crc/1.9.0/crc/crc64/constant.ISO.html) #[derive(Clone)] pub struct DefaultBuildHasher; impl BuildHasher for DefaultBuildHasher { type Hasher = Digest; fn build_hasher(&self) -> Self::Hasher { Digest::new(ISO) } } /// Determines partitions based on hashes #[derive(Clone)] pub struct Partitioner<B: BuildHasher + Clone = DefaultBuildHasher> { partitions: Vec<PartitionId>, build_hasher: B, } impl Partitioner<DefaultBuildHasher> { /// Create a new instance with the given partitions. /// /// The order of the given partitions will not be changed. /// /// ## Panics /// /// If partitions is empty pub fn new(partitions: Vec<PartitionId>) -> Self { Self::new_with_hasher(partitions, DefaultBuildHasher) } /// Create a new instance with the given partitions. /// /// The partitions will be sorted by first trying to convert /// the partitions to numbers and sorting by these. Otherwise /// they will be sorted ba their contained string. /// /// ## Panics /// /// If partitions is empty pub fn new_sorted(partitions: Vec<PartitionId>) -> Self { Self::new_sorted_with_hasher(partitions, DefaultBuildHasher) } /// Create a new instance for the partitions of the /// given event type. /// /// The partitions will be sorted by first trying to convert /// the partitions to numbers and sorting by these. Otherwise /// they will be sorted ba their contained string. /// /// Fails if the event type has no partitions. pub async fn from_event_type<C>( event_type: &EventTypeName, api_client: &C, ) -> Result<Self, NakadiApiError> where C: MonitoringApi, { Self::from_event_type_with_hasher(event_type, api_client, DefaultBuildHasher).await } } impl<B> Partitioner<B> where B: BuildHasher + Clone, { /// Create a new instance with the given partitions and a provided /// hashing algorithm. /// /// The order of the given partitions will not be changed. /// /// ## Panics /// /// If partitions is empty pub fn new_with_hasher(partitions: Vec<PartitionId>, build_hasher: B) -> Self { assert!(!partitions.is_empty(), "partitions may not be empty"); Self { partitions, build_hasher, } } /// Create a new instance with the given partitions and a provided /// hashing algorithm. /// /// The partitions will be sorted by first trying to convert /// the partitions to numbers and sorting by these. Otherwise /// they will be sorted by their string representation. /// /// ## Panics /// /// If partitions is empty pub fn new_sorted_with_hasher(partitions: Vec<PartitionId>, build_hasher: B) -> Self { create_sorted_partitioner(partitions, build_hasher) } /// Create a new instance for the partitions of the /// given event type and a provided hashing algorithm. /// /// The partitions will be sorted by first trying to convert /// the partitions to numbers and sorting by these. Otherwise /// they will be sorted by their string representation. /// /// Fails if the event type has no partitions. pub async fn from_event_type_with_hasher<C>( event_type: &EventTypeName, api_client: &C, build_hasher: B, ) -> Result<Self, NakadiApiError> where C: MonitoringApi, { let partitions = api_client .get_event_type_partitions(event_type, RandomFlowId) .await?; if partitions.is_empty() { // Would be strange if Nakadi allowed this... return Err(NakadiApiError::other().with_context( "A partitioner can not be created from an event type without partitions", )); } let partitions: Vec<PartitionId> = partitions.into_iter().map(|p| p.partition).collect(); Ok(create_sorted_partitioner(partitions, build_hasher)) } /// Returns the partition that matches the given key pub fn partition_for_key<H>(&self, partition_key: &H) -> &PartitionId where H: Hash, { let mut hasher = self.build_hasher.build_hasher(); partition_key.hash(&mut hasher); partition_for_hash(&self.partitions, hasher.finish()) } /// Determines and assigns partitions pub fn assign<E: PartitionKeyExtractable + PartitionAssignable>(&self, event: &mut E) { let key = event.partition_key(); let partition = self.partition_for_key(&key); event.assign_partition(partition); } /// Returns the partitions as used by the `Partitioner` pub fn partitions(&self) -> &[PartitionId] { &self.partitions } } /// Can return a key for manual partitioning pub trait PartitionKeyExtractable { type Key: Hash; /// Returns the key for partitioning fn partition_key(&self) -> Self::Key; } /// Can be assigned a partition pub trait PartitionAssignable { /// Assign a partition. fn assign_partition(&mut self, partition: &PartitionId); } impl<D> PartitionAssignable for BusinessEventPub<D> { fn assign_partition(&mut self, partition: &PartitionId) { self.metadata.partition = Some(partition.clone()); } } impl<D> PartitionAssignable for DataChangeEventPub<D> { fn assign_partition(&mut self, partition: &PartitionId) { self.metadata.partition = Some(partition.clone()); } } impl<D> PartitionKeyExtractable for BusinessEventPub<D> where D: PartitionKeyExtractable, { type Key = D::Key; fn partition_key(&self) -> Self::Key { self.data.partition_key() } } impl<D> PartitionKeyExtractable for DataChangeEventPub<D> where D: PartitionKeyExtractable, { type Key = D::Key; fn partition_key(&self) -> Self::Key { self.data.partition_key() } } fn create_sorted_partitioner<B: BuildHasher + Clone>( mut partitions: Vec<PartitionId>, build_hasher: B, ) -> Partitioner<B> { let ids_and_ints: Result<Vec<_>, _> = partitions .iter() .map(|id| id.as_str().parse::<u64>().map(|n| (id, n))) .collect(); if let Ok(mut ids_and_ints) = ids_and_ints { ids_and_ints.sort_by_key(|x| x.1); Partitioner::new_with_hasher( ids_and_ints.into_iter().map(|(p, _)| p.clone()).collect(), build_hasher, ) } else { partitions.sort(); Partitioner::new_sorted_with_hasher(partitions, build_hasher) } } fn partition_for_hash<P>(partitions: &[P], hash: u64) -> &P { let idx = hash % (partitions.len() as u64); &partitions[idx as usize] } #[test] fn partition_for_for_hash_assigns_correctly() { let partitions = &[1u32, 2, 3]; assert_eq!(*partition_for_hash(partitions, 0), 1); assert_eq!(*partition_for_hash(partitions, 1), 2); assert_eq!(*partition_for_hash(partitions, 2), 3); assert_eq!(*partition_for_hash(partitions, 3), 1); assert_eq!(*partition_for_hash(partitions, 4), 2); assert_eq!(*partition_for_hash(partitions, 5), 3); } #[cfg(test)] mod tests_with_default_hasher { use super::*; #[derive(Clone, Copy)] struct CustomHashes(&'static str); impl std::hash::Hash for CustomHashes { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.0.as_bytes().hash(state) } } #[test] fn hasher_is_stable() { // WARNING! If this test fails behaviour of components // using the DefaultBuildHasher will change in a seriously // broken way! let sample_keys = [ (CustomHashes("HE742A011-Q110010000"), 8382545129338073832u64), (CustomHashes("PU143E0A9-Q110152000"), 2242809023958206461), (CustomHashes("EV421T048-Q11000L000"), 14780139298840732394), (CustomHashes("M5921E05S-Q1100XL000"), 14777921106714327039), (CustomHashes("INL81R01D-A11000S000"), 13851497914756523380), (CustomHashes("AD121G084-G110034000"), 14774336303094658421), (CustomHashes("AD541D1FZ-J11000S000"), 14545158386393691066), (CustomHashes("MQ581A002-Q11000S000"), 13866904338030752491), (CustomHashes("ZZO0UCT55-G00046FB4A"), 16561860853217772572), (CustomHashes("ORJ21C05M-K110040000"), 14797538103842336865), (CustomHashes("ZZO0TXN53-N00046AAAF"), 10014478766256073642), (CustomHashes("AD581A007-A11000S000"), 13863609120258880235), ]; for &(sample, expected_hash) in sample_keys.iter() { let mut hasher = DefaultBuildHasher.build_hasher(); sample.hash(&mut hasher); let sample_hash = hasher.finish(); assert_eq!(sample_hash, expected_hash, "{}", sample.0); } } #[test] fn get_partitions_by_hash() { let sample_keys = [ (CustomHashes("HE742A011-Q110010000"), PartitionId::new("0")), (CustomHashes("PU143E0A9-Q110152000"), PartitionId::new("1")), (CustomHashes("EV421T048-Q11000L000"), PartitionId::new("2")), (CustomHashes("M5921E05S-Q1100XL000"), PartitionId::new("3")), (CustomHashes("INL81R01D-A11000S000"), PartitionId::new("4")), (CustomHashes("AD121G084-G110034000"), PartitionId::new("5")), (CustomHashes("AD541D1FZ-J11000S000"), PartitionId::new("6")), (CustomHashes("MQ581A002-Q11000S000"), PartitionId::new("7")), (CustomHashes("ZZO0UCT55-G00046FB4A"), PartitionId::new("8")), (CustomHashes("ORJ21C05M-K110040000"), PartitionId::new("9")), (CustomHashes("ZZO0TXN53-N00046AAAF"), PartitionId::new("10")), (CustomHashes("AD581A007-A11000S000"), PartitionId::new("11")), ]; let partitions: Vec<_> = sample_keys.iter().map(|s| s.1.clone()).collect(); let partitioner = Partitioner::new_sorted(partitions); for (sample_key, expected_partition) in sample_keys.iter() { let assigned_partition = partitioner.partition_for_key(sample_key); assert_eq!(assigned_partition, expected_partition); } } #[test] fn assign_partitions_by_hash() { let sample_keys = [ (CustomHashes("HE742A011-Q110010000"), PartitionId::new("0")), (CustomHashes("PU143E0A9-Q110152000"), PartitionId::new("1")), (CustomHashes("EV421T048-Q11000L000"), PartitionId::new("2")), (CustomHashes("M5921E05S-Q1100XL000"), PartitionId::new("3")), (CustomHashes("INL81R01D-A11000S000"), PartitionId::new("4")), (CustomHashes("AD121G084-G110034000"), PartitionId::new("5")), (CustomHashes("AD541D1FZ-J11000S000"), PartitionId::new("6")), (CustomHashes("MQ581A002-Q11000S000"), PartitionId::new("7")), (CustomHashes("ZZO0UCT55-G00046FB4A"), PartitionId::new("8")), (CustomHashes("ORJ21C05M-K110040000"), PartitionId::new("9")), (CustomHashes("ZZO0TXN53-N00046AAAF"), PartitionId::new("10")), (CustomHashes("AD581A007-A11000S000"), PartitionId::new("11")), ]; struct EventSample { key: CustomHashes, partition: Option<PartitionId>, } impl PartitionAssignable for EventSample { fn assign_partition(&mut self, partition: &PartitionId) { self.partition = Some(partition.clone()); } } impl PartitionKeyExtractable for EventSample { type Key = CustomHashes; fn partition_key(&self) -> Self::Key { self.key } } let partitions: Vec<_> = sample_keys.iter().map(|s| s.1.clone()).collect(); let partitioner = Partitioner::new_sorted(partitions); for (sample_key, expected_partition) in sample_keys.iter() { let mut event_sample = EventSample { key: *sample_key, partition: None, }; partitioner.assign(&mut event_sample); assert_eq!(event_sample.partition.as_ref(), Some(expected_partition)); } } }
34.110512
98
0.630976
76d324e56a09b711da48de6fd742c504eaeb01ea
407,859
//! Autogenerated: 'src/ExtractionOCaml/word_by_word_montgomery' --lang Rust p384 32 '2^384 - 2^128 - 2^96 + 2^32 - 1' mul square add sub opp from_montgomery to_montgomery nonzero selectznz to_bytes from_bytes one msat divstep divstep_precomp //! curve description: p384 //! machine_wordsize = 32 (from "32") //! requested operations: mul, square, add, sub, opp, from_montgomery, to_montgomery, nonzero, selectznz, to_bytes, from_bytes, one, msat, divstep, divstep_precomp //! m = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff (from "2^384 - 2^128 - 2^96 + 2^32 - 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] << 32) + (z[2] << 64) + (z[3] << 96) + (z[4] << 128) + (z[5] << 160) + (z[6] << 192) + (z[7] << 224) + (z[8] << 256) + (z[9] << 0x120) + (z[10] << 0x140) + (z[11] << 0x160) //! 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) #![allow(unused_parens)] #[allow(non_camel_case_types)] pub type fiat_p384_u1 = u8; pub type fiat_p384_i1 = i8; pub type fiat_p384_u2 = u8; pub type fiat_p384_i2 = i8; /// The function fiat_p384_addcarryx_u32 is an addition with carry. /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^32 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_p384_addcarryx_u32(out1: &mut u32, out2: &mut fiat_p384_u1, arg1: fiat_p384_u1, arg2: u32, arg3: u32) -> () { let x1: u64 = (((arg1 as u64) + (arg2 as u64)) + (arg3 as u64)); let x2: u32 = ((x1 & (0xffffffff as u64)) as u32); let x3: fiat_p384_u1 = ((x1 >> 32) as fiat_p384_u1); *out1 = x2; *out2 = x3; } /// The function fiat_p384_subborrowx_u32 is a subtraction with borrow. /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^32 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0x1] #[inline] pub fn fiat_p384_subborrowx_u32(out1: &mut u32, out2: &mut fiat_p384_u1, arg1: fiat_p384_u1, arg2: u32, arg3: u32) -> () { let x1: i64 = (((arg2 as i64) - (arg1 as i64)) - (arg3 as i64)); let x2: fiat_p384_i1 = ((x1 >> 32) as fiat_p384_i1); let x3: u32 = ((x1 & (0xffffffff as i64)) as u32); *out1 = x3; *out2 = (((0x0 as fiat_p384_i2) - (x2 as fiat_p384_i2)) as fiat_p384_u1); } /// The function fiat_p384_mulx_u32 is a multiplication, returning the full double-width result. /// Postconditions: /// out1 = (arg1 * arg2) mod 2^32 /// out2 = ⌊arg1 * arg2 / 2^32⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffff] /// arg2: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_p384_mulx_u32(out1: &mut u32, out2: &mut u32, arg1: u32, arg2: u32) -> () { let x1: u64 = ((arg1 as u64) * (arg2 as u64)); let x2: u32 = ((x1 & (0xffffffff as u64)) as u32); let x3: u32 = ((x1 >> 32) as u32); *out1 = x2; *out2 = x3; } /// The function fiat_p384_cmovznz_u32 is a single-word conditional move. /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffff] /// arg3: [0x0 ~> 0xffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_p384_cmovznz_u32(out1: &mut u32, arg1: fiat_p384_u1, arg2: u32, arg3: u32) -> () { let x1: fiat_p384_u1 = (!(!arg1)); let x2: u32 = ((((((0x0 as fiat_p384_i2) - (x1 as fiat_p384_i2)) as fiat_p384_i1) as i64) & (0xffffffff as i64)) as u32); let x3: u32 = ((x2 & arg3) | ((!x2) & arg2)); *out1 = x3; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_mul(out1: &mut [u32; 12], arg1: &[u32; 12], arg2: &[u32; 12]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[8]); let x9: u32 = (arg1[9]); let x10: u32 = (arg1[10]); let x11: u32 = (arg1[11]); let x12: u32 = (arg1[0]); let mut x13: u32 = 0; let mut x14: u32 = 0; fiat_p384_mulx_u32(&mut x13, &mut x14, x12, (arg2[11])); let mut x15: u32 = 0; let mut x16: u32 = 0; fiat_p384_mulx_u32(&mut x15, &mut x16, x12, (arg2[10])); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_p384_mulx_u32(&mut x17, &mut x18, x12, (arg2[9])); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_p384_mulx_u32(&mut x19, &mut x20, x12, (arg2[8])); let mut x21: u32 = 0; let mut x22: u32 = 0; fiat_p384_mulx_u32(&mut x21, &mut x22, x12, (arg2[7])); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_p384_mulx_u32(&mut x23, &mut x24, x12, (arg2[6])); let mut x25: u32 = 0; let mut x26: u32 = 0; fiat_p384_mulx_u32(&mut x25, &mut x26, x12, (arg2[5])); let mut x27: u32 = 0; let mut x28: u32 = 0; fiat_p384_mulx_u32(&mut x27, &mut x28, x12, (arg2[4])); let mut x29: u32 = 0; let mut x30: u32 = 0; fiat_p384_mulx_u32(&mut x29, &mut x30, x12, (arg2[3])); let mut x31: u32 = 0; let mut x32: u32 = 0; fiat_p384_mulx_u32(&mut x31, &mut x32, x12, (arg2[2])); let mut x33: u32 = 0; let mut x34: u32 = 0; fiat_p384_mulx_u32(&mut x33, &mut x34, x12, (arg2[1])); let mut x35: u32 = 0; let mut x36: u32 = 0; fiat_p384_mulx_u32(&mut x35, &mut x36, x12, (arg2[0])); let mut x37: u32 = 0; let mut x38: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x37, &mut x38, 0x0, x36, x33); let mut x39: u32 = 0; let mut x40: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x39, &mut x40, x38, x34, x31); let mut x41: u32 = 0; let mut x42: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x41, &mut x42, x40, x32, x29); let mut x43: u32 = 0; let mut x44: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x43, &mut x44, x42, x30, x27); let mut x45: u32 = 0; let mut x46: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x45, &mut x46, x44, x28, x25); let mut x47: u32 = 0; let mut x48: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x47, &mut x48, x46, x26, x23); let mut x49: u32 = 0; let mut x50: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x49, &mut x50, x48, x24, x21); let mut x51: u32 = 0; let mut x52: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x51, &mut x52, x50, x22, x19); let mut x53: u32 = 0; let mut x54: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x53, &mut x54, x52, x20, x17); let mut x55: u32 = 0; let mut x56: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x55, &mut x56, x54, x18, x15); let mut x57: u32 = 0; let mut x58: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x57, &mut x58, x56, x16, x13); let x59: u32 = ((x58 as u32) + x14); let mut x60: u32 = 0; let mut x61: u32 = 0; fiat_p384_mulx_u32(&mut x60, &mut x61, x35, 0xffffffff); let mut x62: u32 = 0; let mut x63: u32 = 0; fiat_p384_mulx_u32(&mut x62, &mut x63, x35, 0xffffffff); let mut x64: u32 = 0; let mut x65: u32 = 0; fiat_p384_mulx_u32(&mut x64, &mut x65, x35, 0xffffffff); let mut x66: u32 = 0; let mut x67: u32 = 0; fiat_p384_mulx_u32(&mut x66, &mut x67, x35, 0xffffffff); let mut x68: u32 = 0; let mut x69: u32 = 0; fiat_p384_mulx_u32(&mut x68, &mut x69, x35, 0xffffffff); let mut x70: u32 = 0; let mut x71: u32 = 0; fiat_p384_mulx_u32(&mut x70, &mut x71, x35, 0xffffffff); let mut x72: u32 = 0; let mut x73: u32 = 0; fiat_p384_mulx_u32(&mut x72, &mut x73, x35, 0xffffffff); let mut x74: u32 = 0; let mut x75: u32 = 0; fiat_p384_mulx_u32(&mut x74, &mut x75, x35, 0xfffffffe); let mut x76: u32 = 0; let mut x77: u32 = 0; fiat_p384_mulx_u32(&mut x76, &mut x77, x35, 0xffffffff); let mut x78: u32 = 0; let mut x79: u32 = 0; fiat_p384_mulx_u32(&mut x78, &mut x79, x35, 0xffffffff); let mut x80: u32 = 0; let mut x81: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x80, &mut x81, 0x0, x77, x74); let mut x82: u32 = 0; let mut x83: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x82, &mut x83, x81, x75, x72); let mut x84: u32 = 0; let mut x85: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x84, &mut x85, x83, x73, x70); let mut x86: u32 = 0; let mut x87: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x86, &mut x87, x85, x71, x68); let mut x88: u32 = 0; let mut x89: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x88, &mut x89, x87, x69, x66); let mut x90: u32 = 0; let mut x91: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x90, &mut x91, x89, x67, x64); let mut x92: u32 = 0; let mut x93: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x92, &mut x93, x91, x65, x62); let mut x94: u32 = 0; let mut x95: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x94, &mut x95, x93, x63, x60); let x96: u32 = ((x95 as u32) + x61); let mut x97: u32 = 0; let mut x98: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x97, &mut x98, 0x0, x35, x78); let mut x99: u32 = 0; let mut x100: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x99, &mut x100, x98, x37, x79); let mut x101: u32 = 0; let mut x102: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x101, &mut x102, x100, x39, (0x0 as u32)); let mut x103: u32 = 0; let mut x104: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x103, &mut x104, x102, x41, x76); let mut x105: u32 = 0; let mut x106: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x105, &mut x106, x104, x43, x80); let mut x107: u32 = 0; let mut x108: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x107, &mut x108, x106, x45, x82); let mut x109: u32 = 0; let mut x110: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x109, &mut x110, x108, x47, x84); let mut x111: u32 = 0; let mut x112: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x111, &mut x112, x110, x49, x86); let mut x113: u32 = 0; let mut x114: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x113, &mut x114, x112, x51, x88); let mut x115: u32 = 0; let mut x116: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x115, &mut x116, x114, x53, x90); let mut x117: u32 = 0; let mut x118: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x117, &mut x118, x116, x55, x92); let mut x119: u32 = 0; let mut x120: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x119, &mut x120, x118, x57, x94); let mut x121: u32 = 0; let mut x122: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x121, &mut x122, x120, x59, x96); let mut x123: u32 = 0; let mut x124: u32 = 0; fiat_p384_mulx_u32(&mut x123, &mut x124, x1, (arg2[11])); let mut x125: u32 = 0; let mut x126: u32 = 0; fiat_p384_mulx_u32(&mut x125, &mut x126, x1, (arg2[10])); let mut x127: u32 = 0; let mut x128: u32 = 0; fiat_p384_mulx_u32(&mut x127, &mut x128, x1, (arg2[9])); let mut x129: u32 = 0; let mut x130: u32 = 0; fiat_p384_mulx_u32(&mut x129, &mut x130, x1, (arg2[8])); let mut x131: u32 = 0; let mut x132: u32 = 0; fiat_p384_mulx_u32(&mut x131, &mut x132, x1, (arg2[7])); let mut x133: u32 = 0; let mut x134: u32 = 0; fiat_p384_mulx_u32(&mut x133, &mut x134, x1, (arg2[6])); let mut x135: u32 = 0; let mut x136: u32 = 0; fiat_p384_mulx_u32(&mut x135, &mut x136, x1, (arg2[5])); let mut x137: u32 = 0; let mut x138: u32 = 0; fiat_p384_mulx_u32(&mut x137, &mut x138, x1, (arg2[4])); let mut x139: u32 = 0; let mut x140: u32 = 0; fiat_p384_mulx_u32(&mut x139, &mut x140, x1, (arg2[3])); let mut x141: u32 = 0; let mut x142: u32 = 0; fiat_p384_mulx_u32(&mut x141, &mut x142, x1, (arg2[2])); let mut x143: u32 = 0; let mut x144: u32 = 0; fiat_p384_mulx_u32(&mut x143, &mut x144, x1, (arg2[1])); let mut x145: u32 = 0; let mut x146: u32 = 0; fiat_p384_mulx_u32(&mut x145, &mut x146, x1, (arg2[0])); let mut x147: u32 = 0; let mut x148: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x147, &mut x148, 0x0, x146, x143); let mut x149: u32 = 0; let mut x150: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x149, &mut x150, x148, x144, x141); let mut x151: u32 = 0; let mut x152: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x151, &mut x152, x150, x142, x139); let mut x153: u32 = 0; let mut x154: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x153, &mut x154, x152, x140, x137); let mut x155: u32 = 0; let mut x156: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x155, &mut x156, x154, x138, x135); let mut x157: u32 = 0; let mut x158: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x157, &mut x158, x156, x136, x133); let mut x159: u32 = 0; let mut x160: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x159, &mut x160, x158, x134, x131); let mut x161: u32 = 0; let mut x162: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x161, &mut x162, x160, x132, x129); let mut x163: u32 = 0; let mut x164: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x163, &mut x164, x162, x130, x127); let mut x165: u32 = 0; let mut x166: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x165, &mut x166, x164, x128, x125); let mut x167: u32 = 0; let mut x168: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x167, &mut x168, x166, x126, x123); let x169: u32 = ((x168 as u32) + x124); let mut x170: u32 = 0; let mut x171: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x170, &mut x171, 0x0, x99, x145); let mut x172: u32 = 0; let mut x173: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x172, &mut x173, x171, x101, x147); let mut x174: u32 = 0; let mut x175: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x174, &mut x175, x173, x103, x149); let mut x176: u32 = 0; let mut x177: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x176, &mut x177, x175, x105, x151); let mut x178: u32 = 0; let mut x179: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x178, &mut x179, x177, x107, x153); let mut x180: u32 = 0; let mut x181: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x180, &mut x181, x179, x109, x155); let mut x182: u32 = 0; let mut x183: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x182, &mut x183, x181, x111, x157); let mut x184: u32 = 0; let mut x185: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x184, &mut x185, x183, x113, x159); let mut x186: u32 = 0; let mut x187: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x186, &mut x187, x185, x115, x161); let mut x188: u32 = 0; let mut x189: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x188, &mut x189, x187, x117, x163); let mut x190: u32 = 0; let mut x191: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x190, &mut x191, x189, x119, x165); let mut x192: u32 = 0; let mut x193: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x192, &mut x193, x191, x121, x167); let mut x194: u32 = 0; let mut x195: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x194, &mut x195, x193, (x122 as u32), x169); let mut x196: u32 = 0; let mut x197: u32 = 0; fiat_p384_mulx_u32(&mut x196, &mut x197, x170, 0xffffffff); let mut x198: u32 = 0; let mut x199: u32 = 0; fiat_p384_mulx_u32(&mut x198, &mut x199, x170, 0xffffffff); let mut x200: u32 = 0; let mut x201: u32 = 0; fiat_p384_mulx_u32(&mut x200, &mut x201, x170, 0xffffffff); let mut x202: u32 = 0; let mut x203: u32 = 0; fiat_p384_mulx_u32(&mut x202, &mut x203, x170, 0xffffffff); let mut x204: u32 = 0; let mut x205: u32 = 0; fiat_p384_mulx_u32(&mut x204, &mut x205, x170, 0xffffffff); let mut x206: u32 = 0; let mut x207: u32 = 0; fiat_p384_mulx_u32(&mut x206, &mut x207, x170, 0xffffffff); let mut x208: u32 = 0; let mut x209: u32 = 0; fiat_p384_mulx_u32(&mut x208, &mut x209, x170, 0xffffffff); let mut x210: u32 = 0; let mut x211: u32 = 0; fiat_p384_mulx_u32(&mut x210, &mut x211, x170, 0xfffffffe); let mut x212: u32 = 0; let mut x213: u32 = 0; fiat_p384_mulx_u32(&mut x212, &mut x213, x170, 0xffffffff); let mut x214: u32 = 0; let mut x215: u32 = 0; fiat_p384_mulx_u32(&mut x214, &mut x215, x170, 0xffffffff); let mut x216: u32 = 0; let mut x217: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x216, &mut x217, 0x0, x213, x210); let mut x218: u32 = 0; let mut x219: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x218, &mut x219, x217, x211, x208); let mut x220: u32 = 0; let mut x221: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x220, &mut x221, x219, x209, x206); let mut x222: u32 = 0; let mut x223: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x222, &mut x223, x221, x207, x204); let mut x224: u32 = 0; let mut x225: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x224, &mut x225, x223, x205, x202); let mut x226: u32 = 0; let mut x227: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x226, &mut x227, x225, x203, x200); let mut x228: u32 = 0; let mut x229: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x228, &mut x229, x227, x201, x198); let mut x230: u32 = 0; let mut x231: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x230, &mut x231, x229, x199, x196); let x232: u32 = ((x231 as u32) + x197); let mut x233: u32 = 0; let mut x234: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x233, &mut x234, 0x0, x170, x214); let mut x235: u32 = 0; let mut x236: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x235, &mut x236, x234, x172, x215); let mut x237: u32 = 0; let mut x238: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x237, &mut x238, x236, x174, (0x0 as u32)); let mut x239: u32 = 0; let mut x240: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x239, &mut x240, x238, x176, x212); let mut x241: u32 = 0; let mut x242: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x241, &mut x242, x240, x178, x216); let mut x243: u32 = 0; let mut x244: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x243, &mut x244, x242, x180, x218); let mut x245: u32 = 0; let mut x246: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x245, &mut x246, x244, x182, x220); let mut x247: u32 = 0; let mut x248: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x247, &mut x248, x246, x184, x222); let mut x249: u32 = 0; let mut x250: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x249, &mut x250, x248, x186, x224); let mut x251: u32 = 0; let mut x252: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x251, &mut x252, x250, x188, x226); let mut x253: u32 = 0; let mut x254: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x253, &mut x254, x252, x190, x228); let mut x255: u32 = 0; let mut x256: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x255, &mut x256, x254, x192, x230); let mut x257: u32 = 0; let mut x258: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x257, &mut x258, x256, x194, x232); let x259: u32 = ((x258 as u32) + (x195 as u32)); let mut x260: u32 = 0; let mut x261: u32 = 0; fiat_p384_mulx_u32(&mut x260, &mut x261, x2, (arg2[11])); let mut x262: u32 = 0; let mut x263: u32 = 0; fiat_p384_mulx_u32(&mut x262, &mut x263, x2, (arg2[10])); let mut x264: u32 = 0; let mut x265: u32 = 0; fiat_p384_mulx_u32(&mut x264, &mut x265, x2, (arg2[9])); let mut x266: u32 = 0; let mut x267: u32 = 0; fiat_p384_mulx_u32(&mut x266, &mut x267, x2, (arg2[8])); let mut x268: u32 = 0; let mut x269: u32 = 0; fiat_p384_mulx_u32(&mut x268, &mut x269, x2, (arg2[7])); let mut x270: u32 = 0; let mut x271: u32 = 0; fiat_p384_mulx_u32(&mut x270, &mut x271, x2, (arg2[6])); let mut x272: u32 = 0; let mut x273: u32 = 0; fiat_p384_mulx_u32(&mut x272, &mut x273, x2, (arg2[5])); let mut x274: u32 = 0; let mut x275: u32 = 0; fiat_p384_mulx_u32(&mut x274, &mut x275, x2, (arg2[4])); let mut x276: u32 = 0; let mut x277: u32 = 0; fiat_p384_mulx_u32(&mut x276, &mut x277, x2, (arg2[3])); let mut x278: u32 = 0; let mut x279: u32 = 0; fiat_p384_mulx_u32(&mut x278, &mut x279, x2, (arg2[2])); let mut x280: u32 = 0; let mut x281: u32 = 0; fiat_p384_mulx_u32(&mut x280, &mut x281, x2, (arg2[1])); let mut x282: u32 = 0; let mut x283: u32 = 0; fiat_p384_mulx_u32(&mut x282, &mut x283, x2, (arg2[0])); let mut x284: u32 = 0; let mut x285: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x284, &mut x285, 0x0, x283, x280); let mut x286: u32 = 0; let mut x287: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x286, &mut x287, x285, x281, x278); let mut x288: u32 = 0; let mut x289: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x288, &mut x289, x287, x279, x276); let mut x290: u32 = 0; let mut x291: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x290, &mut x291, x289, x277, x274); let mut x292: u32 = 0; let mut x293: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x292, &mut x293, x291, x275, x272); let mut x294: u32 = 0; let mut x295: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x294, &mut x295, x293, x273, x270); let mut x296: u32 = 0; let mut x297: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x296, &mut x297, x295, x271, x268); let mut x298: u32 = 0; let mut x299: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x298, &mut x299, x297, x269, x266); let mut x300: u32 = 0; let mut x301: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x300, &mut x301, x299, x267, x264); let mut x302: u32 = 0; let mut x303: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x302, &mut x303, x301, x265, x262); let mut x304: u32 = 0; let mut x305: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x304, &mut x305, x303, x263, x260); let x306: u32 = ((x305 as u32) + x261); let mut x307: u32 = 0; let mut x308: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x307, &mut x308, 0x0, x235, x282); let mut x309: u32 = 0; let mut x310: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x309, &mut x310, x308, x237, x284); let mut x311: u32 = 0; let mut x312: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x311, &mut x312, x310, x239, x286); let mut x313: u32 = 0; let mut x314: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x313, &mut x314, x312, x241, x288); let mut x315: u32 = 0; let mut x316: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x315, &mut x316, x314, x243, x290); let mut x317: u32 = 0; let mut x318: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x317, &mut x318, x316, x245, x292); let mut x319: u32 = 0; let mut x320: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x319, &mut x320, x318, x247, x294); let mut x321: u32 = 0; let mut x322: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x321, &mut x322, x320, x249, x296); let mut x323: u32 = 0; let mut x324: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x323, &mut x324, x322, x251, x298); let mut x325: u32 = 0; let mut x326: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x325, &mut x326, x324, x253, x300); let mut x327: u32 = 0; let mut x328: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x327, &mut x328, x326, x255, x302); let mut x329: u32 = 0; let mut x330: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x329, &mut x330, x328, x257, x304); let mut x331: u32 = 0; let mut x332: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x331, &mut x332, x330, x259, x306); let mut x333: u32 = 0; let mut x334: u32 = 0; fiat_p384_mulx_u32(&mut x333, &mut x334, x307, 0xffffffff); let mut x335: u32 = 0; let mut x336: u32 = 0; fiat_p384_mulx_u32(&mut x335, &mut x336, x307, 0xffffffff); let mut x337: u32 = 0; let mut x338: u32 = 0; fiat_p384_mulx_u32(&mut x337, &mut x338, x307, 0xffffffff); let mut x339: u32 = 0; let mut x340: u32 = 0; fiat_p384_mulx_u32(&mut x339, &mut x340, x307, 0xffffffff); let mut x341: u32 = 0; let mut x342: u32 = 0; fiat_p384_mulx_u32(&mut x341, &mut x342, x307, 0xffffffff); let mut x343: u32 = 0; let mut x344: u32 = 0; fiat_p384_mulx_u32(&mut x343, &mut x344, x307, 0xffffffff); let mut x345: u32 = 0; let mut x346: u32 = 0; fiat_p384_mulx_u32(&mut x345, &mut x346, x307, 0xffffffff); let mut x347: u32 = 0; let mut x348: u32 = 0; fiat_p384_mulx_u32(&mut x347, &mut x348, x307, 0xfffffffe); let mut x349: u32 = 0; let mut x350: u32 = 0; fiat_p384_mulx_u32(&mut x349, &mut x350, x307, 0xffffffff); let mut x351: u32 = 0; let mut x352: u32 = 0; fiat_p384_mulx_u32(&mut x351, &mut x352, x307, 0xffffffff); let mut x353: u32 = 0; let mut x354: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x353, &mut x354, 0x0, x350, x347); let mut x355: u32 = 0; let mut x356: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x355, &mut x356, x354, x348, x345); let mut x357: u32 = 0; let mut x358: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x357, &mut x358, x356, x346, x343); let mut x359: u32 = 0; let mut x360: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x359, &mut x360, x358, x344, x341); let mut x361: u32 = 0; let mut x362: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x361, &mut x362, x360, x342, x339); let mut x363: u32 = 0; let mut x364: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x363, &mut x364, x362, x340, x337); let mut x365: u32 = 0; let mut x366: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x365, &mut x366, x364, x338, x335); let mut x367: u32 = 0; let mut x368: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x367, &mut x368, x366, x336, x333); let x369: u32 = ((x368 as u32) + x334); let mut x370: u32 = 0; let mut x371: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x370, &mut x371, 0x0, x307, x351); let mut x372: u32 = 0; let mut x373: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x372, &mut x373, x371, x309, x352); let mut x374: u32 = 0; let mut x375: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x374, &mut x375, x373, x311, (0x0 as u32)); let mut x376: u32 = 0; let mut x377: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x376, &mut x377, x375, x313, x349); let mut x378: u32 = 0; let mut x379: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x378, &mut x379, x377, x315, x353); let mut x380: u32 = 0; let mut x381: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x380, &mut x381, x379, x317, x355); let mut x382: u32 = 0; let mut x383: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x382, &mut x383, x381, x319, x357); let mut x384: u32 = 0; let mut x385: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x384, &mut x385, x383, x321, x359); let mut x386: u32 = 0; let mut x387: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x386, &mut x387, x385, x323, x361); let mut x388: u32 = 0; let mut x389: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x388, &mut x389, x387, x325, x363); let mut x390: u32 = 0; let mut x391: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x390, &mut x391, x389, x327, x365); let mut x392: u32 = 0; let mut x393: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x392, &mut x393, x391, x329, x367); let mut x394: u32 = 0; let mut x395: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x394, &mut x395, x393, x331, x369); let x396: u32 = ((x395 as u32) + (x332 as u32)); let mut x397: u32 = 0; let mut x398: u32 = 0; fiat_p384_mulx_u32(&mut x397, &mut x398, x3, (arg2[11])); let mut x399: u32 = 0; let mut x400: u32 = 0; fiat_p384_mulx_u32(&mut x399, &mut x400, x3, (arg2[10])); let mut x401: u32 = 0; let mut x402: u32 = 0; fiat_p384_mulx_u32(&mut x401, &mut x402, x3, (arg2[9])); let mut x403: u32 = 0; let mut x404: u32 = 0; fiat_p384_mulx_u32(&mut x403, &mut x404, x3, (arg2[8])); let mut x405: u32 = 0; let mut x406: u32 = 0; fiat_p384_mulx_u32(&mut x405, &mut x406, x3, (arg2[7])); let mut x407: u32 = 0; let mut x408: u32 = 0; fiat_p384_mulx_u32(&mut x407, &mut x408, x3, (arg2[6])); let mut x409: u32 = 0; let mut x410: u32 = 0; fiat_p384_mulx_u32(&mut x409, &mut x410, x3, (arg2[5])); let mut x411: u32 = 0; let mut x412: u32 = 0; fiat_p384_mulx_u32(&mut x411, &mut x412, x3, (arg2[4])); let mut x413: u32 = 0; let mut x414: u32 = 0; fiat_p384_mulx_u32(&mut x413, &mut x414, x3, (arg2[3])); let mut x415: u32 = 0; let mut x416: u32 = 0; fiat_p384_mulx_u32(&mut x415, &mut x416, x3, (arg2[2])); let mut x417: u32 = 0; let mut x418: u32 = 0; fiat_p384_mulx_u32(&mut x417, &mut x418, x3, (arg2[1])); let mut x419: u32 = 0; let mut x420: u32 = 0; fiat_p384_mulx_u32(&mut x419, &mut x420, x3, (arg2[0])); let mut x421: u32 = 0; let mut x422: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x421, &mut x422, 0x0, x420, x417); let mut x423: u32 = 0; let mut x424: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x423, &mut x424, x422, x418, x415); let mut x425: u32 = 0; let mut x426: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x425, &mut x426, x424, x416, x413); let mut x427: u32 = 0; let mut x428: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x427, &mut x428, x426, x414, x411); let mut x429: u32 = 0; let mut x430: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x429, &mut x430, x428, x412, x409); let mut x431: u32 = 0; let mut x432: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x431, &mut x432, x430, x410, x407); let mut x433: u32 = 0; let mut x434: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x433, &mut x434, x432, x408, x405); let mut x435: u32 = 0; let mut x436: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x435, &mut x436, x434, x406, x403); let mut x437: u32 = 0; let mut x438: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x437, &mut x438, x436, x404, x401); let mut x439: u32 = 0; let mut x440: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x439, &mut x440, x438, x402, x399); let mut x441: u32 = 0; let mut x442: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x441, &mut x442, x440, x400, x397); let x443: u32 = ((x442 as u32) + x398); let mut x444: u32 = 0; let mut x445: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x444, &mut x445, 0x0, x372, x419); let mut x446: u32 = 0; let mut x447: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x446, &mut x447, x445, x374, x421); let mut x448: u32 = 0; let mut x449: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x448, &mut x449, x447, x376, x423); let mut x450: u32 = 0; let mut x451: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x450, &mut x451, x449, x378, x425); let mut x452: u32 = 0; let mut x453: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x452, &mut x453, x451, x380, x427); let mut x454: u32 = 0; let mut x455: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x454, &mut x455, x453, x382, x429); let mut x456: u32 = 0; let mut x457: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x456, &mut x457, x455, x384, x431); let mut x458: u32 = 0; let mut x459: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x458, &mut x459, x457, x386, x433); let mut x460: u32 = 0; let mut x461: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x460, &mut x461, x459, x388, x435); let mut x462: u32 = 0; let mut x463: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x462, &mut x463, x461, x390, x437); let mut x464: u32 = 0; let mut x465: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x464, &mut x465, x463, x392, x439); let mut x466: u32 = 0; let mut x467: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x466, &mut x467, x465, x394, x441); let mut x468: u32 = 0; let mut x469: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x468, &mut x469, x467, x396, x443); let mut x470: u32 = 0; let mut x471: u32 = 0; fiat_p384_mulx_u32(&mut x470, &mut x471, x444, 0xffffffff); let mut x472: u32 = 0; let mut x473: u32 = 0; fiat_p384_mulx_u32(&mut x472, &mut x473, x444, 0xffffffff); let mut x474: u32 = 0; let mut x475: u32 = 0; fiat_p384_mulx_u32(&mut x474, &mut x475, x444, 0xffffffff); let mut x476: u32 = 0; let mut x477: u32 = 0; fiat_p384_mulx_u32(&mut x476, &mut x477, x444, 0xffffffff); let mut x478: u32 = 0; let mut x479: u32 = 0; fiat_p384_mulx_u32(&mut x478, &mut x479, x444, 0xffffffff); let mut x480: u32 = 0; let mut x481: u32 = 0; fiat_p384_mulx_u32(&mut x480, &mut x481, x444, 0xffffffff); let mut x482: u32 = 0; let mut x483: u32 = 0; fiat_p384_mulx_u32(&mut x482, &mut x483, x444, 0xffffffff); let mut x484: u32 = 0; let mut x485: u32 = 0; fiat_p384_mulx_u32(&mut x484, &mut x485, x444, 0xfffffffe); let mut x486: u32 = 0; let mut x487: u32 = 0; fiat_p384_mulx_u32(&mut x486, &mut x487, x444, 0xffffffff); let mut x488: u32 = 0; let mut x489: u32 = 0; fiat_p384_mulx_u32(&mut x488, &mut x489, x444, 0xffffffff); let mut x490: u32 = 0; let mut x491: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x490, &mut x491, 0x0, x487, x484); let mut x492: u32 = 0; let mut x493: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x492, &mut x493, x491, x485, x482); let mut x494: u32 = 0; let mut x495: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x494, &mut x495, x493, x483, x480); let mut x496: u32 = 0; let mut x497: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x496, &mut x497, x495, x481, x478); let mut x498: u32 = 0; let mut x499: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x498, &mut x499, x497, x479, x476); let mut x500: u32 = 0; let mut x501: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x500, &mut x501, x499, x477, x474); let mut x502: u32 = 0; let mut x503: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x502, &mut x503, x501, x475, x472); let mut x504: u32 = 0; let mut x505: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x504, &mut x505, x503, x473, x470); let x506: u32 = ((x505 as u32) + x471); let mut x507: u32 = 0; let mut x508: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x507, &mut x508, 0x0, x444, x488); let mut x509: u32 = 0; let mut x510: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x509, &mut x510, x508, x446, x489); let mut x511: u32 = 0; let mut x512: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x511, &mut x512, x510, x448, (0x0 as u32)); let mut x513: u32 = 0; let mut x514: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x513, &mut x514, x512, x450, x486); let mut x515: u32 = 0; let mut x516: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x515, &mut x516, x514, x452, x490); let mut x517: u32 = 0; let mut x518: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x517, &mut x518, x516, x454, x492); let mut x519: u32 = 0; let mut x520: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x519, &mut x520, x518, x456, x494); let mut x521: u32 = 0; let mut x522: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x521, &mut x522, x520, x458, x496); let mut x523: u32 = 0; let mut x524: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x523, &mut x524, x522, x460, x498); let mut x525: u32 = 0; let mut x526: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x525, &mut x526, x524, x462, x500); let mut x527: u32 = 0; let mut x528: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x527, &mut x528, x526, x464, x502); let mut x529: u32 = 0; let mut x530: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x529, &mut x530, x528, x466, x504); let mut x531: u32 = 0; let mut x532: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x531, &mut x532, x530, x468, x506); let x533: u32 = ((x532 as u32) + (x469 as u32)); let mut x534: u32 = 0; let mut x535: u32 = 0; fiat_p384_mulx_u32(&mut x534, &mut x535, x4, (arg2[11])); let mut x536: u32 = 0; let mut x537: u32 = 0; fiat_p384_mulx_u32(&mut x536, &mut x537, x4, (arg2[10])); let mut x538: u32 = 0; let mut x539: u32 = 0; fiat_p384_mulx_u32(&mut x538, &mut x539, x4, (arg2[9])); let mut x540: u32 = 0; let mut x541: u32 = 0; fiat_p384_mulx_u32(&mut x540, &mut x541, x4, (arg2[8])); let mut x542: u32 = 0; let mut x543: u32 = 0; fiat_p384_mulx_u32(&mut x542, &mut x543, x4, (arg2[7])); let mut x544: u32 = 0; let mut x545: u32 = 0; fiat_p384_mulx_u32(&mut x544, &mut x545, x4, (arg2[6])); let mut x546: u32 = 0; let mut x547: u32 = 0; fiat_p384_mulx_u32(&mut x546, &mut x547, x4, (arg2[5])); let mut x548: u32 = 0; let mut x549: u32 = 0; fiat_p384_mulx_u32(&mut x548, &mut x549, x4, (arg2[4])); let mut x550: u32 = 0; let mut x551: u32 = 0; fiat_p384_mulx_u32(&mut x550, &mut x551, x4, (arg2[3])); let mut x552: u32 = 0; let mut x553: u32 = 0; fiat_p384_mulx_u32(&mut x552, &mut x553, x4, (arg2[2])); let mut x554: u32 = 0; let mut x555: u32 = 0; fiat_p384_mulx_u32(&mut x554, &mut x555, x4, (arg2[1])); let mut x556: u32 = 0; let mut x557: u32 = 0; fiat_p384_mulx_u32(&mut x556, &mut x557, x4, (arg2[0])); let mut x558: u32 = 0; let mut x559: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x558, &mut x559, 0x0, x557, x554); let mut x560: u32 = 0; let mut x561: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x560, &mut x561, x559, x555, x552); let mut x562: u32 = 0; let mut x563: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x562, &mut x563, x561, x553, x550); let mut x564: u32 = 0; let mut x565: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x564, &mut x565, x563, x551, x548); let mut x566: u32 = 0; let mut x567: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x566, &mut x567, x565, x549, x546); let mut x568: u32 = 0; let mut x569: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x568, &mut x569, x567, x547, x544); let mut x570: u32 = 0; let mut x571: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x570, &mut x571, x569, x545, x542); let mut x572: u32 = 0; let mut x573: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x572, &mut x573, x571, x543, x540); let mut x574: u32 = 0; let mut x575: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x574, &mut x575, x573, x541, x538); let mut x576: u32 = 0; let mut x577: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x576, &mut x577, x575, x539, x536); let mut x578: u32 = 0; let mut x579: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x578, &mut x579, x577, x537, x534); let x580: u32 = ((x579 as u32) + x535); let mut x581: u32 = 0; let mut x582: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x581, &mut x582, 0x0, x509, x556); let mut x583: u32 = 0; let mut x584: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x583, &mut x584, x582, x511, x558); let mut x585: u32 = 0; let mut x586: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x585, &mut x586, x584, x513, x560); let mut x587: u32 = 0; let mut x588: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x587, &mut x588, x586, x515, x562); let mut x589: u32 = 0; let mut x590: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x589, &mut x590, x588, x517, x564); let mut x591: u32 = 0; let mut x592: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x591, &mut x592, x590, x519, x566); let mut x593: u32 = 0; let mut x594: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x593, &mut x594, x592, x521, x568); let mut x595: u32 = 0; let mut x596: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x595, &mut x596, x594, x523, x570); let mut x597: u32 = 0; let mut x598: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x597, &mut x598, x596, x525, x572); let mut x599: u32 = 0; let mut x600: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x599, &mut x600, x598, x527, x574); let mut x601: u32 = 0; let mut x602: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x601, &mut x602, x600, x529, x576); let mut x603: u32 = 0; let mut x604: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x603, &mut x604, x602, x531, x578); let mut x605: u32 = 0; let mut x606: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x605, &mut x606, x604, x533, x580); let mut x607: u32 = 0; let mut x608: u32 = 0; fiat_p384_mulx_u32(&mut x607, &mut x608, x581, 0xffffffff); let mut x609: u32 = 0; let mut x610: u32 = 0; fiat_p384_mulx_u32(&mut x609, &mut x610, x581, 0xffffffff); let mut x611: u32 = 0; let mut x612: u32 = 0; fiat_p384_mulx_u32(&mut x611, &mut x612, x581, 0xffffffff); let mut x613: u32 = 0; let mut x614: u32 = 0; fiat_p384_mulx_u32(&mut x613, &mut x614, x581, 0xffffffff); let mut x615: u32 = 0; let mut x616: u32 = 0; fiat_p384_mulx_u32(&mut x615, &mut x616, x581, 0xffffffff); let mut x617: u32 = 0; let mut x618: u32 = 0; fiat_p384_mulx_u32(&mut x617, &mut x618, x581, 0xffffffff); let mut x619: u32 = 0; let mut x620: u32 = 0; fiat_p384_mulx_u32(&mut x619, &mut x620, x581, 0xffffffff); let mut x621: u32 = 0; let mut x622: u32 = 0; fiat_p384_mulx_u32(&mut x621, &mut x622, x581, 0xfffffffe); let mut x623: u32 = 0; let mut x624: u32 = 0; fiat_p384_mulx_u32(&mut x623, &mut x624, x581, 0xffffffff); let mut x625: u32 = 0; let mut x626: u32 = 0; fiat_p384_mulx_u32(&mut x625, &mut x626, x581, 0xffffffff); let mut x627: u32 = 0; let mut x628: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x627, &mut x628, 0x0, x624, x621); let mut x629: u32 = 0; let mut x630: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x629, &mut x630, x628, x622, x619); let mut x631: u32 = 0; let mut x632: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x631, &mut x632, x630, x620, x617); let mut x633: u32 = 0; let mut x634: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x633, &mut x634, x632, x618, x615); let mut x635: u32 = 0; let mut x636: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x635, &mut x636, x634, x616, x613); let mut x637: u32 = 0; let mut x638: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x637, &mut x638, x636, x614, x611); let mut x639: u32 = 0; let mut x640: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x639, &mut x640, x638, x612, x609); let mut x641: u32 = 0; let mut x642: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x641, &mut x642, x640, x610, x607); let x643: u32 = ((x642 as u32) + x608); let mut x644: u32 = 0; let mut x645: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x644, &mut x645, 0x0, x581, x625); let mut x646: u32 = 0; let mut x647: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x646, &mut x647, x645, x583, x626); let mut x648: u32 = 0; let mut x649: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x648, &mut x649, x647, x585, (0x0 as u32)); let mut x650: u32 = 0; let mut x651: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x650, &mut x651, x649, x587, x623); let mut x652: u32 = 0; let mut x653: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x652, &mut x653, x651, x589, x627); let mut x654: u32 = 0; let mut x655: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x654, &mut x655, x653, x591, x629); let mut x656: u32 = 0; let mut x657: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x656, &mut x657, x655, x593, x631); let mut x658: u32 = 0; let mut x659: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x658, &mut x659, x657, x595, x633); let mut x660: u32 = 0; let mut x661: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x660, &mut x661, x659, x597, x635); let mut x662: u32 = 0; let mut x663: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x662, &mut x663, x661, x599, x637); let mut x664: u32 = 0; let mut x665: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x664, &mut x665, x663, x601, x639); let mut x666: u32 = 0; let mut x667: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x666, &mut x667, x665, x603, x641); let mut x668: u32 = 0; let mut x669: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x668, &mut x669, x667, x605, x643); let x670: u32 = ((x669 as u32) + (x606 as u32)); let mut x671: u32 = 0; let mut x672: u32 = 0; fiat_p384_mulx_u32(&mut x671, &mut x672, x5, (arg2[11])); let mut x673: u32 = 0; let mut x674: u32 = 0; fiat_p384_mulx_u32(&mut x673, &mut x674, x5, (arg2[10])); let mut x675: u32 = 0; let mut x676: u32 = 0; fiat_p384_mulx_u32(&mut x675, &mut x676, x5, (arg2[9])); let mut x677: u32 = 0; let mut x678: u32 = 0; fiat_p384_mulx_u32(&mut x677, &mut x678, x5, (arg2[8])); let mut x679: u32 = 0; let mut x680: u32 = 0; fiat_p384_mulx_u32(&mut x679, &mut x680, x5, (arg2[7])); let mut x681: u32 = 0; let mut x682: u32 = 0; fiat_p384_mulx_u32(&mut x681, &mut x682, x5, (arg2[6])); let mut x683: u32 = 0; let mut x684: u32 = 0; fiat_p384_mulx_u32(&mut x683, &mut x684, x5, (arg2[5])); let mut x685: u32 = 0; let mut x686: u32 = 0; fiat_p384_mulx_u32(&mut x685, &mut x686, x5, (arg2[4])); let mut x687: u32 = 0; let mut x688: u32 = 0; fiat_p384_mulx_u32(&mut x687, &mut x688, x5, (arg2[3])); let mut x689: u32 = 0; let mut x690: u32 = 0; fiat_p384_mulx_u32(&mut x689, &mut x690, x5, (arg2[2])); let mut x691: u32 = 0; let mut x692: u32 = 0; fiat_p384_mulx_u32(&mut x691, &mut x692, x5, (arg2[1])); let mut x693: u32 = 0; let mut x694: u32 = 0; fiat_p384_mulx_u32(&mut x693, &mut x694, x5, (arg2[0])); let mut x695: u32 = 0; let mut x696: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x695, &mut x696, 0x0, x694, x691); let mut x697: u32 = 0; let mut x698: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x697, &mut x698, x696, x692, x689); let mut x699: u32 = 0; let mut x700: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x699, &mut x700, x698, x690, x687); let mut x701: u32 = 0; let mut x702: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x701, &mut x702, x700, x688, x685); let mut x703: u32 = 0; let mut x704: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x703, &mut x704, x702, x686, x683); let mut x705: u32 = 0; let mut x706: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x705, &mut x706, x704, x684, x681); let mut x707: u32 = 0; let mut x708: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x707, &mut x708, x706, x682, x679); let mut x709: u32 = 0; let mut x710: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x709, &mut x710, x708, x680, x677); let mut x711: u32 = 0; let mut x712: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x711, &mut x712, x710, x678, x675); let mut x713: u32 = 0; let mut x714: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x713, &mut x714, x712, x676, x673); let mut x715: u32 = 0; let mut x716: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x715, &mut x716, x714, x674, x671); let x717: u32 = ((x716 as u32) + x672); let mut x718: u32 = 0; let mut x719: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x718, &mut x719, 0x0, x646, x693); let mut x720: u32 = 0; let mut x721: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x720, &mut x721, x719, x648, x695); let mut x722: u32 = 0; let mut x723: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x722, &mut x723, x721, x650, x697); let mut x724: u32 = 0; let mut x725: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x724, &mut x725, x723, x652, x699); let mut x726: u32 = 0; let mut x727: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x726, &mut x727, x725, x654, x701); let mut x728: u32 = 0; let mut x729: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x728, &mut x729, x727, x656, x703); let mut x730: u32 = 0; let mut x731: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x730, &mut x731, x729, x658, x705); let mut x732: u32 = 0; let mut x733: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x732, &mut x733, x731, x660, x707); let mut x734: u32 = 0; let mut x735: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x734, &mut x735, x733, x662, x709); let mut x736: u32 = 0; let mut x737: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x736, &mut x737, x735, x664, x711); let mut x738: u32 = 0; let mut x739: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x738, &mut x739, x737, x666, x713); let mut x740: u32 = 0; let mut x741: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x740, &mut x741, x739, x668, x715); let mut x742: u32 = 0; let mut x743: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x742, &mut x743, x741, x670, x717); let mut x744: u32 = 0; let mut x745: u32 = 0; fiat_p384_mulx_u32(&mut x744, &mut x745, x718, 0xffffffff); let mut x746: u32 = 0; let mut x747: u32 = 0; fiat_p384_mulx_u32(&mut x746, &mut x747, x718, 0xffffffff); let mut x748: u32 = 0; let mut x749: u32 = 0; fiat_p384_mulx_u32(&mut x748, &mut x749, x718, 0xffffffff); let mut x750: u32 = 0; let mut x751: u32 = 0; fiat_p384_mulx_u32(&mut x750, &mut x751, x718, 0xffffffff); let mut x752: u32 = 0; let mut x753: u32 = 0; fiat_p384_mulx_u32(&mut x752, &mut x753, x718, 0xffffffff); let mut x754: u32 = 0; let mut x755: u32 = 0; fiat_p384_mulx_u32(&mut x754, &mut x755, x718, 0xffffffff); let mut x756: u32 = 0; let mut x757: u32 = 0; fiat_p384_mulx_u32(&mut x756, &mut x757, x718, 0xffffffff); let mut x758: u32 = 0; let mut x759: u32 = 0; fiat_p384_mulx_u32(&mut x758, &mut x759, x718, 0xfffffffe); let mut x760: u32 = 0; let mut x761: u32 = 0; fiat_p384_mulx_u32(&mut x760, &mut x761, x718, 0xffffffff); let mut x762: u32 = 0; let mut x763: u32 = 0; fiat_p384_mulx_u32(&mut x762, &mut x763, x718, 0xffffffff); let mut x764: u32 = 0; let mut x765: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x764, &mut x765, 0x0, x761, x758); let mut x766: u32 = 0; let mut x767: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x766, &mut x767, x765, x759, x756); let mut x768: u32 = 0; let mut x769: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x768, &mut x769, x767, x757, x754); let mut x770: u32 = 0; let mut x771: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x770, &mut x771, x769, x755, x752); let mut x772: u32 = 0; let mut x773: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x772, &mut x773, x771, x753, x750); let mut x774: u32 = 0; let mut x775: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x774, &mut x775, x773, x751, x748); let mut x776: u32 = 0; let mut x777: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x776, &mut x777, x775, x749, x746); let mut x778: u32 = 0; let mut x779: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x778, &mut x779, x777, x747, x744); let x780: u32 = ((x779 as u32) + x745); let mut x781: u32 = 0; let mut x782: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x781, &mut x782, 0x0, x718, x762); let mut x783: u32 = 0; let mut x784: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x783, &mut x784, x782, x720, x763); let mut x785: u32 = 0; let mut x786: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x785, &mut x786, x784, x722, (0x0 as u32)); let mut x787: u32 = 0; let mut x788: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x787, &mut x788, x786, x724, x760); let mut x789: u32 = 0; let mut x790: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x789, &mut x790, x788, x726, x764); let mut x791: u32 = 0; let mut x792: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x791, &mut x792, x790, x728, x766); let mut x793: u32 = 0; let mut x794: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x793, &mut x794, x792, x730, x768); let mut x795: u32 = 0; let mut x796: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x795, &mut x796, x794, x732, x770); let mut x797: u32 = 0; let mut x798: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x797, &mut x798, x796, x734, x772); let mut x799: u32 = 0; let mut x800: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x799, &mut x800, x798, x736, x774); let mut x801: u32 = 0; let mut x802: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x801, &mut x802, x800, x738, x776); let mut x803: u32 = 0; let mut x804: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x803, &mut x804, x802, x740, x778); let mut x805: u32 = 0; let mut x806: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x805, &mut x806, x804, x742, x780); let x807: u32 = ((x806 as u32) + (x743 as u32)); let mut x808: u32 = 0; let mut x809: u32 = 0; fiat_p384_mulx_u32(&mut x808, &mut x809, x6, (arg2[11])); let mut x810: u32 = 0; let mut x811: u32 = 0; fiat_p384_mulx_u32(&mut x810, &mut x811, x6, (arg2[10])); let mut x812: u32 = 0; let mut x813: u32 = 0; fiat_p384_mulx_u32(&mut x812, &mut x813, x6, (arg2[9])); let mut x814: u32 = 0; let mut x815: u32 = 0; fiat_p384_mulx_u32(&mut x814, &mut x815, x6, (arg2[8])); let mut x816: u32 = 0; let mut x817: u32 = 0; fiat_p384_mulx_u32(&mut x816, &mut x817, x6, (arg2[7])); let mut x818: u32 = 0; let mut x819: u32 = 0; fiat_p384_mulx_u32(&mut x818, &mut x819, x6, (arg2[6])); let mut x820: u32 = 0; let mut x821: u32 = 0; fiat_p384_mulx_u32(&mut x820, &mut x821, x6, (arg2[5])); let mut x822: u32 = 0; let mut x823: u32 = 0; fiat_p384_mulx_u32(&mut x822, &mut x823, x6, (arg2[4])); let mut x824: u32 = 0; let mut x825: u32 = 0; fiat_p384_mulx_u32(&mut x824, &mut x825, x6, (arg2[3])); let mut x826: u32 = 0; let mut x827: u32 = 0; fiat_p384_mulx_u32(&mut x826, &mut x827, x6, (arg2[2])); let mut x828: u32 = 0; let mut x829: u32 = 0; fiat_p384_mulx_u32(&mut x828, &mut x829, x6, (arg2[1])); let mut x830: u32 = 0; let mut x831: u32 = 0; fiat_p384_mulx_u32(&mut x830, &mut x831, x6, (arg2[0])); let mut x832: u32 = 0; let mut x833: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x832, &mut x833, 0x0, x831, x828); let mut x834: u32 = 0; let mut x835: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x834, &mut x835, x833, x829, x826); let mut x836: u32 = 0; let mut x837: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x836, &mut x837, x835, x827, x824); let mut x838: u32 = 0; let mut x839: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x838, &mut x839, x837, x825, x822); let mut x840: u32 = 0; let mut x841: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x840, &mut x841, x839, x823, x820); let mut x842: u32 = 0; let mut x843: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x842, &mut x843, x841, x821, x818); let mut x844: u32 = 0; let mut x845: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x844, &mut x845, x843, x819, x816); let mut x846: u32 = 0; let mut x847: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x846, &mut x847, x845, x817, x814); let mut x848: u32 = 0; let mut x849: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x848, &mut x849, x847, x815, x812); let mut x850: u32 = 0; let mut x851: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x850, &mut x851, x849, x813, x810); let mut x852: u32 = 0; let mut x853: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x852, &mut x853, x851, x811, x808); let x854: u32 = ((x853 as u32) + x809); let mut x855: u32 = 0; let mut x856: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x855, &mut x856, 0x0, x783, x830); let mut x857: u32 = 0; let mut x858: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x857, &mut x858, x856, x785, x832); let mut x859: u32 = 0; let mut x860: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x859, &mut x860, x858, x787, x834); let mut x861: u32 = 0; let mut x862: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x861, &mut x862, x860, x789, x836); let mut x863: u32 = 0; let mut x864: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x863, &mut x864, x862, x791, x838); let mut x865: u32 = 0; let mut x866: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x865, &mut x866, x864, x793, x840); let mut x867: u32 = 0; let mut x868: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x867, &mut x868, x866, x795, x842); let mut x869: u32 = 0; let mut x870: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x869, &mut x870, x868, x797, x844); let mut x871: u32 = 0; let mut x872: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x871, &mut x872, x870, x799, x846); let mut x873: u32 = 0; let mut x874: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x873, &mut x874, x872, x801, x848); let mut x875: u32 = 0; let mut x876: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x875, &mut x876, x874, x803, x850); let mut x877: u32 = 0; let mut x878: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x877, &mut x878, x876, x805, x852); let mut x879: u32 = 0; let mut x880: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x879, &mut x880, x878, x807, x854); let mut x881: u32 = 0; let mut x882: u32 = 0; fiat_p384_mulx_u32(&mut x881, &mut x882, x855, 0xffffffff); let mut x883: u32 = 0; let mut x884: u32 = 0; fiat_p384_mulx_u32(&mut x883, &mut x884, x855, 0xffffffff); let mut x885: u32 = 0; let mut x886: u32 = 0; fiat_p384_mulx_u32(&mut x885, &mut x886, x855, 0xffffffff); let mut x887: u32 = 0; let mut x888: u32 = 0; fiat_p384_mulx_u32(&mut x887, &mut x888, x855, 0xffffffff); let mut x889: u32 = 0; let mut x890: u32 = 0; fiat_p384_mulx_u32(&mut x889, &mut x890, x855, 0xffffffff); let mut x891: u32 = 0; let mut x892: u32 = 0; fiat_p384_mulx_u32(&mut x891, &mut x892, x855, 0xffffffff); let mut x893: u32 = 0; let mut x894: u32 = 0; fiat_p384_mulx_u32(&mut x893, &mut x894, x855, 0xffffffff); let mut x895: u32 = 0; let mut x896: u32 = 0; fiat_p384_mulx_u32(&mut x895, &mut x896, x855, 0xfffffffe); let mut x897: u32 = 0; let mut x898: u32 = 0; fiat_p384_mulx_u32(&mut x897, &mut x898, x855, 0xffffffff); let mut x899: u32 = 0; let mut x900: u32 = 0; fiat_p384_mulx_u32(&mut x899, &mut x900, x855, 0xffffffff); let mut x901: u32 = 0; let mut x902: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x901, &mut x902, 0x0, x898, x895); let mut x903: u32 = 0; let mut x904: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x903, &mut x904, x902, x896, x893); let mut x905: u32 = 0; let mut x906: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x905, &mut x906, x904, x894, x891); let mut x907: u32 = 0; let mut x908: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x907, &mut x908, x906, x892, x889); let mut x909: u32 = 0; let mut x910: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x909, &mut x910, x908, x890, x887); let mut x911: u32 = 0; let mut x912: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x911, &mut x912, x910, x888, x885); let mut x913: u32 = 0; let mut x914: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x913, &mut x914, x912, x886, x883); let mut x915: u32 = 0; let mut x916: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x915, &mut x916, x914, x884, x881); let x917: u32 = ((x916 as u32) + x882); let mut x918: u32 = 0; let mut x919: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x918, &mut x919, 0x0, x855, x899); let mut x920: u32 = 0; let mut x921: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x920, &mut x921, x919, x857, x900); let mut x922: u32 = 0; let mut x923: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x922, &mut x923, x921, x859, (0x0 as u32)); let mut x924: u32 = 0; let mut x925: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x924, &mut x925, x923, x861, x897); let mut x926: u32 = 0; let mut x927: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x926, &mut x927, x925, x863, x901); let mut x928: u32 = 0; let mut x929: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x928, &mut x929, x927, x865, x903); let mut x930: u32 = 0; let mut x931: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x930, &mut x931, x929, x867, x905); let mut x932: u32 = 0; let mut x933: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x932, &mut x933, x931, x869, x907); let mut x934: u32 = 0; let mut x935: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x934, &mut x935, x933, x871, x909); let mut x936: u32 = 0; let mut x937: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x936, &mut x937, x935, x873, x911); let mut x938: u32 = 0; let mut x939: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x938, &mut x939, x937, x875, x913); let mut x940: u32 = 0; let mut x941: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x940, &mut x941, x939, x877, x915); let mut x942: u32 = 0; let mut x943: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x942, &mut x943, x941, x879, x917); let x944: u32 = ((x943 as u32) + (x880 as u32)); let mut x945: u32 = 0; let mut x946: u32 = 0; fiat_p384_mulx_u32(&mut x945, &mut x946, x7, (arg2[11])); let mut x947: u32 = 0; let mut x948: u32 = 0; fiat_p384_mulx_u32(&mut x947, &mut x948, x7, (arg2[10])); let mut x949: u32 = 0; let mut x950: u32 = 0; fiat_p384_mulx_u32(&mut x949, &mut x950, x7, (arg2[9])); let mut x951: u32 = 0; let mut x952: u32 = 0; fiat_p384_mulx_u32(&mut x951, &mut x952, x7, (arg2[8])); let mut x953: u32 = 0; let mut x954: u32 = 0; fiat_p384_mulx_u32(&mut x953, &mut x954, x7, (arg2[7])); let mut x955: u32 = 0; let mut x956: u32 = 0; fiat_p384_mulx_u32(&mut x955, &mut x956, x7, (arg2[6])); let mut x957: u32 = 0; let mut x958: u32 = 0; fiat_p384_mulx_u32(&mut x957, &mut x958, x7, (arg2[5])); let mut x959: u32 = 0; let mut x960: u32 = 0; fiat_p384_mulx_u32(&mut x959, &mut x960, x7, (arg2[4])); let mut x961: u32 = 0; let mut x962: u32 = 0; fiat_p384_mulx_u32(&mut x961, &mut x962, x7, (arg2[3])); let mut x963: u32 = 0; let mut x964: u32 = 0; fiat_p384_mulx_u32(&mut x963, &mut x964, x7, (arg2[2])); let mut x965: u32 = 0; let mut x966: u32 = 0; fiat_p384_mulx_u32(&mut x965, &mut x966, x7, (arg2[1])); let mut x967: u32 = 0; let mut x968: u32 = 0; fiat_p384_mulx_u32(&mut x967, &mut x968, x7, (arg2[0])); let mut x969: u32 = 0; let mut x970: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x969, &mut x970, 0x0, x968, x965); let mut x971: u32 = 0; let mut x972: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x971, &mut x972, x970, x966, x963); let mut x973: u32 = 0; let mut x974: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x973, &mut x974, x972, x964, x961); let mut x975: u32 = 0; let mut x976: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x975, &mut x976, x974, x962, x959); let mut x977: u32 = 0; let mut x978: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x977, &mut x978, x976, x960, x957); let mut x979: u32 = 0; let mut x980: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x979, &mut x980, x978, x958, x955); let mut x981: u32 = 0; let mut x982: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x981, &mut x982, x980, x956, x953); let mut x983: u32 = 0; let mut x984: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x983, &mut x984, x982, x954, x951); let mut x985: u32 = 0; let mut x986: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x985, &mut x986, x984, x952, x949); let mut x987: u32 = 0; let mut x988: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x987, &mut x988, x986, x950, x947); let mut x989: u32 = 0; let mut x990: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x989, &mut x990, x988, x948, x945); let x991: u32 = ((x990 as u32) + x946); let mut x992: u32 = 0; let mut x993: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x992, &mut x993, 0x0, x920, x967); let mut x994: u32 = 0; let mut x995: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x994, &mut x995, x993, x922, x969); let mut x996: u32 = 0; let mut x997: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x996, &mut x997, x995, x924, x971); let mut x998: u32 = 0; let mut x999: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x998, &mut x999, x997, x926, x973); let mut x1000: u32 = 0; let mut x1001: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1000, &mut x1001, x999, x928, x975); let mut x1002: u32 = 0; let mut x1003: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1002, &mut x1003, x1001, x930, x977); let mut x1004: u32 = 0; let mut x1005: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1004, &mut x1005, x1003, x932, x979); let mut x1006: u32 = 0; let mut x1007: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1006, &mut x1007, x1005, x934, x981); let mut x1008: u32 = 0; let mut x1009: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1008, &mut x1009, x1007, x936, x983); let mut x1010: u32 = 0; let mut x1011: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1010, &mut x1011, x1009, x938, x985); let mut x1012: u32 = 0; let mut x1013: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1012, &mut x1013, x1011, x940, x987); let mut x1014: u32 = 0; let mut x1015: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1014, &mut x1015, x1013, x942, x989); let mut x1016: u32 = 0; let mut x1017: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1016, &mut x1017, x1015, x944, x991); let mut x1018: u32 = 0; let mut x1019: u32 = 0; fiat_p384_mulx_u32(&mut x1018, &mut x1019, x992, 0xffffffff); let mut x1020: u32 = 0; let mut x1021: u32 = 0; fiat_p384_mulx_u32(&mut x1020, &mut x1021, x992, 0xffffffff); let mut x1022: u32 = 0; let mut x1023: u32 = 0; fiat_p384_mulx_u32(&mut x1022, &mut x1023, x992, 0xffffffff); let mut x1024: u32 = 0; let mut x1025: u32 = 0; fiat_p384_mulx_u32(&mut x1024, &mut x1025, x992, 0xffffffff); let mut x1026: u32 = 0; let mut x1027: u32 = 0; fiat_p384_mulx_u32(&mut x1026, &mut x1027, x992, 0xffffffff); let mut x1028: u32 = 0; let mut x1029: u32 = 0; fiat_p384_mulx_u32(&mut x1028, &mut x1029, x992, 0xffffffff); let mut x1030: u32 = 0; let mut x1031: u32 = 0; fiat_p384_mulx_u32(&mut x1030, &mut x1031, x992, 0xffffffff); let mut x1032: u32 = 0; let mut x1033: u32 = 0; fiat_p384_mulx_u32(&mut x1032, &mut x1033, x992, 0xfffffffe); let mut x1034: u32 = 0; let mut x1035: u32 = 0; fiat_p384_mulx_u32(&mut x1034, &mut x1035, x992, 0xffffffff); let mut x1036: u32 = 0; let mut x1037: u32 = 0; fiat_p384_mulx_u32(&mut x1036, &mut x1037, x992, 0xffffffff); let mut x1038: u32 = 0; let mut x1039: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1038, &mut x1039, 0x0, x1035, x1032); let mut x1040: u32 = 0; let mut x1041: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1040, &mut x1041, x1039, x1033, x1030); let mut x1042: u32 = 0; let mut x1043: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1042, &mut x1043, x1041, x1031, x1028); let mut x1044: u32 = 0; let mut x1045: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1044, &mut x1045, x1043, x1029, x1026); let mut x1046: u32 = 0; let mut x1047: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1046, &mut x1047, x1045, x1027, x1024); let mut x1048: u32 = 0; let mut x1049: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1048, &mut x1049, x1047, x1025, x1022); let mut x1050: u32 = 0; let mut x1051: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1050, &mut x1051, x1049, x1023, x1020); let mut x1052: u32 = 0; let mut x1053: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1052, &mut x1053, x1051, x1021, x1018); let x1054: u32 = ((x1053 as u32) + x1019); let mut x1055: u32 = 0; let mut x1056: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1055, &mut x1056, 0x0, x992, x1036); let mut x1057: u32 = 0; let mut x1058: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1057, &mut x1058, x1056, x994, x1037); let mut x1059: u32 = 0; let mut x1060: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1059, &mut x1060, x1058, x996, (0x0 as u32)); let mut x1061: u32 = 0; let mut x1062: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1061, &mut x1062, x1060, x998, x1034); let mut x1063: u32 = 0; let mut x1064: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1063, &mut x1064, x1062, x1000, x1038); let mut x1065: u32 = 0; let mut x1066: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1065, &mut x1066, x1064, x1002, x1040); let mut x1067: u32 = 0; let mut x1068: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1067, &mut x1068, x1066, x1004, x1042); let mut x1069: u32 = 0; let mut x1070: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1069, &mut x1070, x1068, x1006, x1044); let mut x1071: u32 = 0; let mut x1072: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1071, &mut x1072, x1070, x1008, x1046); let mut x1073: u32 = 0; let mut x1074: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1073, &mut x1074, x1072, x1010, x1048); let mut x1075: u32 = 0; let mut x1076: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1075, &mut x1076, x1074, x1012, x1050); let mut x1077: u32 = 0; let mut x1078: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1077, &mut x1078, x1076, x1014, x1052); let mut x1079: u32 = 0; let mut x1080: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1079, &mut x1080, x1078, x1016, x1054); let x1081: u32 = ((x1080 as u32) + (x1017 as u32)); let mut x1082: u32 = 0; let mut x1083: u32 = 0; fiat_p384_mulx_u32(&mut x1082, &mut x1083, x8, (arg2[11])); let mut x1084: u32 = 0; let mut x1085: u32 = 0; fiat_p384_mulx_u32(&mut x1084, &mut x1085, x8, (arg2[10])); let mut x1086: u32 = 0; let mut x1087: u32 = 0; fiat_p384_mulx_u32(&mut x1086, &mut x1087, x8, (arg2[9])); let mut x1088: u32 = 0; let mut x1089: u32 = 0; fiat_p384_mulx_u32(&mut x1088, &mut x1089, x8, (arg2[8])); let mut x1090: u32 = 0; let mut x1091: u32 = 0; fiat_p384_mulx_u32(&mut x1090, &mut x1091, x8, (arg2[7])); let mut x1092: u32 = 0; let mut x1093: u32 = 0; fiat_p384_mulx_u32(&mut x1092, &mut x1093, x8, (arg2[6])); let mut x1094: u32 = 0; let mut x1095: u32 = 0; fiat_p384_mulx_u32(&mut x1094, &mut x1095, x8, (arg2[5])); let mut x1096: u32 = 0; let mut x1097: u32 = 0; fiat_p384_mulx_u32(&mut x1096, &mut x1097, x8, (arg2[4])); let mut x1098: u32 = 0; let mut x1099: u32 = 0; fiat_p384_mulx_u32(&mut x1098, &mut x1099, x8, (arg2[3])); let mut x1100: u32 = 0; let mut x1101: u32 = 0; fiat_p384_mulx_u32(&mut x1100, &mut x1101, x8, (arg2[2])); let mut x1102: u32 = 0; let mut x1103: u32 = 0; fiat_p384_mulx_u32(&mut x1102, &mut x1103, x8, (arg2[1])); let mut x1104: u32 = 0; let mut x1105: u32 = 0; fiat_p384_mulx_u32(&mut x1104, &mut x1105, x8, (arg2[0])); let mut x1106: u32 = 0; let mut x1107: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1106, &mut x1107, 0x0, x1105, x1102); let mut x1108: u32 = 0; let mut x1109: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1108, &mut x1109, x1107, x1103, x1100); let mut x1110: u32 = 0; let mut x1111: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1110, &mut x1111, x1109, x1101, x1098); let mut x1112: u32 = 0; let mut x1113: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1112, &mut x1113, x1111, x1099, x1096); let mut x1114: u32 = 0; let mut x1115: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1114, &mut x1115, x1113, x1097, x1094); let mut x1116: u32 = 0; let mut x1117: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1116, &mut x1117, x1115, x1095, x1092); let mut x1118: u32 = 0; let mut x1119: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1118, &mut x1119, x1117, x1093, x1090); let mut x1120: u32 = 0; let mut x1121: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1120, &mut x1121, x1119, x1091, x1088); let mut x1122: u32 = 0; let mut x1123: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1122, &mut x1123, x1121, x1089, x1086); let mut x1124: u32 = 0; let mut x1125: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1124, &mut x1125, x1123, x1087, x1084); let mut x1126: u32 = 0; let mut x1127: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1126, &mut x1127, x1125, x1085, x1082); let x1128: u32 = ((x1127 as u32) + x1083); let mut x1129: u32 = 0; let mut x1130: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1129, &mut x1130, 0x0, x1057, x1104); let mut x1131: u32 = 0; let mut x1132: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1131, &mut x1132, x1130, x1059, x1106); let mut x1133: u32 = 0; let mut x1134: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1133, &mut x1134, x1132, x1061, x1108); let mut x1135: u32 = 0; let mut x1136: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1135, &mut x1136, x1134, x1063, x1110); let mut x1137: u32 = 0; let mut x1138: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1137, &mut x1138, x1136, x1065, x1112); let mut x1139: u32 = 0; let mut x1140: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1139, &mut x1140, x1138, x1067, x1114); let mut x1141: u32 = 0; let mut x1142: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1141, &mut x1142, x1140, x1069, x1116); let mut x1143: u32 = 0; let mut x1144: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1143, &mut x1144, x1142, x1071, x1118); let mut x1145: u32 = 0; let mut x1146: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1145, &mut x1146, x1144, x1073, x1120); let mut x1147: u32 = 0; let mut x1148: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1147, &mut x1148, x1146, x1075, x1122); let mut x1149: u32 = 0; let mut x1150: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1149, &mut x1150, x1148, x1077, x1124); let mut x1151: u32 = 0; let mut x1152: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1151, &mut x1152, x1150, x1079, x1126); let mut x1153: u32 = 0; let mut x1154: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1153, &mut x1154, x1152, x1081, x1128); let mut x1155: u32 = 0; let mut x1156: u32 = 0; fiat_p384_mulx_u32(&mut x1155, &mut x1156, x1129, 0xffffffff); let mut x1157: u32 = 0; let mut x1158: u32 = 0; fiat_p384_mulx_u32(&mut x1157, &mut x1158, x1129, 0xffffffff); let mut x1159: u32 = 0; let mut x1160: u32 = 0; fiat_p384_mulx_u32(&mut x1159, &mut x1160, x1129, 0xffffffff); let mut x1161: u32 = 0; let mut x1162: u32 = 0; fiat_p384_mulx_u32(&mut x1161, &mut x1162, x1129, 0xffffffff); let mut x1163: u32 = 0; let mut x1164: u32 = 0; fiat_p384_mulx_u32(&mut x1163, &mut x1164, x1129, 0xffffffff); let mut x1165: u32 = 0; let mut x1166: u32 = 0; fiat_p384_mulx_u32(&mut x1165, &mut x1166, x1129, 0xffffffff); let mut x1167: u32 = 0; let mut x1168: u32 = 0; fiat_p384_mulx_u32(&mut x1167, &mut x1168, x1129, 0xffffffff); let mut x1169: u32 = 0; let mut x1170: u32 = 0; fiat_p384_mulx_u32(&mut x1169, &mut x1170, x1129, 0xfffffffe); let mut x1171: u32 = 0; let mut x1172: u32 = 0; fiat_p384_mulx_u32(&mut x1171, &mut x1172, x1129, 0xffffffff); let mut x1173: u32 = 0; let mut x1174: u32 = 0; fiat_p384_mulx_u32(&mut x1173, &mut x1174, x1129, 0xffffffff); let mut x1175: u32 = 0; let mut x1176: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1175, &mut x1176, 0x0, x1172, x1169); let mut x1177: u32 = 0; let mut x1178: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1177, &mut x1178, x1176, x1170, x1167); let mut x1179: u32 = 0; let mut x1180: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1179, &mut x1180, x1178, x1168, x1165); let mut x1181: u32 = 0; let mut x1182: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1181, &mut x1182, x1180, x1166, x1163); let mut x1183: u32 = 0; let mut x1184: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1183, &mut x1184, x1182, x1164, x1161); let mut x1185: u32 = 0; let mut x1186: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1185, &mut x1186, x1184, x1162, x1159); let mut x1187: u32 = 0; let mut x1188: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1187, &mut x1188, x1186, x1160, x1157); let mut x1189: u32 = 0; let mut x1190: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1189, &mut x1190, x1188, x1158, x1155); let x1191: u32 = ((x1190 as u32) + x1156); let mut x1192: u32 = 0; let mut x1193: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1192, &mut x1193, 0x0, x1129, x1173); let mut x1194: u32 = 0; let mut x1195: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1194, &mut x1195, x1193, x1131, x1174); let mut x1196: u32 = 0; let mut x1197: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1196, &mut x1197, x1195, x1133, (0x0 as u32)); let mut x1198: u32 = 0; let mut x1199: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1198, &mut x1199, x1197, x1135, x1171); let mut x1200: u32 = 0; let mut x1201: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1200, &mut x1201, x1199, x1137, x1175); let mut x1202: u32 = 0; let mut x1203: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1202, &mut x1203, x1201, x1139, x1177); let mut x1204: u32 = 0; let mut x1205: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1204, &mut x1205, x1203, x1141, x1179); let mut x1206: u32 = 0; let mut x1207: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1206, &mut x1207, x1205, x1143, x1181); let mut x1208: u32 = 0; let mut x1209: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1208, &mut x1209, x1207, x1145, x1183); let mut x1210: u32 = 0; let mut x1211: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1210, &mut x1211, x1209, x1147, x1185); let mut x1212: u32 = 0; let mut x1213: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1212, &mut x1213, x1211, x1149, x1187); let mut x1214: u32 = 0; let mut x1215: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1214, &mut x1215, x1213, x1151, x1189); let mut x1216: u32 = 0; let mut x1217: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1216, &mut x1217, x1215, x1153, x1191); let x1218: u32 = ((x1217 as u32) + (x1154 as u32)); let mut x1219: u32 = 0; let mut x1220: u32 = 0; fiat_p384_mulx_u32(&mut x1219, &mut x1220, x9, (arg2[11])); let mut x1221: u32 = 0; let mut x1222: u32 = 0; fiat_p384_mulx_u32(&mut x1221, &mut x1222, x9, (arg2[10])); let mut x1223: u32 = 0; let mut x1224: u32 = 0; fiat_p384_mulx_u32(&mut x1223, &mut x1224, x9, (arg2[9])); let mut x1225: u32 = 0; let mut x1226: u32 = 0; fiat_p384_mulx_u32(&mut x1225, &mut x1226, x9, (arg2[8])); let mut x1227: u32 = 0; let mut x1228: u32 = 0; fiat_p384_mulx_u32(&mut x1227, &mut x1228, x9, (arg2[7])); let mut x1229: u32 = 0; let mut x1230: u32 = 0; fiat_p384_mulx_u32(&mut x1229, &mut x1230, x9, (arg2[6])); let mut x1231: u32 = 0; let mut x1232: u32 = 0; fiat_p384_mulx_u32(&mut x1231, &mut x1232, x9, (arg2[5])); let mut x1233: u32 = 0; let mut x1234: u32 = 0; fiat_p384_mulx_u32(&mut x1233, &mut x1234, x9, (arg2[4])); let mut x1235: u32 = 0; let mut x1236: u32 = 0; fiat_p384_mulx_u32(&mut x1235, &mut x1236, x9, (arg2[3])); let mut x1237: u32 = 0; let mut x1238: u32 = 0; fiat_p384_mulx_u32(&mut x1237, &mut x1238, x9, (arg2[2])); let mut x1239: u32 = 0; let mut x1240: u32 = 0; fiat_p384_mulx_u32(&mut x1239, &mut x1240, x9, (arg2[1])); let mut x1241: u32 = 0; let mut x1242: u32 = 0; fiat_p384_mulx_u32(&mut x1241, &mut x1242, x9, (arg2[0])); let mut x1243: u32 = 0; let mut x1244: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1243, &mut x1244, 0x0, x1242, x1239); let mut x1245: u32 = 0; let mut x1246: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1245, &mut x1246, x1244, x1240, x1237); let mut x1247: u32 = 0; let mut x1248: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1247, &mut x1248, x1246, x1238, x1235); let mut x1249: u32 = 0; let mut x1250: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1249, &mut x1250, x1248, x1236, x1233); let mut x1251: u32 = 0; let mut x1252: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1251, &mut x1252, x1250, x1234, x1231); let mut x1253: u32 = 0; let mut x1254: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1253, &mut x1254, x1252, x1232, x1229); let mut x1255: u32 = 0; let mut x1256: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1255, &mut x1256, x1254, x1230, x1227); let mut x1257: u32 = 0; let mut x1258: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1257, &mut x1258, x1256, x1228, x1225); let mut x1259: u32 = 0; let mut x1260: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1259, &mut x1260, x1258, x1226, x1223); let mut x1261: u32 = 0; let mut x1262: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1261, &mut x1262, x1260, x1224, x1221); let mut x1263: u32 = 0; let mut x1264: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1263, &mut x1264, x1262, x1222, x1219); let x1265: u32 = ((x1264 as u32) + x1220); let mut x1266: u32 = 0; let mut x1267: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1266, &mut x1267, 0x0, x1194, x1241); let mut x1268: u32 = 0; let mut x1269: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1268, &mut x1269, x1267, x1196, x1243); let mut x1270: u32 = 0; let mut x1271: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1270, &mut x1271, x1269, x1198, x1245); let mut x1272: u32 = 0; let mut x1273: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1272, &mut x1273, x1271, x1200, x1247); let mut x1274: u32 = 0; let mut x1275: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1274, &mut x1275, x1273, x1202, x1249); let mut x1276: u32 = 0; let mut x1277: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1276, &mut x1277, x1275, x1204, x1251); let mut x1278: u32 = 0; let mut x1279: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1278, &mut x1279, x1277, x1206, x1253); let mut x1280: u32 = 0; let mut x1281: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1280, &mut x1281, x1279, x1208, x1255); let mut x1282: u32 = 0; let mut x1283: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1282, &mut x1283, x1281, x1210, x1257); let mut x1284: u32 = 0; let mut x1285: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1284, &mut x1285, x1283, x1212, x1259); let mut x1286: u32 = 0; let mut x1287: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1286, &mut x1287, x1285, x1214, x1261); let mut x1288: u32 = 0; let mut x1289: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1288, &mut x1289, x1287, x1216, x1263); let mut x1290: u32 = 0; let mut x1291: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1290, &mut x1291, x1289, x1218, x1265); let mut x1292: u32 = 0; let mut x1293: u32 = 0; fiat_p384_mulx_u32(&mut x1292, &mut x1293, x1266, 0xffffffff); let mut x1294: u32 = 0; let mut x1295: u32 = 0; fiat_p384_mulx_u32(&mut x1294, &mut x1295, x1266, 0xffffffff); let mut x1296: u32 = 0; let mut x1297: u32 = 0; fiat_p384_mulx_u32(&mut x1296, &mut x1297, x1266, 0xffffffff); let mut x1298: u32 = 0; let mut x1299: u32 = 0; fiat_p384_mulx_u32(&mut x1298, &mut x1299, x1266, 0xffffffff); let mut x1300: u32 = 0; let mut x1301: u32 = 0; fiat_p384_mulx_u32(&mut x1300, &mut x1301, x1266, 0xffffffff); let mut x1302: u32 = 0; let mut x1303: u32 = 0; fiat_p384_mulx_u32(&mut x1302, &mut x1303, x1266, 0xffffffff); let mut x1304: u32 = 0; let mut x1305: u32 = 0; fiat_p384_mulx_u32(&mut x1304, &mut x1305, x1266, 0xffffffff); let mut x1306: u32 = 0; let mut x1307: u32 = 0; fiat_p384_mulx_u32(&mut x1306, &mut x1307, x1266, 0xfffffffe); let mut x1308: u32 = 0; let mut x1309: u32 = 0; fiat_p384_mulx_u32(&mut x1308, &mut x1309, x1266, 0xffffffff); let mut x1310: u32 = 0; let mut x1311: u32 = 0; fiat_p384_mulx_u32(&mut x1310, &mut x1311, x1266, 0xffffffff); let mut x1312: u32 = 0; let mut x1313: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1312, &mut x1313, 0x0, x1309, x1306); let mut x1314: u32 = 0; let mut x1315: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1314, &mut x1315, x1313, x1307, x1304); let mut x1316: u32 = 0; let mut x1317: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1316, &mut x1317, x1315, x1305, x1302); let mut x1318: u32 = 0; let mut x1319: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1318, &mut x1319, x1317, x1303, x1300); let mut x1320: u32 = 0; let mut x1321: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1320, &mut x1321, x1319, x1301, x1298); let mut x1322: u32 = 0; let mut x1323: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1322, &mut x1323, x1321, x1299, x1296); let mut x1324: u32 = 0; let mut x1325: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1324, &mut x1325, x1323, x1297, x1294); let mut x1326: u32 = 0; let mut x1327: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1326, &mut x1327, x1325, x1295, x1292); let x1328: u32 = ((x1327 as u32) + x1293); let mut x1329: u32 = 0; let mut x1330: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1329, &mut x1330, 0x0, x1266, x1310); let mut x1331: u32 = 0; let mut x1332: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1331, &mut x1332, x1330, x1268, x1311); let mut x1333: u32 = 0; let mut x1334: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1333, &mut x1334, x1332, x1270, (0x0 as u32)); let mut x1335: u32 = 0; let mut x1336: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1335, &mut x1336, x1334, x1272, x1308); let mut x1337: u32 = 0; let mut x1338: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1337, &mut x1338, x1336, x1274, x1312); let mut x1339: u32 = 0; let mut x1340: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1339, &mut x1340, x1338, x1276, x1314); let mut x1341: u32 = 0; let mut x1342: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1341, &mut x1342, x1340, x1278, x1316); let mut x1343: u32 = 0; let mut x1344: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1343, &mut x1344, x1342, x1280, x1318); let mut x1345: u32 = 0; let mut x1346: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1345, &mut x1346, x1344, x1282, x1320); let mut x1347: u32 = 0; let mut x1348: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1347, &mut x1348, x1346, x1284, x1322); let mut x1349: u32 = 0; let mut x1350: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1349, &mut x1350, x1348, x1286, x1324); let mut x1351: u32 = 0; let mut x1352: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1351, &mut x1352, x1350, x1288, x1326); let mut x1353: u32 = 0; let mut x1354: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1353, &mut x1354, x1352, x1290, x1328); let x1355: u32 = ((x1354 as u32) + (x1291 as u32)); let mut x1356: u32 = 0; let mut x1357: u32 = 0; fiat_p384_mulx_u32(&mut x1356, &mut x1357, x10, (arg2[11])); let mut x1358: u32 = 0; let mut x1359: u32 = 0; fiat_p384_mulx_u32(&mut x1358, &mut x1359, x10, (arg2[10])); let mut x1360: u32 = 0; let mut x1361: u32 = 0; fiat_p384_mulx_u32(&mut x1360, &mut x1361, x10, (arg2[9])); let mut x1362: u32 = 0; let mut x1363: u32 = 0; fiat_p384_mulx_u32(&mut x1362, &mut x1363, x10, (arg2[8])); let mut x1364: u32 = 0; let mut x1365: u32 = 0; fiat_p384_mulx_u32(&mut x1364, &mut x1365, x10, (arg2[7])); let mut x1366: u32 = 0; let mut x1367: u32 = 0; fiat_p384_mulx_u32(&mut x1366, &mut x1367, x10, (arg2[6])); let mut x1368: u32 = 0; let mut x1369: u32 = 0; fiat_p384_mulx_u32(&mut x1368, &mut x1369, x10, (arg2[5])); let mut x1370: u32 = 0; let mut x1371: u32 = 0; fiat_p384_mulx_u32(&mut x1370, &mut x1371, x10, (arg2[4])); let mut x1372: u32 = 0; let mut x1373: u32 = 0; fiat_p384_mulx_u32(&mut x1372, &mut x1373, x10, (arg2[3])); let mut x1374: u32 = 0; let mut x1375: u32 = 0; fiat_p384_mulx_u32(&mut x1374, &mut x1375, x10, (arg2[2])); let mut x1376: u32 = 0; let mut x1377: u32 = 0; fiat_p384_mulx_u32(&mut x1376, &mut x1377, x10, (arg2[1])); let mut x1378: u32 = 0; let mut x1379: u32 = 0; fiat_p384_mulx_u32(&mut x1378, &mut x1379, x10, (arg2[0])); let mut x1380: u32 = 0; let mut x1381: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1380, &mut x1381, 0x0, x1379, x1376); let mut x1382: u32 = 0; let mut x1383: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1382, &mut x1383, x1381, x1377, x1374); let mut x1384: u32 = 0; let mut x1385: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1384, &mut x1385, x1383, x1375, x1372); let mut x1386: u32 = 0; let mut x1387: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1386, &mut x1387, x1385, x1373, x1370); let mut x1388: u32 = 0; let mut x1389: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1388, &mut x1389, x1387, x1371, x1368); let mut x1390: u32 = 0; let mut x1391: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1390, &mut x1391, x1389, x1369, x1366); let mut x1392: u32 = 0; let mut x1393: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1392, &mut x1393, x1391, x1367, x1364); let mut x1394: u32 = 0; let mut x1395: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1394, &mut x1395, x1393, x1365, x1362); let mut x1396: u32 = 0; let mut x1397: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1396, &mut x1397, x1395, x1363, x1360); let mut x1398: u32 = 0; let mut x1399: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1398, &mut x1399, x1397, x1361, x1358); let mut x1400: u32 = 0; let mut x1401: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1400, &mut x1401, x1399, x1359, x1356); let x1402: u32 = ((x1401 as u32) + x1357); let mut x1403: u32 = 0; let mut x1404: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1403, &mut x1404, 0x0, x1331, x1378); let mut x1405: u32 = 0; let mut x1406: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1405, &mut x1406, x1404, x1333, x1380); let mut x1407: u32 = 0; let mut x1408: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1407, &mut x1408, x1406, x1335, x1382); let mut x1409: u32 = 0; let mut x1410: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1409, &mut x1410, x1408, x1337, x1384); let mut x1411: u32 = 0; let mut x1412: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1411, &mut x1412, x1410, x1339, x1386); let mut x1413: u32 = 0; let mut x1414: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1413, &mut x1414, x1412, x1341, x1388); let mut x1415: u32 = 0; let mut x1416: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1415, &mut x1416, x1414, x1343, x1390); let mut x1417: u32 = 0; let mut x1418: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1417, &mut x1418, x1416, x1345, x1392); let mut x1419: u32 = 0; let mut x1420: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1419, &mut x1420, x1418, x1347, x1394); let mut x1421: u32 = 0; let mut x1422: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1421, &mut x1422, x1420, x1349, x1396); let mut x1423: u32 = 0; let mut x1424: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1423, &mut x1424, x1422, x1351, x1398); let mut x1425: u32 = 0; let mut x1426: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1425, &mut x1426, x1424, x1353, x1400); let mut x1427: u32 = 0; let mut x1428: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1427, &mut x1428, x1426, x1355, x1402); let mut x1429: u32 = 0; let mut x1430: u32 = 0; fiat_p384_mulx_u32(&mut x1429, &mut x1430, x1403, 0xffffffff); let mut x1431: u32 = 0; let mut x1432: u32 = 0; fiat_p384_mulx_u32(&mut x1431, &mut x1432, x1403, 0xffffffff); let mut x1433: u32 = 0; let mut x1434: u32 = 0; fiat_p384_mulx_u32(&mut x1433, &mut x1434, x1403, 0xffffffff); let mut x1435: u32 = 0; let mut x1436: u32 = 0; fiat_p384_mulx_u32(&mut x1435, &mut x1436, x1403, 0xffffffff); let mut x1437: u32 = 0; let mut x1438: u32 = 0; fiat_p384_mulx_u32(&mut x1437, &mut x1438, x1403, 0xffffffff); let mut x1439: u32 = 0; let mut x1440: u32 = 0; fiat_p384_mulx_u32(&mut x1439, &mut x1440, x1403, 0xffffffff); let mut x1441: u32 = 0; let mut x1442: u32 = 0; fiat_p384_mulx_u32(&mut x1441, &mut x1442, x1403, 0xffffffff); let mut x1443: u32 = 0; let mut x1444: u32 = 0; fiat_p384_mulx_u32(&mut x1443, &mut x1444, x1403, 0xfffffffe); let mut x1445: u32 = 0; let mut x1446: u32 = 0; fiat_p384_mulx_u32(&mut x1445, &mut x1446, x1403, 0xffffffff); let mut x1447: u32 = 0; let mut x1448: u32 = 0; fiat_p384_mulx_u32(&mut x1447, &mut x1448, x1403, 0xffffffff); let mut x1449: u32 = 0; let mut x1450: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1449, &mut x1450, 0x0, x1446, x1443); let mut x1451: u32 = 0; let mut x1452: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1451, &mut x1452, x1450, x1444, x1441); let mut x1453: u32 = 0; let mut x1454: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1453, &mut x1454, x1452, x1442, x1439); let mut x1455: u32 = 0; let mut x1456: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1455, &mut x1456, x1454, x1440, x1437); let mut x1457: u32 = 0; let mut x1458: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1457, &mut x1458, x1456, x1438, x1435); let mut x1459: u32 = 0; let mut x1460: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1459, &mut x1460, x1458, x1436, x1433); let mut x1461: u32 = 0; let mut x1462: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1461, &mut x1462, x1460, x1434, x1431); let mut x1463: u32 = 0; let mut x1464: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1463, &mut x1464, x1462, x1432, x1429); let x1465: u32 = ((x1464 as u32) + x1430); let mut x1466: u32 = 0; let mut x1467: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1466, &mut x1467, 0x0, x1403, x1447); let mut x1468: u32 = 0; let mut x1469: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1468, &mut x1469, x1467, x1405, x1448); let mut x1470: u32 = 0; let mut x1471: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1470, &mut x1471, x1469, x1407, (0x0 as u32)); let mut x1472: u32 = 0; let mut x1473: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1472, &mut x1473, x1471, x1409, x1445); let mut x1474: u32 = 0; let mut x1475: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1474, &mut x1475, x1473, x1411, x1449); let mut x1476: u32 = 0; let mut x1477: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1476, &mut x1477, x1475, x1413, x1451); let mut x1478: u32 = 0; let mut x1479: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1478, &mut x1479, x1477, x1415, x1453); let mut x1480: u32 = 0; let mut x1481: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1480, &mut x1481, x1479, x1417, x1455); let mut x1482: u32 = 0; let mut x1483: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1482, &mut x1483, x1481, x1419, x1457); let mut x1484: u32 = 0; let mut x1485: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1484, &mut x1485, x1483, x1421, x1459); let mut x1486: u32 = 0; let mut x1487: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1486, &mut x1487, x1485, x1423, x1461); let mut x1488: u32 = 0; let mut x1489: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1488, &mut x1489, x1487, x1425, x1463); let mut x1490: u32 = 0; let mut x1491: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1490, &mut x1491, x1489, x1427, x1465); let x1492: u32 = ((x1491 as u32) + (x1428 as u32)); let mut x1493: u32 = 0; let mut x1494: u32 = 0; fiat_p384_mulx_u32(&mut x1493, &mut x1494, x11, (arg2[11])); let mut x1495: u32 = 0; let mut x1496: u32 = 0; fiat_p384_mulx_u32(&mut x1495, &mut x1496, x11, (arg2[10])); let mut x1497: u32 = 0; let mut x1498: u32 = 0; fiat_p384_mulx_u32(&mut x1497, &mut x1498, x11, (arg2[9])); let mut x1499: u32 = 0; let mut x1500: u32 = 0; fiat_p384_mulx_u32(&mut x1499, &mut x1500, x11, (arg2[8])); let mut x1501: u32 = 0; let mut x1502: u32 = 0; fiat_p384_mulx_u32(&mut x1501, &mut x1502, x11, (arg2[7])); let mut x1503: u32 = 0; let mut x1504: u32 = 0; fiat_p384_mulx_u32(&mut x1503, &mut x1504, x11, (arg2[6])); let mut x1505: u32 = 0; let mut x1506: u32 = 0; fiat_p384_mulx_u32(&mut x1505, &mut x1506, x11, (arg2[5])); let mut x1507: u32 = 0; let mut x1508: u32 = 0; fiat_p384_mulx_u32(&mut x1507, &mut x1508, x11, (arg2[4])); let mut x1509: u32 = 0; let mut x1510: u32 = 0; fiat_p384_mulx_u32(&mut x1509, &mut x1510, x11, (arg2[3])); let mut x1511: u32 = 0; let mut x1512: u32 = 0; fiat_p384_mulx_u32(&mut x1511, &mut x1512, x11, (arg2[2])); let mut x1513: u32 = 0; let mut x1514: u32 = 0; fiat_p384_mulx_u32(&mut x1513, &mut x1514, x11, (arg2[1])); let mut x1515: u32 = 0; let mut x1516: u32 = 0; fiat_p384_mulx_u32(&mut x1515, &mut x1516, x11, (arg2[0])); let mut x1517: u32 = 0; let mut x1518: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1517, &mut x1518, 0x0, x1516, x1513); let mut x1519: u32 = 0; let mut x1520: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1519, &mut x1520, x1518, x1514, x1511); let mut x1521: u32 = 0; let mut x1522: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1521, &mut x1522, x1520, x1512, x1509); let mut x1523: u32 = 0; let mut x1524: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1523, &mut x1524, x1522, x1510, x1507); let mut x1525: u32 = 0; let mut x1526: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1525, &mut x1526, x1524, x1508, x1505); let mut x1527: u32 = 0; let mut x1528: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1527, &mut x1528, x1526, x1506, x1503); let mut x1529: u32 = 0; let mut x1530: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1529, &mut x1530, x1528, x1504, x1501); let mut x1531: u32 = 0; let mut x1532: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1531, &mut x1532, x1530, x1502, x1499); let mut x1533: u32 = 0; let mut x1534: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1533, &mut x1534, x1532, x1500, x1497); let mut x1535: u32 = 0; let mut x1536: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1535, &mut x1536, x1534, x1498, x1495); let mut x1537: u32 = 0; let mut x1538: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1537, &mut x1538, x1536, x1496, x1493); let x1539: u32 = ((x1538 as u32) + x1494); let mut x1540: u32 = 0; let mut x1541: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1540, &mut x1541, 0x0, x1468, x1515); let mut x1542: u32 = 0; let mut x1543: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1542, &mut x1543, x1541, x1470, x1517); let mut x1544: u32 = 0; let mut x1545: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1544, &mut x1545, x1543, x1472, x1519); let mut x1546: u32 = 0; let mut x1547: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1546, &mut x1547, x1545, x1474, x1521); let mut x1548: u32 = 0; let mut x1549: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1548, &mut x1549, x1547, x1476, x1523); let mut x1550: u32 = 0; let mut x1551: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1550, &mut x1551, x1549, x1478, x1525); let mut x1552: u32 = 0; let mut x1553: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1552, &mut x1553, x1551, x1480, x1527); let mut x1554: u32 = 0; let mut x1555: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1554, &mut x1555, x1553, x1482, x1529); let mut x1556: u32 = 0; let mut x1557: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1556, &mut x1557, x1555, x1484, x1531); let mut x1558: u32 = 0; let mut x1559: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1558, &mut x1559, x1557, x1486, x1533); let mut x1560: u32 = 0; let mut x1561: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1560, &mut x1561, x1559, x1488, x1535); let mut x1562: u32 = 0; let mut x1563: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1562, &mut x1563, x1561, x1490, x1537); let mut x1564: u32 = 0; let mut x1565: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1564, &mut x1565, x1563, x1492, x1539); let mut x1566: u32 = 0; let mut x1567: u32 = 0; fiat_p384_mulx_u32(&mut x1566, &mut x1567, x1540, 0xffffffff); let mut x1568: u32 = 0; let mut x1569: u32 = 0; fiat_p384_mulx_u32(&mut x1568, &mut x1569, x1540, 0xffffffff); let mut x1570: u32 = 0; let mut x1571: u32 = 0; fiat_p384_mulx_u32(&mut x1570, &mut x1571, x1540, 0xffffffff); let mut x1572: u32 = 0; let mut x1573: u32 = 0; fiat_p384_mulx_u32(&mut x1572, &mut x1573, x1540, 0xffffffff); let mut x1574: u32 = 0; let mut x1575: u32 = 0; fiat_p384_mulx_u32(&mut x1574, &mut x1575, x1540, 0xffffffff); let mut x1576: u32 = 0; let mut x1577: u32 = 0; fiat_p384_mulx_u32(&mut x1576, &mut x1577, x1540, 0xffffffff); let mut x1578: u32 = 0; let mut x1579: u32 = 0; fiat_p384_mulx_u32(&mut x1578, &mut x1579, x1540, 0xffffffff); let mut x1580: u32 = 0; let mut x1581: u32 = 0; fiat_p384_mulx_u32(&mut x1580, &mut x1581, x1540, 0xfffffffe); let mut x1582: u32 = 0; let mut x1583: u32 = 0; fiat_p384_mulx_u32(&mut x1582, &mut x1583, x1540, 0xffffffff); let mut x1584: u32 = 0; let mut x1585: u32 = 0; fiat_p384_mulx_u32(&mut x1584, &mut x1585, x1540, 0xffffffff); let mut x1586: u32 = 0; let mut x1587: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1586, &mut x1587, 0x0, x1583, x1580); let mut x1588: u32 = 0; let mut x1589: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1588, &mut x1589, x1587, x1581, x1578); let mut x1590: u32 = 0; let mut x1591: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1590, &mut x1591, x1589, x1579, x1576); let mut x1592: u32 = 0; let mut x1593: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1592, &mut x1593, x1591, x1577, x1574); let mut x1594: u32 = 0; let mut x1595: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1594, &mut x1595, x1593, x1575, x1572); let mut x1596: u32 = 0; let mut x1597: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1596, &mut x1597, x1595, x1573, x1570); let mut x1598: u32 = 0; let mut x1599: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1598, &mut x1599, x1597, x1571, x1568); let mut x1600: u32 = 0; let mut x1601: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1600, &mut x1601, x1599, x1569, x1566); let x1602: u32 = ((x1601 as u32) + x1567); let mut x1603: u32 = 0; let mut x1604: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1603, &mut x1604, 0x0, x1540, x1584); let mut x1605: u32 = 0; let mut x1606: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1605, &mut x1606, x1604, x1542, x1585); let mut x1607: u32 = 0; let mut x1608: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1607, &mut x1608, x1606, x1544, (0x0 as u32)); let mut x1609: u32 = 0; let mut x1610: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1609, &mut x1610, x1608, x1546, x1582); let mut x1611: u32 = 0; let mut x1612: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1611, &mut x1612, x1610, x1548, x1586); let mut x1613: u32 = 0; let mut x1614: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1613, &mut x1614, x1612, x1550, x1588); let mut x1615: u32 = 0; let mut x1616: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1615, &mut x1616, x1614, x1552, x1590); let mut x1617: u32 = 0; let mut x1618: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1617, &mut x1618, x1616, x1554, x1592); let mut x1619: u32 = 0; let mut x1620: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1619, &mut x1620, x1618, x1556, x1594); let mut x1621: u32 = 0; let mut x1622: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1621, &mut x1622, x1620, x1558, x1596); let mut x1623: u32 = 0; let mut x1624: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1623, &mut x1624, x1622, x1560, x1598); let mut x1625: u32 = 0; let mut x1626: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1625, &mut x1626, x1624, x1562, x1600); let mut x1627: u32 = 0; let mut x1628: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1627, &mut x1628, x1626, x1564, x1602); let x1629: u32 = ((x1628 as u32) + (x1565 as u32)); let mut x1630: u32 = 0; let mut x1631: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1630, &mut x1631, 0x0, x1605, 0xffffffff); let mut x1632: u32 = 0; let mut x1633: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1632, &mut x1633, x1631, x1607, (0x0 as u32)); let mut x1634: u32 = 0; let mut x1635: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1634, &mut x1635, x1633, x1609, (0x0 as u32)); let mut x1636: u32 = 0; let mut x1637: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1636, &mut x1637, x1635, x1611, 0xffffffff); let mut x1638: u32 = 0; let mut x1639: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1638, &mut x1639, x1637, x1613, 0xfffffffe); let mut x1640: u32 = 0; let mut x1641: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1640, &mut x1641, x1639, x1615, 0xffffffff); let mut x1642: u32 = 0; let mut x1643: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1642, &mut x1643, x1641, x1617, 0xffffffff); let mut x1644: u32 = 0; let mut x1645: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1644, &mut x1645, x1643, x1619, 0xffffffff); let mut x1646: u32 = 0; let mut x1647: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1646, &mut x1647, x1645, x1621, 0xffffffff); let mut x1648: u32 = 0; let mut x1649: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1648, &mut x1649, x1647, x1623, 0xffffffff); let mut x1650: u32 = 0; let mut x1651: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1650, &mut x1651, x1649, x1625, 0xffffffff); let mut x1652: u32 = 0; let mut x1653: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1652, &mut x1653, x1651, x1627, 0xffffffff); let mut x1654: u32 = 0; let mut x1655: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1654, &mut x1655, x1653, x1629, (0x0 as u32)); let mut x1656: u32 = 0; fiat_p384_cmovznz_u32(&mut x1656, x1655, x1630, x1605); let mut x1657: u32 = 0; fiat_p384_cmovznz_u32(&mut x1657, x1655, x1632, x1607); let mut x1658: u32 = 0; fiat_p384_cmovznz_u32(&mut x1658, x1655, x1634, x1609); let mut x1659: u32 = 0; fiat_p384_cmovznz_u32(&mut x1659, x1655, x1636, x1611); let mut x1660: u32 = 0; fiat_p384_cmovznz_u32(&mut x1660, x1655, x1638, x1613); let mut x1661: u32 = 0; fiat_p384_cmovznz_u32(&mut x1661, x1655, x1640, x1615); let mut x1662: u32 = 0; fiat_p384_cmovznz_u32(&mut x1662, x1655, x1642, x1617); let mut x1663: u32 = 0; fiat_p384_cmovznz_u32(&mut x1663, x1655, x1644, x1619); let mut x1664: u32 = 0; fiat_p384_cmovznz_u32(&mut x1664, x1655, x1646, x1621); let mut x1665: u32 = 0; fiat_p384_cmovznz_u32(&mut x1665, x1655, x1648, x1623); let mut x1666: u32 = 0; fiat_p384_cmovznz_u32(&mut x1666, x1655, x1650, x1625); let mut x1667: u32 = 0; fiat_p384_cmovznz_u32(&mut x1667, x1655, x1652, x1627); out1[0] = x1656; out1[1] = x1657; out1[2] = x1658; out1[3] = x1659; out1[4] = x1660; out1[5] = x1661; out1[6] = x1662; out1[7] = x1663; out1[8] = x1664; out1[9] = x1665; out1[10] = x1666; out1[11] = x1667; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_square(out1: &mut [u32; 12], arg1: &[u32; 12]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[8]); let x9: u32 = (arg1[9]); let x10: u32 = (arg1[10]); let x11: u32 = (arg1[11]); let x12: u32 = (arg1[0]); let mut x13: u32 = 0; let mut x14: u32 = 0; fiat_p384_mulx_u32(&mut x13, &mut x14, x12, (arg1[11])); let mut x15: u32 = 0; let mut x16: u32 = 0; fiat_p384_mulx_u32(&mut x15, &mut x16, x12, (arg1[10])); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_p384_mulx_u32(&mut x17, &mut x18, x12, (arg1[9])); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_p384_mulx_u32(&mut x19, &mut x20, x12, (arg1[8])); let mut x21: u32 = 0; let mut x22: u32 = 0; fiat_p384_mulx_u32(&mut x21, &mut x22, x12, (arg1[7])); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_p384_mulx_u32(&mut x23, &mut x24, x12, (arg1[6])); let mut x25: u32 = 0; let mut x26: u32 = 0; fiat_p384_mulx_u32(&mut x25, &mut x26, x12, (arg1[5])); let mut x27: u32 = 0; let mut x28: u32 = 0; fiat_p384_mulx_u32(&mut x27, &mut x28, x12, (arg1[4])); let mut x29: u32 = 0; let mut x30: u32 = 0; fiat_p384_mulx_u32(&mut x29, &mut x30, x12, (arg1[3])); let mut x31: u32 = 0; let mut x32: u32 = 0; fiat_p384_mulx_u32(&mut x31, &mut x32, x12, (arg1[2])); let mut x33: u32 = 0; let mut x34: u32 = 0; fiat_p384_mulx_u32(&mut x33, &mut x34, x12, (arg1[1])); let mut x35: u32 = 0; let mut x36: u32 = 0; fiat_p384_mulx_u32(&mut x35, &mut x36, x12, (arg1[0])); let mut x37: u32 = 0; let mut x38: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x37, &mut x38, 0x0, x36, x33); let mut x39: u32 = 0; let mut x40: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x39, &mut x40, x38, x34, x31); let mut x41: u32 = 0; let mut x42: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x41, &mut x42, x40, x32, x29); let mut x43: u32 = 0; let mut x44: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x43, &mut x44, x42, x30, x27); let mut x45: u32 = 0; let mut x46: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x45, &mut x46, x44, x28, x25); let mut x47: u32 = 0; let mut x48: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x47, &mut x48, x46, x26, x23); let mut x49: u32 = 0; let mut x50: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x49, &mut x50, x48, x24, x21); let mut x51: u32 = 0; let mut x52: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x51, &mut x52, x50, x22, x19); let mut x53: u32 = 0; let mut x54: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x53, &mut x54, x52, x20, x17); let mut x55: u32 = 0; let mut x56: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x55, &mut x56, x54, x18, x15); let mut x57: u32 = 0; let mut x58: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x57, &mut x58, x56, x16, x13); let x59: u32 = ((x58 as u32) + x14); let mut x60: u32 = 0; let mut x61: u32 = 0; fiat_p384_mulx_u32(&mut x60, &mut x61, x35, 0xffffffff); let mut x62: u32 = 0; let mut x63: u32 = 0; fiat_p384_mulx_u32(&mut x62, &mut x63, x35, 0xffffffff); let mut x64: u32 = 0; let mut x65: u32 = 0; fiat_p384_mulx_u32(&mut x64, &mut x65, x35, 0xffffffff); let mut x66: u32 = 0; let mut x67: u32 = 0; fiat_p384_mulx_u32(&mut x66, &mut x67, x35, 0xffffffff); let mut x68: u32 = 0; let mut x69: u32 = 0; fiat_p384_mulx_u32(&mut x68, &mut x69, x35, 0xffffffff); let mut x70: u32 = 0; let mut x71: u32 = 0; fiat_p384_mulx_u32(&mut x70, &mut x71, x35, 0xffffffff); let mut x72: u32 = 0; let mut x73: u32 = 0; fiat_p384_mulx_u32(&mut x72, &mut x73, x35, 0xffffffff); let mut x74: u32 = 0; let mut x75: u32 = 0; fiat_p384_mulx_u32(&mut x74, &mut x75, x35, 0xfffffffe); let mut x76: u32 = 0; let mut x77: u32 = 0; fiat_p384_mulx_u32(&mut x76, &mut x77, x35, 0xffffffff); let mut x78: u32 = 0; let mut x79: u32 = 0; fiat_p384_mulx_u32(&mut x78, &mut x79, x35, 0xffffffff); let mut x80: u32 = 0; let mut x81: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x80, &mut x81, 0x0, x77, x74); let mut x82: u32 = 0; let mut x83: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x82, &mut x83, x81, x75, x72); let mut x84: u32 = 0; let mut x85: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x84, &mut x85, x83, x73, x70); let mut x86: u32 = 0; let mut x87: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x86, &mut x87, x85, x71, x68); let mut x88: u32 = 0; let mut x89: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x88, &mut x89, x87, x69, x66); let mut x90: u32 = 0; let mut x91: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x90, &mut x91, x89, x67, x64); let mut x92: u32 = 0; let mut x93: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x92, &mut x93, x91, x65, x62); let mut x94: u32 = 0; let mut x95: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x94, &mut x95, x93, x63, x60); let x96: u32 = ((x95 as u32) + x61); let mut x97: u32 = 0; let mut x98: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x97, &mut x98, 0x0, x35, x78); let mut x99: u32 = 0; let mut x100: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x99, &mut x100, x98, x37, x79); let mut x101: u32 = 0; let mut x102: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x101, &mut x102, x100, x39, (0x0 as u32)); let mut x103: u32 = 0; let mut x104: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x103, &mut x104, x102, x41, x76); let mut x105: u32 = 0; let mut x106: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x105, &mut x106, x104, x43, x80); let mut x107: u32 = 0; let mut x108: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x107, &mut x108, x106, x45, x82); let mut x109: u32 = 0; let mut x110: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x109, &mut x110, x108, x47, x84); let mut x111: u32 = 0; let mut x112: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x111, &mut x112, x110, x49, x86); let mut x113: u32 = 0; let mut x114: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x113, &mut x114, x112, x51, x88); let mut x115: u32 = 0; let mut x116: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x115, &mut x116, x114, x53, x90); let mut x117: u32 = 0; let mut x118: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x117, &mut x118, x116, x55, x92); let mut x119: u32 = 0; let mut x120: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x119, &mut x120, x118, x57, x94); let mut x121: u32 = 0; let mut x122: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x121, &mut x122, x120, x59, x96); let mut x123: u32 = 0; let mut x124: u32 = 0; fiat_p384_mulx_u32(&mut x123, &mut x124, x1, (arg1[11])); let mut x125: u32 = 0; let mut x126: u32 = 0; fiat_p384_mulx_u32(&mut x125, &mut x126, x1, (arg1[10])); let mut x127: u32 = 0; let mut x128: u32 = 0; fiat_p384_mulx_u32(&mut x127, &mut x128, x1, (arg1[9])); let mut x129: u32 = 0; let mut x130: u32 = 0; fiat_p384_mulx_u32(&mut x129, &mut x130, x1, (arg1[8])); let mut x131: u32 = 0; let mut x132: u32 = 0; fiat_p384_mulx_u32(&mut x131, &mut x132, x1, (arg1[7])); let mut x133: u32 = 0; let mut x134: u32 = 0; fiat_p384_mulx_u32(&mut x133, &mut x134, x1, (arg1[6])); let mut x135: u32 = 0; let mut x136: u32 = 0; fiat_p384_mulx_u32(&mut x135, &mut x136, x1, (arg1[5])); let mut x137: u32 = 0; let mut x138: u32 = 0; fiat_p384_mulx_u32(&mut x137, &mut x138, x1, (arg1[4])); let mut x139: u32 = 0; let mut x140: u32 = 0; fiat_p384_mulx_u32(&mut x139, &mut x140, x1, (arg1[3])); let mut x141: u32 = 0; let mut x142: u32 = 0; fiat_p384_mulx_u32(&mut x141, &mut x142, x1, (arg1[2])); let mut x143: u32 = 0; let mut x144: u32 = 0; fiat_p384_mulx_u32(&mut x143, &mut x144, x1, (arg1[1])); let mut x145: u32 = 0; let mut x146: u32 = 0; fiat_p384_mulx_u32(&mut x145, &mut x146, x1, (arg1[0])); let mut x147: u32 = 0; let mut x148: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x147, &mut x148, 0x0, x146, x143); let mut x149: u32 = 0; let mut x150: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x149, &mut x150, x148, x144, x141); let mut x151: u32 = 0; let mut x152: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x151, &mut x152, x150, x142, x139); let mut x153: u32 = 0; let mut x154: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x153, &mut x154, x152, x140, x137); let mut x155: u32 = 0; let mut x156: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x155, &mut x156, x154, x138, x135); let mut x157: u32 = 0; let mut x158: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x157, &mut x158, x156, x136, x133); let mut x159: u32 = 0; let mut x160: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x159, &mut x160, x158, x134, x131); let mut x161: u32 = 0; let mut x162: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x161, &mut x162, x160, x132, x129); let mut x163: u32 = 0; let mut x164: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x163, &mut x164, x162, x130, x127); let mut x165: u32 = 0; let mut x166: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x165, &mut x166, x164, x128, x125); let mut x167: u32 = 0; let mut x168: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x167, &mut x168, x166, x126, x123); let x169: u32 = ((x168 as u32) + x124); let mut x170: u32 = 0; let mut x171: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x170, &mut x171, 0x0, x99, x145); let mut x172: u32 = 0; let mut x173: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x172, &mut x173, x171, x101, x147); let mut x174: u32 = 0; let mut x175: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x174, &mut x175, x173, x103, x149); let mut x176: u32 = 0; let mut x177: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x176, &mut x177, x175, x105, x151); let mut x178: u32 = 0; let mut x179: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x178, &mut x179, x177, x107, x153); let mut x180: u32 = 0; let mut x181: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x180, &mut x181, x179, x109, x155); let mut x182: u32 = 0; let mut x183: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x182, &mut x183, x181, x111, x157); let mut x184: u32 = 0; let mut x185: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x184, &mut x185, x183, x113, x159); let mut x186: u32 = 0; let mut x187: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x186, &mut x187, x185, x115, x161); let mut x188: u32 = 0; let mut x189: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x188, &mut x189, x187, x117, x163); let mut x190: u32 = 0; let mut x191: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x190, &mut x191, x189, x119, x165); let mut x192: u32 = 0; let mut x193: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x192, &mut x193, x191, x121, x167); let mut x194: u32 = 0; let mut x195: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x194, &mut x195, x193, (x122 as u32), x169); let mut x196: u32 = 0; let mut x197: u32 = 0; fiat_p384_mulx_u32(&mut x196, &mut x197, x170, 0xffffffff); let mut x198: u32 = 0; let mut x199: u32 = 0; fiat_p384_mulx_u32(&mut x198, &mut x199, x170, 0xffffffff); let mut x200: u32 = 0; let mut x201: u32 = 0; fiat_p384_mulx_u32(&mut x200, &mut x201, x170, 0xffffffff); let mut x202: u32 = 0; let mut x203: u32 = 0; fiat_p384_mulx_u32(&mut x202, &mut x203, x170, 0xffffffff); let mut x204: u32 = 0; let mut x205: u32 = 0; fiat_p384_mulx_u32(&mut x204, &mut x205, x170, 0xffffffff); let mut x206: u32 = 0; let mut x207: u32 = 0; fiat_p384_mulx_u32(&mut x206, &mut x207, x170, 0xffffffff); let mut x208: u32 = 0; let mut x209: u32 = 0; fiat_p384_mulx_u32(&mut x208, &mut x209, x170, 0xffffffff); let mut x210: u32 = 0; let mut x211: u32 = 0; fiat_p384_mulx_u32(&mut x210, &mut x211, x170, 0xfffffffe); let mut x212: u32 = 0; let mut x213: u32 = 0; fiat_p384_mulx_u32(&mut x212, &mut x213, x170, 0xffffffff); let mut x214: u32 = 0; let mut x215: u32 = 0; fiat_p384_mulx_u32(&mut x214, &mut x215, x170, 0xffffffff); let mut x216: u32 = 0; let mut x217: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x216, &mut x217, 0x0, x213, x210); let mut x218: u32 = 0; let mut x219: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x218, &mut x219, x217, x211, x208); let mut x220: u32 = 0; let mut x221: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x220, &mut x221, x219, x209, x206); let mut x222: u32 = 0; let mut x223: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x222, &mut x223, x221, x207, x204); let mut x224: u32 = 0; let mut x225: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x224, &mut x225, x223, x205, x202); let mut x226: u32 = 0; let mut x227: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x226, &mut x227, x225, x203, x200); let mut x228: u32 = 0; let mut x229: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x228, &mut x229, x227, x201, x198); let mut x230: u32 = 0; let mut x231: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x230, &mut x231, x229, x199, x196); let x232: u32 = ((x231 as u32) + x197); let mut x233: u32 = 0; let mut x234: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x233, &mut x234, 0x0, x170, x214); let mut x235: u32 = 0; let mut x236: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x235, &mut x236, x234, x172, x215); let mut x237: u32 = 0; let mut x238: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x237, &mut x238, x236, x174, (0x0 as u32)); let mut x239: u32 = 0; let mut x240: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x239, &mut x240, x238, x176, x212); let mut x241: u32 = 0; let mut x242: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x241, &mut x242, x240, x178, x216); let mut x243: u32 = 0; let mut x244: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x243, &mut x244, x242, x180, x218); let mut x245: u32 = 0; let mut x246: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x245, &mut x246, x244, x182, x220); let mut x247: u32 = 0; let mut x248: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x247, &mut x248, x246, x184, x222); let mut x249: u32 = 0; let mut x250: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x249, &mut x250, x248, x186, x224); let mut x251: u32 = 0; let mut x252: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x251, &mut x252, x250, x188, x226); let mut x253: u32 = 0; let mut x254: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x253, &mut x254, x252, x190, x228); let mut x255: u32 = 0; let mut x256: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x255, &mut x256, x254, x192, x230); let mut x257: u32 = 0; let mut x258: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x257, &mut x258, x256, x194, x232); let x259: u32 = ((x258 as u32) + (x195 as u32)); let mut x260: u32 = 0; let mut x261: u32 = 0; fiat_p384_mulx_u32(&mut x260, &mut x261, x2, (arg1[11])); let mut x262: u32 = 0; let mut x263: u32 = 0; fiat_p384_mulx_u32(&mut x262, &mut x263, x2, (arg1[10])); let mut x264: u32 = 0; let mut x265: u32 = 0; fiat_p384_mulx_u32(&mut x264, &mut x265, x2, (arg1[9])); let mut x266: u32 = 0; let mut x267: u32 = 0; fiat_p384_mulx_u32(&mut x266, &mut x267, x2, (arg1[8])); let mut x268: u32 = 0; let mut x269: u32 = 0; fiat_p384_mulx_u32(&mut x268, &mut x269, x2, (arg1[7])); let mut x270: u32 = 0; let mut x271: u32 = 0; fiat_p384_mulx_u32(&mut x270, &mut x271, x2, (arg1[6])); let mut x272: u32 = 0; let mut x273: u32 = 0; fiat_p384_mulx_u32(&mut x272, &mut x273, x2, (arg1[5])); let mut x274: u32 = 0; let mut x275: u32 = 0; fiat_p384_mulx_u32(&mut x274, &mut x275, x2, (arg1[4])); let mut x276: u32 = 0; let mut x277: u32 = 0; fiat_p384_mulx_u32(&mut x276, &mut x277, x2, (arg1[3])); let mut x278: u32 = 0; let mut x279: u32 = 0; fiat_p384_mulx_u32(&mut x278, &mut x279, x2, (arg1[2])); let mut x280: u32 = 0; let mut x281: u32 = 0; fiat_p384_mulx_u32(&mut x280, &mut x281, x2, (arg1[1])); let mut x282: u32 = 0; let mut x283: u32 = 0; fiat_p384_mulx_u32(&mut x282, &mut x283, x2, (arg1[0])); let mut x284: u32 = 0; let mut x285: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x284, &mut x285, 0x0, x283, x280); let mut x286: u32 = 0; let mut x287: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x286, &mut x287, x285, x281, x278); let mut x288: u32 = 0; let mut x289: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x288, &mut x289, x287, x279, x276); let mut x290: u32 = 0; let mut x291: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x290, &mut x291, x289, x277, x274); let mut x292: u32 = 0; let mut x293: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x292, &mut x293, x291, x275, x272); let mut x294: u32 = 0; let mut x295: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x294, &mut x295, x293, x273, x270); let mut x296: u32 = 0; let mut x297: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x296, &mut x297, x295, x271, x268); let mut x298: u32 = 0; let mut x299: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x298, &mut x299, x297, x269, x266); let mut x300: u32 = 0; let mut x301: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x300, &mut x301, x299, x267, x264); let mut x302: u32 = 0; let mut x303: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x302, &mut x303, x301, x265, x262); let mut x304: u32 = 0; let mut x305: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x304, &mut x305, x303, x263, x260); let x306: u32 = ((x305 as u32) + x261); let mut x307: u32 = 0; let mut x308: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x307, &mut x308, 0x0, x235, x282); let mut x309: u32 = 0; let mut x310: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x309, &mut x310, x308, x237, x284); let mut x311: u32 = 0; let mut x312: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x311, &mut x312, x310, x239, x286); let mut x313: u32 = 0; let mut x314: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x313, &mut x314, x312, x241, x288); let mut x315: u32 = 0; let mut x316: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x315, &mut x316, x314, x243, x290); let mut x317: u32 = 0; let mut x318: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x317, &mut x318, x316, x245, x292); let mut x319: u32 = 0; let mut x320: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x319, &mut x320, x318, x247, x294); let mut x321: u32 = 0; let mut x322: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x321, &mut x322, x320, x249, x296); let mut x323: u32 = 0; let mut x324: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x323, &mut x324, x322, x251, x298); let mut x325: u32 = 0; let mut x326: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x325, &mut x326, x324, x253, x300); let mut x327: u32 = 0; let mut x328: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x327, &mut x328, x326, x255, x302); let mut x329: u32 = 0; let mut x330: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x329, &mut x330, x328, x257, x304); let mut x331: u32 = 0; let mut x332: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x331, &mut x332, x330, x259, x306); let mut x333: u32 = 0; let mut x334: u32 = 0; fiat_p384_mulx_u32(&mut x333, &mut x334, x307, 0xffffffff); let mut x335: u32 = 0; let mut x336: u32 = 0; fiat_p384_mulx_u32(&mut x335, &mut x336, x307, 0xffffffff); let mut x337: u32 = 0; let mut x338: u32 = 0; fiat_p384_mulx_u32(&mut x337, &mut x338, x307, 0xffffffff); let mut x339: u32 = 0; let mut x340: u32 = 0; fiat_p384_mulx_u32(&mut x339, &mut x340, x307, 0xffffffff); let mut x341: u32 = 0; let mut x342: u32 = 0; fiat_p384_mulx_u32(&mut x341, &mut x342, x307, 0xffffffff); let mut x343: u32 = 0; let mut x344: u32 = 0; fiat_p384_mulx_u32(&mut x343, &mut x344, x307, 0xffffffff); let mut x345: u32 = 0; let mut x346: u32 = 0; fiat_p384_mulx_u32(&mut x345, &mut x346, x307, 0xffffffff); let mut x347: u32 = 0; let mut x348: u32 = 0; fiat_p384_mulx_u32(&mut x347, &mut x348, x307, 0xfffffffe); let mut x349: u32 = 0; let mut x350: u32 = 0; fiat_p384_mulx_u32(&mut x349, &mut x350, x307, 0xffffffff); let mut x351: u32 = 0; let mut x352: u32 = 0; fiat_p384_mulx_u32(&mut x351, &mut x352, x307, 0xffffffff); let mut x353: u32 = 0; let mut x354: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x353, &mut x354, 0x0, x350, x347); let mut x355: u32 = 0; let mut x356: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x355, &mut x356, x354, x348, x345); let mut x357: u32 = 0; let mut x358: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x357, &mut x358, x356, x346, x343); let mut x359: u32 = 0; let mut x360: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x359, &mut x360, x358, x344, x341); let mut x361: u32 = 0; let mut x362: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x361, &mut x362, x360, x342, x339); let mut x363: u32 = 0; let mut x364: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x363, &mut x364, x362, x340, x337); let mut x365: u32 = 0; let mut x366: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x365, &mut x366, x364, x338, x335); let mut x367: u32 = 0; let mut x368: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x367, &mut x368, x366, x336, x333); let x369: u32 = ((x368 as u32) + x334); let mut x370: u32 = 0; let mut x371: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x370, &mut x371, 0x0, x307, x351); let mut x372: u32 = 0; let mut x373: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x372, &mut x373, x371, x309, x352); let mut x374: u32 = 0; let mut x375: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x374, &mut x375, x373, x311, (0x0 as u32)); let mut x376: u32 = 0; let mut x377: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x376, &mut x377, x375, x313, x349); let mut x378: u32 = 0; let mut x379: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x378, &mut x379, x377, x315, x353); let mut x380: u32 = 0; let mut x381: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x380, &mut x381, x379, x317, x355); let mut x382: u32 = 0; let mut x383: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x382, &mut x383, x381, x319, x357); let mut x384: u32 = 0; let mut x385: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x384, &mut x385, x383, x321, x359); let mut x386: u32 = 0; let mut x387: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x386, &mut x387, x385, x323, x361); let mut x388: u32 = 0; let mut x389: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x388, &mut x389, x387, x325, x363); let mut x390: u32 = 0; let mut x391: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x390, &mut x391, x389, x327, x365); let mut x392: u32 = 0; let mut x393: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x392, &mut x393, x391, x329, x367); let mut x394: u32 = 0; let mut x395: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x394, &mut x395, x393, x331, x369); let x396: u32 = ((x395 as u32) + (x332 as u32)); let mut x397: u32 = 0; let mut x398: u32 = 0; fiat_p384_mulx_u32(&mut x397, &mut x398, x3, (arg1[11])); let mut x399: u32 = 0; let mut x400: u32 = 0; fiat_p384_mulx_u32(&mut x399, &mut x400, x3, (arg1[10])); let mut x401: u32 = 0; let mut x402: u32 = 0; fiat_p384_mulx_u32(&mut x401, &mut x402, x3, (arg1[9])); let mut x403: u32 = 0; let mut x404: u32 = 0; fiat_p384_mulx_u32(&mut x403, &mut x404, x3, (arg1[8])); let mut x405: u32 = 0; let mut x406: u32 = 0; fiat_p384_mulx_u32(&mut x405, &mut x406, x3, (arg1[7])); let mut x407: u32 = 0; let mut x408: u32 = 0; fiat_p384_mulx_u32(&mut x407, &mut x408, x3, (arg1[6])); let mut x409: u32 = 0; let mut x410: u32 = 0; fiat_p384_mulx_u32(&mut x409, &mut x410, x3, (arg1[5])); let mut x411: u32 = 0; let mut x412: u32 = 0; fiat_p384_mulx_u32(&mut x411, &mut x412, x3, (arg1[4])); let mut x413: u32 = 0; let mut x414: u32 = 0; fiat_p384_mulx_u32(&mut x413, &mut x414, x3, (arg1[3])); let mut x415: u32 = 0; let mut x416: u32 = 0; fiat_p384_mulx_u32(&mut x415, &mut x416, x3, (arg1[2])); let mut x417: u32 = 0; let mut x418: u32 = 0; fiat_p384_mulx_u32(&mut x417, &mut x418, x3, (arg1[1])); let mut x419: u32 = 0; let mut x420: u32 = 0; fiat_p384_mulx_u32(&mut x419, &mut x420, x3, (arg1[0])); let mut x421: u32 = 0; let mut x422: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x421, &mut x422, 0x0, x420, x417); let mut x423: u32 = 0; let mut x424: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x423, &mut x424, x422, x418, x415); let mut x425: u32 = 0; let mut x426: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x425, &mut x426, x424, x416, x413); let mut x427: u32 = 0; let mut x428: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x427, &mut x428, x426, x414, x411); let mut x429: u32 = 0; let mut x430: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x429, &mut x430, x428, x412, x409); let mut x431: u32 = 0; let mut x432: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x431, &mut x432, x430, x410, x407); let mut x433: u32 = 0; let mut x434: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x433, &mut x434, x432, x408, x405); let mut x435: u32 = 0; let mut x436: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x435, &mut x436, x434, x406, x403); let mut x437: u32 = 0; let mut x438: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x437, &mut x438, x436, x404, x401); let mut x439: u32 = 0; let mut x440: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x439, &mut x440, x438, x402, x399); let mut x441: u32 = 0; let mut x442: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x441, &mut x442, x440, x400, x397); let x443: u32 = ((x442 as u32) + x398); let mut x444: u32 = 0; let mut x445: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x444, &mut x445, 0x0, x372, x419); let mut x446: u32 = 0; let mut x447: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x446, &mut x447, x445, x374, x421); let mut x448: u32 = 0; let mut x449: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x448, &mut x449, x447, x376, x423); let mut x450: u32 = 0; let mut x451: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x450, &mut x451, x449, x378, x425); let mut x452: u32 = 0; let mut x453: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x452, &mut x453, x451, x380, x427); let mut x454: u32 = 0; let mut x455: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x454, &mut x455, x453, x382, x429); let mut x456: u32 = 0; let mut x457: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x456, &mut x457, x455, x384, x431); let mut x458: u32 = 0; let mut x459: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x458, &mut x459, x457, x386, x433); let mut x460: u32 = 0; let mut x461: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x460, &mut x461, x459, x388, x435); let mut x462: u32 = 0; let mut x463: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x462, &mut x463, x461, x390, x437); let mut x464: u32 = 0; let mut x465: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x464, &mut x465, x463, x392, x439); let mut x466: u32 = 0; let mut x467: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x466, &mut x467, x465, x394, x441); let mut x468: u32 = 0; let mut x469: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x468, &mut x469, x467, x396, x443); let mut x470: u32 = 0; let mut x471: u32 = 0; fiat_p384_mulx_u32(&mut x470, &mut x471, x444, 0xffffffff); let mut x472: u32 = 0; let mut x473: u32 = 0; fiat_p384_mulx_u32(&mut x472, &mut x473, x444, 0xffffffff); let mut x474: u32 = 0; let mut x475: u32 = 0; fiat_p384_mulx_u32(&mut x474, &mut x475, x444, 0xffffffff); let mut x476: u32 = 0; let mut x477: u32 = 0; fiat_p384_mulx_u32(&mut x476, &mut x477, x444, 0xffffffff); let mut x478: u32 = 0; let mut x479: u32 = 0; fiat_p384_mulx_u32(&mut x478, &mut x479, x444, 0xffffffff); let mut x480: u32 = 0; let mut x481: u32 = 0; fiat_p384_mulx_u32(&mut x480, &mut x481, x444, 0xffffffff); let mut x482: u32 = 0; let mut x483: u32 = 0; fiat_p384_mulx_u32(&mut x482, &mut x483, x444, 0xffffffff); let mut x484: u32 = 0; let mut x485: u32 = 0; fiat_p384_mulx_u32(&mut x484, &mut x485, x444, 0xfffffffe); let mut x486: u32 = 0; let mut x487: u32 = 0; fiat_p384_mulx_u32(&mut x486, &mut x487, x444, 0xffffffff); let mut x488: u32 = 0; let mut x489: u32 = 0; fiat_p384_mulx_u32(&mut x488, &mut x489, x444, 0xffffffff); let mut x490: u32 = 0; let mut x491: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x490, &mut x491, 0x0, x487, x484); let mut x492: u32 = 0; let mut x493: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x492, &mut x493, x491, x485, x482); let mut x494: u32 = 0; let mut x495: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x494, &mut x495, x493, x483, x480); let mut x496: u32 = 0; let mut x497: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x496, &mut x497, x495, x481, x478); let mut x498: u32 = 0; let mut x499: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x498, &mut x499, x497, x479, x476); let mut x500: u32 = 0; let mut x501: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x500, &mut x501, x499, x477, x474); let mut x502: u32 = 0; let mut x503: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x502, &mut x503, x501, x475, x472); let mut x504: u32 = 0; let mut x505: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x504, &mut x505, x503, x473, x470); let x506: u32 = ((x505 as u32) + x471); let mut x507: u32 = 0; let mut x508: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x507, &mut x508, 0x0, x444, x488); let mut x509: u32 = 0; let mut x510: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x509, &mut x510, x508, x446, x489); let mut x511: u32 = 0; let mut x512: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x511, &mut x512, x510, x448, (0x0 as u32)); let mut x513: u32 = 0; let mut x514: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x513, &mut x514, x512, x450, x486); let mut x515: u32 = 0; let mut x516: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x515, &mut x516, x514, x452, x490); let mut x517: u32 = 0; let mut x518: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x517, &mut x518, x516, x454, x492); let mut x519: u32 = 0; let mut x520: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x519, &mut x520, x518, x456, x494); let mut x521: u32 = 0; let mut x522: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x521, &mut x522, x520, x458, x496); let mut x523: u32 = 0; let mut x524: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x523, &mut x524, x522, x460, x498); let mut x525: u32 = 0; let mut x526: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x525, &mut x526, x524, x462, x500); let mut x527: u32 = 0; let mut x528: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x527, &mut x528, x526, x464, x502); let mut x529: u32 = 0; let mut x530: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x529, &mut x530, x528, x466, x504); let mut x531: u32 = 0; let mut x532: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x531, &mut x532, x530, x468, x506); let x533: u32 = ((x532 as u32) + (x469 as u32)); let mut x534: u32 = 0; let mut x535: u32 = 0; fiat_p384_mulx_u32(&mut x534, &mut x535, x4, (arg1[11])); let mut x536: u32 = 0; let mut x537: u32 = 0; fiat_p384_mulx_u32(&mut x536, &mut x537, x4, (arg1[10])); let mut x538: u32 = 0; let mut x539: u32 = 0; fiat_p384_mulx_u32(&mut x538, &mut x539, x4, (arg1[9])); let mut x540: u32 = 0; let mut x541: u32 = 0; fiat_p384_mulx_u32(&mut x540, &mut x541, x4, (arg1[8])); let mut x542: u32 = 0; let mut x543: u32 = 0; fiat_p384_mulx_u32(&mut x542, &mut x543, x4, (arg1[7])); let mut x544: u32 = 0; let mut x545: u32 = 0; fiat_p384_mulx_u32(&mut x544, &mut x545, x4, (arg1[6])); let mut x546: u32 = 0; let mut x547: u32 = 0; fiat_p384_mulx_u32(&mut x546, &mut x547, x4, (arg1[5])); let mut x548: u32 = 0; let mut x549: u32 = 0; fiat_p384_mulx_u32(&mut x548, &mut x549, x4, (arg1[4])); let mut x550: u32 = 0; let mut x551: u32 = 0; fiat_p384_mulx_u32(&mut x550, &mut x551, x4, (arg1[3])); let mut x552: u32 = 0; let mut x553: u32 = 0; fiat_p384_mulx_u32(&mut x552, &mut x553, x4, (arg1[2])); let mut x554: u32 = 0; let mut x555: u32 = 0; fiat_p384_mulx_u32(&mut x554, &mut x555, x4, (arg1[1])); let mut x556: u32 = 0; let mut x557: u32 = 0; fiat_p384_mulx_u32(&mut x556, &mut x557, x4, (arg1[0])); let mut x558: u32 = 0; let mut x559: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x558, &mut x559, 0x0, x557, x554); let mut x560: u32 = 0; let mut x561: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x560, &mut x561, x559, x555, x552); let mut x562: u32 = 0; let mut x563: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x562, &mut x563, x561, x553, x550); let mut x564: u32 = 0; let mut x565: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x564, &mut x565, x563, x551, x548); let mut x566: u32 = 0; let mut x567: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x566, &mut x567, x565, x549, x546); let mut x568: u32 = 0; let mut x569: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x568, &mut x569, x567, x547, x544); let mut x570: u32 = 0; let mut x571: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x570, &mut x571, x569, x545, x542); let mut x572: u32 = 0; let mut x573: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x572, &mut x573, x571, x543, x540); let mut x574: u32 = 0; let mut x575: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x574, &mut x575, x573, x541, x538); let mut x576: u32 = 0; let mut x577: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x576, &mut x577, x575, x539, x536); let mut x578: u32 = 0; let mut x579: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x578, &mut x579, x577, x537, x534); let x580: u32 = ((x579 as u32) + x535); let mut x581: u32 = 0; let mut x582: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x581, &mut x582, 0x0, x509, x556); let mut x583: u32 = 0; let mut x584: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x583, &mut x584, x582, x511, x558); let mut x585: u32 = 0; let mut x586: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x585, &mut x586, x584, x513, x560); let mut x587: u32 = 0; let mut x588: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x587, &mut x588, x586, x515, x562); let mut x589: u32 = 0; let mut x590: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x589, &mut x590, x588, x517, x564); let mut x591: u32 = 0; let mut x592: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x591, &mut x592, x590, x519, x566); let mut x593: u32 = 0; let mut x594: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x593, &mut x594, x592, x521, x568); let mut x595: u32 = 0; let mut x596: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x595, &mut x596, x594, x523, x570); let mut x597: u32 = 0; let mut x598: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x597, &mut x598, x596, x525, x572); let mut x599: u32 = 0; let mut x600: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x599, &mut x600, x598, x527, x574); let mut x601: u32 = 0; let mut x602: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x601, &mut x602, x600, x529, x576); let mut x603: u32 = 0; let mut x604: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x603, &mut x604, x602, x531, x578); let mut x605: u32 = 0; let mut x606: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x605, &mut x606, x604, x533, x580); let mut x607: u32 = 0; let mut x608: u32 = 0; fiat_p384_mulx_u32(&mut x607, &mut x608, x581, 0xffffffff); let mut x609: u32 = 0; let mut x610: u32 = 0; fiat_p384_mulx_u32(&mut x609, &mut x610, x581, 0xffffffff); let mut x611: u32 = 0; let mut x612: u32 = 0; fiat_p384_mulx_u32(&mut x611, &mut x612, x581, 0xffffffff); let mut x613: u32 = 0; let mut x614: u32 = 0; fiat_p384_mulx_u32(&mut x613, &mut x614, x581, 0xffffffff); let mut x615: u32 = 0; let mut x616: u32 = 0; fiat_p384_mulx_u32(&mut x615, &mut x616, x581, 0xffffffff); let mut x617: u32 = 0; let mut x618: u32 = 0; fiat_p384_mulx_u32(&mut x617, &mut x618, x581, 0xffffffff); let mut x619: u32 = 0; let mut x620: u32 = 0; fiat_p384_mulx_u32(&mut x619, &mut x620, x581, 0xffffffff); let mut x621: u32 = 0; let mut x622: u32 = 0; fiat_p384_mulx_u32(&mut x621, &mut x622, x581, 0xfffffffe); let mut x623: u32 = 0; let mut x624: u32 = 0; fiat_p384_mulx_u32(&mut x623, &mut x624, x581, 0xffffffff); let mut x625: u32 = 0; let mut x626: u32 = 0; fiat_p384_mulx_u32(&mut x625, &mut x626, x581, 0xffffffff); let mut x627: u32 = 0; let mut x628: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x627, &mut x628, 0x0, x624, x621); let mut x629: u32 = 0; let mut x630: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x629, &mut x630, x628, x622, x619); let mut x631: u32 = 0; let mut x632: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x631, &mut x632, x630, x620, x617); let mut x633: u32 = 0; let mut x634: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x633, &mut x634, x632, x618, x615); let mut x635: u32 = 0; let mut x636: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x635, &mut x636, x634, x616, x613); let mut x637: u32 = 0; let mut x638: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x637, &mut x638, x636, x614, x611); let mut x639: u32 = 0; let mut x640: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x639, &mut x640, x638, x612, x609); let mut x641: u32 = 0; let mut x642: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x641, &mut x642, x640, x610, x607); let x643: u32 = ((x642 as u32) + x608); let mut x644: u32 = 0; let mut x645: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x644, &mut x645, 0x0, x581, x625); let mut x646: u32 = 0; let mut x647: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x646, &mut x647, x645, x583, x626); let mut x648: u32 = 0; let mut x649: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x648, &mut x649, x647, x585, (0x0 as u32)); let mut x650: u32 = 0; let mut x651: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x650, &mut x651, x649, x587, x623); let mut x652: u32 = 0; let mut x653: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x652, &mut x653, x651, x589, x627); let mut x654: u32 = 0; let mut x655: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x654, &mut x655, x653, x591, x629); let mut x656: u32 = 0; let mut x657: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x656, &mut x657, x655, x593, x631); let mut x658: u32 = 0; let mut x659: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x658, &mut x659, x657, x595, x633); let mut x660: u32 = 0; let mut x661: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x660, &mut x661, x659, x597, x635); let mut x662: u32 = 0; let mut x663: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x662, &mut x663, x661, x599, x637); let mut x664: u32 = 0; let mut x665: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x664, &mut x665, x663, x601, x639); let mut x666: u32 = 0; let mut x667: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x666, &mut x667, x665, x603, x641); let mut x668: u32 = 0; let mut x669: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x668, &mut x669, x667, x605, x643); let x670: u32 = ((x669 as u32) + (x606 as u32)); let mut x671: u32 = 0; let mut x672: u32 = 0; fiat_p384_mulx_u32(&mut x671, &mut x672, x5, (arg1[11])); let mut x673: u32 = 0; let mut x674: u32 = 0; fiat_p384_mulx_u32(&mut x673, &mut x674, x5, (arg1[10])); let mut x675: u32 = 0; let mut x676: u32 = 0; fiat_p384_mulx_u32(&mut x675, &mut x676, x5, (arg1[9])); let mut x677: u32 = 0; let mut x678: u32 = 0; fiat_p384_mulx_u32(&mut x677, &mut x678, x5, (arg1[8])); let mut x679: u32 = 0; let mut x680: u32 = 0; fiat_p384_mulx_u32(&mut x679, &mut x680, x5, (arg1[7])); let mut x681: u32 = 0; let mut x682: u32 = 0; fiat_p384_mulx_u32(&mut x681, &mut x682, x5, (arg1[6])); let mut x683: u32 = 0; let mut x684: u32 = 0; fiat_p384_mulx_u32(&mut x683, &mut x684, x5, (arg1[5])); let mut x685: u32 = 0; let mut x686: u32 = 0; fiat_p384_mulx_u32(&mut x685, &mut x686, x5, (arg1[4])); let mut x687: u32 = 0; let mut x688: u32 = 0; fiat_p384_mulx_u32(&mut x687, &mut x688, x5, (arg1[3])); let mut x689: u32 = 0; let mut x690: u32 = 0; fiat_p384_mulx_u32(&mut x689, &mut x690, x5, (arg1[2])); let mut x691: u32 = 0; let mut x692: u32 = 0; fiat_p384_mulx_u32(&mut x691, &mut x692, x5, (arg1[1])); let mut x693: u32 = 0; let mut x694: u32 = 0; fiat_p384_mulx_u32(&mut x693, &mut x694, x5, (arg1[0])); let mut x695: u32 = 0; let mut x696: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x695, &mut x696, 0x0, x694, x691); let mut x697: u32 = 0; let mut x698: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x697, &mut x698, x696, x692, x689); let mut x699: u32 = 0; let mut x700: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x699, &mut x700, x698, x690, x687); let mut x701: u32 = 0; let mut x702: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x701, &mut x702, x700, x688, x685); let mut x703: u32 = 0; let mut x704: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x703, &mut x704, x702, x686, x683); let mut x705: u32 = 0; let mut x706: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x705, &mut x706, x704, x684, x681); let mut x707: u32 = 0; let mut x708: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x707, &mut x708, x706, x682, x679); let mut x709: u32 = 0; let mut x710: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x709, &mut x710, x708, x680, x677); let mut x711: u32 = 0; let mut x712: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x711, &mut x712, x710, x678, x675); let mut x713: u32 = 0; let mut x714: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x713, &mut x714, x712, x676, x673); let mut x715: u32 = 0; let mut x716: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x715, &mut x716, x714, x674, x671); let x717: u32 = ((x716 as u32) + x672); let mut x718: u32 = 0; let mut x719: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x718, &mut x719, 0x0, x646, x693); let mut x720: u32 = 0; let mut x721: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x720, &mut x721, x719, x648, x695); let mut x722: u32 = 0; let mut x723: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x722, &mut x723, x721, x650, x697); let mut x724: u32 = 0; let mut x725: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x724, &mut x725, x723, x652, x699); let mut x726: u32 = 0; let mut x727: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x726, &mut x727, x725, x654, x701); let mut x728: u32 = 0; let mut x729: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x728, &mut x729, x727, x656, x703); let mut x730: u32 = 0; let mut x731: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x730, &mut x731, x729, x658, x705); let mut x732: u32 = 0; let mut x733: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x732, &mut x733, x731, x660, x707); let mut x734: u32 = 0; let mut x735: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x734, &mut x735, x733, x662, x709); let mut x736: u32 = 0; let mut x737: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x736, &mut x737, x735, x664, x711); let mut x738: u32 = 0; let mut x739: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x738, &mut x739, x737, x666, x713); let mut x740: u32 = 0; let mut x741: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x740, &mut x741, x739, x668, x715); let mut x742: u32 = 0; let mut x743: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x742, &mut x743, x741, x670, x717); let mut x744: u32 = 0; let mut x745: u32 = 0; fiat_p384_mulx_u32(&mut x744, &mut x745, x718, 0xffffffff); let mut x746: u32 = 0; let mut x747: u32 = 0; fiat_p384_mulx_u32(&mut x746, &mut x747, x718, 0xffffffff); let mut x748: u32 = 0; let mut x749: u32 = 0; fiat_p384_mulx_u32(&mut x748, &mut x749, x718, 0xffffffff); let mut x750: u32 = 0; let mut x751: u32 = 0; fiat_p384_mulx_u32(&mut x750, &mut x751, x718, 0xffffffff); let mut x752: u32 = 0; let mut x753: u32 = 0; fiat_p384_mulx_u32(&mut x752, &mut x753, x718, 0xffffffff); let mut x754: u32 = 0; let mut x755: u32 = 0; fiat_p384_mulx_u32(&mut x754, &mut x755, x718, 0xffffffff); let mut x756: u32 = 0; let mut x757: u32 = 0; fiat_p384_mulx_u32(&mut x756, &mut x757, x718, 0xffffffff); let mut x758: u32 = 0; let mut x759: u32 = 0; fiat_p384_mulx_u32(&mut x758, &mut x759, x718, 0xfffffffe); let mut x760: u32 = 0; let mut x761: u32 = 0; fiat_p384_mulx_u32(&mut x760, &mut x761, x718, 0xffffffff); let mut x762: u32 = 0; let mut x763: u32 = 0; fiat_p384_mulx_u32(&mut x762, &mut x763, x718, 0xffffffff); let mut x764: u32 = 0; let mut x765: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x764, &mut x765, 0x0, x761, x758); let mut x766: u32 = 0; let mut x767: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x766, &mut x767, x765, x759, x756); let mut x768: u32 = 0; let mut x769: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x768, &mut x769, x767, x757, x754); let mut x770: u32 = 0; let mut x771: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x770, &mut x771, x769, x755, x752); let mut x772: u32 = 0; let mut x773: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x772, &mut x773, x771, x753, x750); let mut x774: u32 = 0; let mut x775: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x774, &mut x775, x773, x751, x748); let mut x776: u32 = 0; let mut x777: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x776, &mut x777, x775, x749, x746); let mut x778: u32 = 0; let mut x779: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x778, &mut x779, x777, x747, x744); let x780: u32 = ((x779 as u32) + x745); let mut x781: u32 = 0; let mut x782: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x781, &mut x782, 0x0, x718, x762); let mut x783: u32 = 0; let mut x784: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x783, &mut x784, x782, x720, x763); let mut x785: u32 = 0; let mut x786: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x785, &mut x786, x784, x722, (0x0 as u32)); let mut x787: u32 = 0; let mut x788: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x787, &mut x788, x786, x724, x760); let mut x789: u32 = 0; let mut x790: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x789, &mut x790, x788, x726, x764); let mut x791: u32 = 0; let mut x792: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x791, &mut x792, x790, x728, x766); let mut x793: u32 = 0; let mut x794: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x793, &mut x794, x792, x730, x768); let mut x795: u32 = 0; let mut x796: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x795, &mut x796, x794, x732, x770); let mut x797: u32 = 0; let mut x798: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x797, &mut x798, x796, x734, x772); let mut x799: u32 = 0; let mut x800: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x799, &mut x800, x798, x736, x774); let mut x801: u32 = 0; let mut x802: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x801, &mut x802, x800, x738, x776); let mut x803: u32 = 0; let mut x804: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x803, &mut x804, x802, x740, x778); let mut x805: u32 = 0; let mut x806: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x805, &mut x806, x804, x742, x780); let x807: u32 = ((x806 as u32) + (x743 as u32)); let mut x808: u32 = 0; let mut x809: u32 = 0; fiat_p384_mulx_u32(&mut x808, &mut x809, x6, (arg1[11])); let mut x810: u32 = 0; let mut x811: u32 = 0; fiat_p384_mulx_u32(&mut x810, &mut x811, x6, (arg1[10])); let mut x812: u32 = 0; let mut x813: u32 = 0; fiat_p384_mulx_u32(&mut x812, &mut x813, x6, (arg1[9])); let mut x814: u32 = 0; let mut x815: u32 = 0; fiat_p384_mulx_u32(&mut x814, &mut x815, x6, (arg1[8])); let mut x816: u32 = 0; let mut x817: u32 = 0; fiat_p384_mulx_u32(&mut x816, &mut x817, x6, (arg1[7])); let mut x818: u32 = 0; let mut x819: u32 = 0; fiat_p384_mulx_u32(&mut x818, &mut x819, x6, (arg1[6])); let mut x820: u32 = 0; let mut x821: u32 = 0; fiat_p384_mulx_u32(&mut x820, &mut x821, x6, (arg1[5])); let mut x822: u32 = 0; let mut x823: u32 = 0; fiat_p384_mulx_u32(&mut x822, &mut x823, x6, (arg1[4])); let mut x824: u32 = 0; let mut x825: u32 = 0; fiat_p384_mulx_u32(&mut x824, &mut x825, x6, (arg1[3])); let mut x826: u32 = 0; let mut x827: u32 = 0; fiat_p384_mulx_u32(&mut x826, &mut x827, x6, (arg1[2])); let mut x828: u32 = 0; let mut x829: u32 = 0; fiat_p384_mulx_u32(&mut x828, &mut x829, x6, (arg1[1])); let mut x830: u32 = 0; let mut x831: u32 = 0; fiat_p384_mulx_u32(&mut x830, &mut x831, x6, (arg1[0])); let mut x832: u32 = 0; let mut x833: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x832, &mut x833, 0x0, x831, x828); let mut x834: u32 = 0; let mut x835: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x834, &mut x835, x833, x829, x826); let mut x836: u32 = 0; let mut x837: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x836, &mut x837, x835, x827, x824); let mut x838: u32 = 0; let mut x839: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x838, &mut x839, x837, x825, x822); let mut x840: u32 = 0; let mut x841: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x840, &mut x841, x839, x823, x820); let mut x842: u32 = 0; let mut x843: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x842, &mut x843, x841, x821, x818); let mut x844: u32 = 0; let mut x845: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x844, &mut x845, x843, x819, x816); let mut x846: u32 = 0; let mut x847: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x846, &mut x847, x845, x817, x814); let mut x848: u32 = 0; let mut x849: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x848, &mut x849, x847, x815, x812); let mut x850: u32 = 0; let mut x851: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x850, &mut x851, x849, x813, x810); let mut x852: u32 = 0; let mut x853: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x852, &mut x853, x851, x811, x808); let x854: u32 = ((x853 as u32) + x809); let mut x855: u32 = 0; let mut x856: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x855, &mut x856, 0x0, x783, x830); let mut x857: u32 = 0; let mut x858: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x857, &mut x858, x856, x785, x832); let mut x859: u32 = 0; let mut x860: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x859, &mut x860, x858, x787, x834); let mut x861: u32 = 0; let mut x862: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x861, &mut x862, x860, x789, x836); let mut x863: u32 = 0; let mut x864: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x863, &mut x864, x862, x791, x838); let mut x865: u32 = 0; let mut x866: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x865, &mut x866, x864, x793, x840); let mut x867: u32 = 0; let mut x868: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x867, &mut x868, x866, x795, x842); let mut x869: u32 = 0; let mut x870: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x869, &mut x870, x868, x797, x844); let mut x871: u32 = 0; let mut x872: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x871, &mut x872, x870, x799, x846); let mut x873: u32 = 0; let mut x874: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x873, &mut x874, x872, x801, x848); let mut x875: u32 = 0; let mut x876: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x875, &mut x876, x874, x803, x850); let mut x877: u32 = 0; let mut x878: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x877, &mut x878, x876, x805, x852); let mut x879: u32 = 0; let mut x880: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x879, &mut x880, x878, x807, x854); let mut x881: u32 = 0; let mut x882: u32 = 0; fiat_p384_mulx_u32(&mut x881, &mut x882, x855, 0xffffffff); let mut x883: u32 = 0; let mut x884: u32 = 0; fiat_p384_mulx_u32(&mut x883, &mut x884, x855, 0xffffffff); let mut x885: u32 = 0; let mut x886: u32 = 0; fiat_p384_mulx_u32(&mut x885, &mut x886, x855, 0xffffffff); let mut x887: u32 = 0; let mut x888: u32 = 0; fiat_p384_mulx_u32(&mut x887, &mut x888, x855, 0xffffffff); let mut x889: u32 = 0; let mut x890: u32 = 0; fiat_p384_mulx_u32(&mut x889, &mut x890, x855, 0xffffffff); let mut x891: u32 = 0; let mut x892: u32 = 0; fiat_p384_mulx_u32(&mut x891, &mut x892, x855, 0xffffffff); let mut x893: u32 = 0; let mut x894: u32 = 0; fiat_p384_mulx_u32(&mut x893, &mut x894, x855, 0xffffffff); let mut x895: u32 = 0; let mut x896: u32 = 0; fiat_p384_mulx_u32(&mut x895, &mut x896, x855, 0xfffffffe); let mut x897: u32 = 0; let mut x898: u32 = 0; fiat_p384_mulx_u32(&mut x897, &mut x898, x855, 0xffffffff); let mut x899: u32 = 0; let mut x900: u32 = 0; fiat_p384_mulx_u32(&mut x899, &mut x900, x855, 0xffffffff); let mut x901: u32 = 0; let mut x902: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x901, &mut x902, 0x0, x898, x895); let mut x903: u32 = 0; let mut x904: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x903, &mut x904, x902, x896, x893); let mut x905: u32 = 0; let mut x906: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x905, &mut x906, x904, x894, x891); let mut x907: u32 = 0; let mut x908: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x907, &mut x908, x906, x892, x889); let mut x909: u32 = 0; let mut x910: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x909, &mut x910, x908, x890, x887); let mut x911: u32 = 0; let mut x912: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x911, &mut x912, x910, x888, x885); let mut x913: u32 = 0; let mut x914: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x913, &mut x914, x912, x886, x883); let mut x915: u32 = 0; let mut x916: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x915, &mut x916, x914, x884, x881); let x917: u32 = ((x916 as u32) + x882); let mut x918: u32 = 0; let mut x919: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x918, &mut x919, 0x0, x855, x899); let mut x920: u32 = 0; let mut x921: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x920, &mut x921, x919, x857, x900); let mut x922: u32 = 0; let mut x923: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x922, &mut x923, x921, x859, (0x0 as u32)); let mut x924: u32 = 0; let mut x925: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x924, &mut x925, x923, x861, x897); let mut x926: u32 = 0; let mut x927: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x926, &mut x927, x925, x863, x901); let mut x928: u32 = 0; let mut x929: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x928, &mut x929, x927, x865, x903); let mut x930: u32 = 0; let mut x931: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x930, &mut x931, x929, x867, x905); let mut x932: u32 = 0; let mut x933: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x932, &mut x933, x931, x869, x907); let mut x934: u32 = 0; let mut x935: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x934, &mut x935, x933, x871, x909); let mut x936: u32 = 0; let mut x937: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x936, &mut x937, x935, x873, x911); let mut x938: u32 = 0; let mut x939: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x938, &mut x939, x937, x875, x913); let mut x940: u32 = 0; let mut x941: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x940, &mut x941, x939, x877, x915); let mut x942: u32 = 0; let mut x943: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x942, &mut x943, x941, x879, x917); let x944: u32 = ((x943 as u32) + (x880 as u32)); let mut x945: u32 = 0; let mut x946: u32 = 0; fiat_p384_mulx_u32(&mut x945, &mut x946, x7, (arg1[11])); let mut x947: u32 = 0; let mut x948: u32 = 0; fiat_p384_mulx_u32(&mut x947, &mut x948, x7, (arg1[10])); let mut x949: u32 = 0; let mut x950: u32 = 0; fiat_p384_mulx_u32(&mut x949, &mut x950, x7, (arg1[9])); let mut x951: u32 = 0; let mut x952: u32 = 0; fiat_p384_mulx_u32(&mut x951, &mut x952, x7, (arg1[8])); let mut x953: u32 = 0; let mut x954: u32 = 0; fiat_p384_mulx_u32(&mut x953, &mut x954, x7, (arg1[7])); let mut x955: u32 = 0; let mut x956: u32 = 0; fiat_p384_mulx_u32(&mut x955, &mut x956, x7, (arg1[6])); let mut x957: u32 = 0; let mut x958: u32 = 0; fiat_p384_mulx_u32(&mut x957, &mut x958, x7, (arg1[5])); let mut x959: u32 = 0; let mut x960: u32 = 0; fiat_p384_mulx_u32(&mut x959, &mut x960, x7, (arg1[4])); let mut x961: u32 = 0; let mut x962: u32 = 0; fiat_p384_mulx_u32(&mut x961, &mut x962, x7, (arg1[3])); let mut x963: u32 = 0; let mut x964: u32 = 0; fiat_p384_mulx_u32(&mut x963, &mut x964, x7, (arg1[2])); let mut x965: u32 = 0; let mut x966: u32 = 0; fiat_p384_mulx_u32(&mut x965, &mut x966, x7, (arg1[1])); let mut x967: u32 = 0; let mut x968: u32 = 0; fiat_p384_mulx_u32(&mut x967, &mut x968, x7, (arg1[0])); let mut x969: u32 = 0; let mut x970: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x969, &mut x970, 0x0, x968, x965); let mut x971: u32 = 0; let mut x972: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x971, &mut x972, x970, x966, x963); let mut x973: u32 = 0; let mut x974: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x973, &mut x974, x972, x964, x961); let mut x975: u32 = 0; let mut x976: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x975, &mut x976, x974, x962, x959); let mut x977: u32 = 0; let mut x978: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x977, &mut x978, x976, x960, x957); let mut x979: u32 = 0; let mut x980: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x979, &mut x980, x978, x958, x955); let mut x981: u32 = 0; let mut x982: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x981, &mut x982, x980, x956, x953); let mut x983: u32 = 0; let mut x984: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x983, &mut x984, x982, x954, x951); let mut x985: u32 = 0; let mut x986: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x985, &mut x986, x984, x952, x949); let mut x987: u32 = 0; let mut x988: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x987, &mut x988, x986, x950, x947); let mut x989: u32 = 0; let mut x990: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x989, &mut x990, x988, x948, x945); let x991: u32 = ((x990 as u32) + x946); let mut x992: u32 = 0; let mut x993: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x992, &mut x993, 0x0, x920, x967); let mut x994: u32 = 0; let mut x995: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x994, &mut x995, x993, x922, x969); let mut x996: u32 = 0; let mut x997: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x996, &mut x997, x995, x924, x971); let mut x998: u32 = 0; let mut x999: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x998, &mut x999, x997, x926, x973); let mut x1000: u32 = 0; let mut x1001: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1000, &mut x1001, x999, x928, x975); let mut x1002: u32 = 0; let mut x1003: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1002, &mut x1003, x1001, x930, x977); let mut x1004: u32 = 0; let mut x1005: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1004, &mut x1005, x1003, x932, x979); let mut x1006: u32 = 0; let mut x1007: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1006, &mut x1007, x1005, x934, x981); let mut x1008: u32 = 0; let mut x1009: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1008, &mut x1009, x1007, x936, x983); let mut x1010: u32 = 0; let mut x1011: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1010, &mut x1011, x1009, x938, x985); let mut x1012: u32 = 0; let mut x1013: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1012, &mut x1013, x1011, x940, x987); let mut x1014: u32 = 0; let mut x1015: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1014, &mut x1015, x1013, x942, x989); let mut x1016: u32 = 0; let mut x1017: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1016, &mut x1017, x1015, x944, x991); let mut x1018: u32 = 0; let mut x1019: u32 = 0; fiat_p384_mulx_u32(&mut x1018, &mut x1019, x992, 0xffffffff); let mut x1020: u32 = 0; let mut x1021: u32 = 0; fiat_p384_mulx_u32(&mut x1020, &mut x1021, x992, 0xffffffff); let mut x1022: u32 = 0; let mut x1023: u32 = 0; fiat_p384_mulx_u32(&mut x1022, &mut x1023, x992, 0xffffffff); let mut x1024: u32 = 0; let mut x1025: u32 = 0; fiat_p384_mulx_u32(&mut x1024, &mut x1025, x992, 0xffffffff); let mut x1026: u32 = 0; let mut x1027: u32 = 0; fiat_p384_mulx_u32(&mut x1026, &mut x1027, x992, 0xffffffff); let mut x1028: u32 = 0; let mut x1029: u32 = 0; fiat_p384_mulx_u32(&mut x1028, &mut x1029, x992, 0xffffffff); let mut x1030: u32 = 0; let mut x1031: u32 = 0; fiat_p384_mulx_u32(&mut x1030, &mut x1031, x992, 0xffffffff); let mut x1032: u32 = 0; let mut x1033: u32 = 0; fiat_p384_mulx_u32(&mut x1032, &mut x1033, x992, 0xfffffffe); let mut x1034: u32 = 0; let mut x1035: u32 = 0; fiat_p384_mulx_u32(&mut x1034, &mut x1035, x992, 0xffffffff); let mut x1036: u32 = 0; let mut x1037: u32 = 0; fiat_p384_mulx_u32(&mut x1036, &mut x1037, x992, 0xffffffff); let mut x1038: u32 = 0; let mut x1039: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1038, &mut x1039, 0x0, x1035, x1032); let mut x1040: u32 = 0; let mut x1041: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1040, &mut x1041, x1039, x1033, x1030); let mut x1042: u32 = 0; let mut x1043: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1042, &mut x1043, x1041, x1031, x1028); let mut x1044: u32 = 0; let mut x1045: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1044, &mut x1045, x1043, x1029, x1026); let mut x1046: u32 = 0; let mut x1047: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1046, &mut x1047, x1045, x1027, x1024); let mut x1048: u32 = 0; let mut x1049: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1048, &mut x1049, x1047, x1025, x1022); let mut x1050: u32 = 0; let mut x1051: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1050, &mut x1051, x1049, x1023, x1020); let mut x1052: u32 = 0; let mut x1053: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1052, &mut x1053, x1051, x1021, x1018); let x1054: u32 = ((x1053 as u32) + x1019); let mut x1055: u32 = 0; let mut x1056: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1055, &mut x1056, 0x0, x992, x1036); let mut x1057: u32 = 0; let mut x1058: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1057, &mut x1058, x1056, x994, x1037); let mut x1059: u32 = 0; let mut x1060: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1059, &mut x1060, x1058, x996, (0x0 as u32)); let mut x1061: u32 = 0; let mut x1062: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1061, &mut x1062, x1060, x998, x1034); let mut x1063: u32 = 0; let mut x1064: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1063, &mut x1064, x1062, x1000, x1038); let mut x1065: u32 = 0; let mut x1066: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1065, &mut x1066, x1064, x1002, x1040); let mut x1067: u32 = 0; let mut x1068: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1067, &mut x1068, x1066, x1004, x1042); let mut x1069: u32 = 0; let mut x1070: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1069, &mut x1070, x1068, x1006, x1044); let mut x1071: u32 = 0; let mut x1072: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1071, &mut x1072, x1070, x1008, x1046); let mut x1073: u32 = 0; let mut x1074: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1073, &mut x1074, x1072, x1010, x1048); let mut x1075: u32 = 0; let mut x1076: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1075, &mut x1076, x1074, x1012, x1050); let mut x1077: u32 = 0; let mut x1078: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1077, &mut x1078, x1076, x1014, x1052); let mut x1079: u32 = 0; let mut x1080: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1079, &mut x1080, x1078, x1016, x1054); let x1081: u32 = ((x1080 as u32) + (x1017 as u32)); let mut x1082: u32 = 0; let mut x1083: u32 = 0; fiat_p384_mulx_u32(&mut x1082, &mut x1083, x8, (arg1[11])); let mut x1084: u32 = 0; let mut x1085: u32 = 0; fiat_p384_mulx_u32(&mut x1084, &mut x1085, x8, (arg1[10])); let mut x1086: u32 = 0; let mut x1087: u32 = 0; fiat_p384_mulx_u32(&mut x1086, &mut x1087, x8, (arg1[9])); let mut x1088: u32 = 0; let mut x1089: u32 = 0; fiat_p384_mulx_u32(&mut x1088, &mut x1089, x8, (arg1[8])); let mut x1090: u32 = 0; let mut x1091: u32 = 0; fiat_p384_mulx_u32(&mut x1090, &mut x1091, x8, (arg1[7])); let mut x1092: u32 = 0; let mut x1093: u32 = 0; fiat_p384_mulx_u32(&mut x1092, &mut x1093, x8, (arg1[6])); let mut x1094: u32 = 0; let mut x1095: u32 = 0; fiat_p384_mulx_u32(&mut x1094, &mut x1095, x8, (arg1[5])); let mut x1096: u32 = 0; let mut x1097: u32 = 0; fiat_p384_mulx_u32(&mut x1096, &mut x1097, x8, (arg1[4])); let mut x1098: u32 = 0; let mut x1099: u32 = 0; fiat_p384_mulx_u32(&mut x1098, &mut x1099, x8, (arg1[3])); let mut x1100: u32 = 0; let mut x1101: u32 = 0; fiat_p384_mulx_u32(&mut x1100, &mut x1101, x8, (arg1[2])); let mut x1102: u32 = 0; let mut x1103: u32 = 0; fiat_p384_mulx_u32(&mut x1102, &mut x1103, x8, (arg1[1])); let mut x1104: u32 = 0; let mut x1105: u32 = 0; fiat_p384_mulx_u32(&mut x1104, &mut x1105, x8, (arg1[0])); let mut x1106: u32 = 0; let mut x1107: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1106, &mut x1107, 0x0, x1105, x1102); let mut x1108: u32 = 0; let mut x1109: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1108, &mut x1109, x1107, x1103, x1100); let mut x1110: u32 = 0; let mut x1111: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1110, &mut x1111, x1109, x1101, x1098); let mut x1112: u32 = 0; let mut x1113: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1112, &mut x1113, x1111, x1099, x1096); let mut x1114: u32 = 0; let mut x1115: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1114, &mut x1115, x1113, x1097, x1094); let mut x1116: u32 = 0; let mut x1117: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1116, &mut x1117, x1115, x1095, x1092); let mut x1118: u32 = 0; let mut x1119: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1118, &mut x1119, x1117, x1093, x1090); let mut x1120: u32 = 0; let mut x1121: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1120, &mut x1121, x1119, x1091, x1088); let mut x1122: u32 = 0; let mut x1123: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1122, &mut x1123, x1121, x1089, x1086); let mut x1124: u32 = 0; let mut x1125: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1124, &mut x1125, x1123, x1087, x1084); let mut x1126: u32 = 0; let mut x1127: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1126, &mut x1127, x1125, x1085, x1082); let x1128: u32 = ((x1127 as u32) + x1083); let mut x1129: u32 = 0; let mut x1130: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1129, &mut x1130, 0x0, x1057, x1104); let mut x1131: u32 = 0; let mut x1132: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1131, &mut x1132, x1130, x1059, x1106); let mut x1133: u32 = 0; let mut x1134: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1133, &mut x1134, x1132, x1061, x1108); let mut x1135: u32 = 0; let mut x1136: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1135, &mut x1136, x1134, x1063, x1110); let mut x1137: u32 = 0; let mut x1138: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1137, &mut x1138, x1136, x1065, x1112); let mut x1139: u32 = 0; let mut x1140: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1139, &mut x1140, x1138, x1067, x1114); let mut x1141: u32 = 0; let mut x1142: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1141, &mut x1142, x1140, x1069, x1116); let mut x1143: u32 = 0; let mut x1144: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1143, &mut x1144, x1142, x1071, x1118); let mut x1145: u32 = 0; let mut x1146: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1145, &mut x1146, x1144, x1073, x1120); let mut x1147: u32 = 0; let mut x1148: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1147, &mut x1148, x1146, x1075, x1122); let mut x1149: u32 = 0; let mut x1150: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1149, &mut x1150, x1148, x1077, x1124); let mut x1151: u32 = 0; let mut x1152: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1151, &mut x1152, x1150, x1079, x1126); let mut x1153: u32 = 0; let mut x1154: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1153, &mut x1154, x1152, x1081, x1128); let mut x1155: u32 = 0; let mut x1156: u32 = 0; fiat_p384_mulx_u32(&mut x1155, &mut x1156, x1129, 0xffffffff); let mut x1157: u32 = 0; let mut x1158: u32 = 0; fiat_p384_mulx_u32(&mut x1157, &mut x1158, x1129, 0xffffffff); let mut x1159: u32 = 0; let mut x1160: u32 = 0; fiat_p384_mulx_u32(&mut x1159, &mut x1160, x1129, 0xffffffff); let mut x1161: u32 = 0; let mut x1162: u32 = 0; fiat_p384_mulx_u32(&mut x1161, &mut x1162, x1129, 0xffffffff); let mut x1163: u32 = 0; let mut x1164: u32 = 0; fiat_p384_mulx_u32(&mut x1163, &mut x1164, x1129, 0xffffffff); let mut x1165: u32 = 0; let mut x1166: u32 = 0; fiat_p384_mulx_u32(&mut x1165, &mut x1166, x1129, 0xffffffff); let mut x1167: u32 = 0; let mut x1168: u32 = 0; fiat_p384_mulx_u32(&mut x1167, &mut x1168, x1129, 0xffffffff); let mut x1169: u32 = 0; let mut x1170: u32 = 0; fiat_p384_mulx_u32(&mut x1169, &mut x1170, x1129, 0xfffffffe); let mut x1171: u32 = 0; let mut x1172: u32 = 0; fiat_p384_mulx_u32(&mut x1171, &mut x1172, x1129, 0xffffffff); let mut x1173: u32 = 0; let mut x1174: u32 = 0; fiat_p384_mulx_u32(&mut x1173, &mut x1174, x1129, 0xffffffff); let mut x1175: u32 = 0; let mut x1176: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1175, &mut x1176, 0x0, x1172, x1169); let mut x1177: u32 = 0; let mut x1178: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1177, &mut x1178, x1176, x1170, x1167); let mut x1179: u32 = 0; let mut x1180: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1179, &mut x1180, x1178, x1168, x1165); let mut x1181: u32 = 0; let mut x1182: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1181, &mut x1182, x1180, x1166, x1163); let mut x1183: u32 = 0; let mut x1184: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1183, &mut x1184, x1182, x1164, x1161); let mut x1185: u32 = 0; let mut x1186: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1185, &mut x1186, x1184, x1162, x1159); let mut x1187: u32 = 0; let mut x1188: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1187, &mut x1188, x1186, x1160, x1157); let mut x1189: u32 = 0; let mut x1190: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1189, &mut x1190, x1188, x1158, x1155); let x1191: u32 = ((x1190 as u32) + x1156); let mut x1192: u32 = 0; let mut x1193: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1192, &mut x1193, 0x0, x1129, x1173); let mut x1194: u32 = 0; let mut x1195: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1194, &mut x1195, x1193, x1131, x1174); let mut x1196: u32 = 0; let mut x1197: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1196, &mut x1197, x1195, x1133, (0x0 as u32)); let mut x1198: u32 = 0; let mut x1199: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1198, &mut x1199, x1197, x1135, x1171); let mut x1200: u32 = 0; let mut x1201: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1200, &mut x1201, x1199, x1137, x1175); let mut x1202: u32 = 0; let mut x1203: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1202, &mut x1203, x1201, x1139, x1177); let mut x1204: u32 = 0; let mut x1205: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1204, &mut x1205, x1203, x1141, x1179); let mut x1206: u32 = 0; let mut x1207: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1206, &mut x1207, x1205, x1143, x1181); let mut x1208: u32 = 0; let mut x1209: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1208, &mut x1209, x1207, x1145, x1183); let mut x1210: u32 = 0; let mut x1211: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1210, &mut x1211, x1209, x1147, x1185); let mut x1212: u32 = 0; let mut x1213: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1212, &mut x1213, x1211, x1149, x1187); let mut x1214: u32 = 0; let mut x1215: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1214, &mut x1215, x1213, x1151, x1189); let mut x1216: u32 = 0; let mut x1217: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1216, &mut x1217, x1215, x1153, x1191); let x1218: u32 = ((x1217 as u32) + (x1154 as u32)); let mut x1219: u32 = 0; let mut x1220: u32 = 0; fiat_p384_mulx_u32(&mut x1219, &mut x1220, x9, (arg1[11])); let mut x1221: u32 = 0; let mut x1222: u32 = 0; fiat_p384_mulx_u32(&mut x1221, &mut x1222, x9, (arg1[10])); let mut x1223: u32 = 0; let mut x1224: u32 = 0; fiat_p384_mulx_u32(&mut x1223, &mut x1224, x9, (arg1[9])); let mut x1225: u32 = 0; let mut x1226: u32 = 0; fiat_p384_mulx_u32(&mut x1225, &mut x1226, x9, (arg1[8])); let mut x1227: u32 = 0; let mut x1228: u32 = 0; fiat_p384_mulx_u32(&mut x1227, &mut x1228, x9, (arg1[7])); let mut x1229: u32 = 0; let mut x1230: u32 = 0; fiat_p384_mulx_u32(&mut x1229, &mut x1230, x9, (arg1[6])); let mut x1231: u32 = 0; let mut x1232: u32 = 0; fiat_p384_mulx_u32(&mut x1231, &mut x1232, x9, (arg1[5])); let mut x1233: u32 = 0; let mut x1234: u32 = 0; fiat_p384_mulx_u32(&mut x1233, &mut x1234, x9, (arg1[4])); let mut x1235: u32 = 0; let mut x1236: u32 = 0; fiat_p384_mulx_u32(&mut x1235, &mut x1236, x9, (arg1[3])); let mut x1237: u32 = 0; let mut x1238: u32 = 0; fiat_p384_mulx_u32(&mut x1237, &mut x1238, x9, (arg1[2])); let mut x1239: u32 = 0; let mut x1240: u32 = 0; fiat_p384_mulx_u32(&mut x1239, &mut x1240, x9, (arg1[1])); let mut x1241: u32 = 0; let mut x1242: u32 = 0; fiat_p384_mulx_u32(&mut x1241, &mut x1242, x9, (arg1[0])); let mut x1243: u32 = 0; let mut x1244: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1243, &mut x1244, 0x0, x1242, x1239); let mut x1245: u32 = 0; let mut x1246: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1245, &mut x1246, x1244, x1240, x1237); let mut x1247: u32 = 0; let mut x1248: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1247, &mut x1248, x1246, x1238, x1235); let mut x1249: u32 = 0; let mut x1250: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1249, &mut x1250, x1248, x1236, x1233); let mut x1251: u32 = 0; let mut x1252: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1251, &mut x1252, x1250, x1234, x1231); let mut x1253: u32 = 0; let mut x1254: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1253, &mut x1254, x1252, x1232, x1229); let mut x1255: u32 = 0; let mut x1256: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1255, &mut x1256, x1254, x1230, x1227); let mut x1257: u32 = 0; let mut x1258: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1257, &mut x1258, x1256, x1228, x1225); let mut x1259: u32 = 0; let mut x1260: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1259, &mut x1260, x1258, x1226, x1223); let mut x1261: u32 = 0; let mut x1262: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1261, &mut x1262, x1260, x1224, x1221); let mut x1263: u32 = 0; let mut x1264: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1263, &mut x1264, x1262, x1222, x1219); let x1265: u32 = ((x1264 as u32) + x1220); let mut x1266: u32 = 0; let mut x1267: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1266, &mut x1267, 0x0, x1194, x1241); let mut x1268: u32 = 0; let mut x1269: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1268, &mut x1269, x1267, x1196, x1243); let mut x1270: u32 = 0; let mut x1271: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1270, &mut x1271, x1269, x1198, x1245); let mut x1272: u32 = 0; let mut x1273: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1272, &mut x1273, x1271, x1200, x1247); let mut x1274: u32 = 0; let mut x1275: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1274, &mut x1275, x1273, x1202, x1249); let mut x1276: u32 = 0; let mut x1277: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1276, &mut x1277, x1275, x1204, x1251); let mut x1278: u32 = 0; let mut x1279: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1278, &mut x1279, x1277, x1206, x1253); let mut x1280: u32 = 0; let mut x1281: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1280, &mut x1281, x1279, x1208, x1255); let mut x1282: u32 = 0; let mut x1283: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1282, &mut x1283, x1281, x1210, x1257); let mut x1284: u32 = 0; let mut x1285: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1284, &mut x1285, x1283, x1212, x1259); let mut x1286: u32 = 0; let mut x1287: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1286, &mut x1287, x1285, x1214, x1261); let mut x1288: u32 = 0; let mut x1289: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1288, &mut x1289, x1287, x1216, x1263); let mut x1290: u32 = 0; let mut x1291: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1290, &mut x1291, x1289, x1218, x1265); let mut x1292: u32 = 0; let mut x1293: u32 = 0; fiat_p384_mulx_u32(&mut x1292, &mut x1293, x1266, 0xffffffff); let mut x1294: u32 = 0; let mut x1295: u32 = 0; fiat_p384_mulx_u32(&mut x1294, &mut x1295, x1266, 0xffffffff); let mut x1296: u32 = 0; let mut x1297: u32 = 0; fiat_p384_mulx_u32(&mut x1296, &mut x1297, x1266, 0xffffffff); let mut x1298: u32 = 0; let mut x1299: u32 = 0; fiat_p384_mulx_u32(&mut x1298, &mut x1299, x1266, 0xffffffff); let mut x1300: u32 = 0; let mut x1301: u32 = 0; fiat_p384_mulx_u32(&mut x1300, &mut x1301, x1266, 0xffffffff); let mut x1302: u32 = 0; let mut x1303: u32 = 0; fiat_p384_mulx_u32(&mut x1302, &mut x1303, x1266, 0xffffffff); let mut x1304: u32 = 0; let mut x1305: u32 = 0; fiat_p384_mulx_u32(&mut x1304, &mut x1305, x1266, 0xffffffff); let mut x1306: u32 = 0; let mut x1307: u32 = 0; fiat_p384_mulx_u32(&mut x1306, &mut x1307, x1266, 0xfffffffe); let mut x1308: u32 = 0; let mut x1309: u32 = 0; fiat_p384_mulx_u32(&mut x1308, &mut x1309, x1266, 0xffffffff); let mut x1310: u32 = 0; let mut x1311: u32 = 0; fiat_p384_mulx_u32(&mut x1310, &mut x1311, x1266, 0xffffffff); let mut x1312: u32 = 0; let mut x1313: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1312, &mut x1313, 0x0, x1309, x1306); let mut x1314: u32 = 0; let mut x1315: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1314, &mut x1315, x1313, x1307, x1304); let mut x1316: u32 = 0; let mut x1317: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1316, &mut x1317, x1315, x1305, x1302); let mut x1318: u32 = 0; let mut x1319: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1318, &mut x1319, x1317, x1303, x1300); let mut x1320: u32 = 0; let mut x1321: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1320, &mut x1321, x1319, x1301, x1298); let mut x1322: u32 = 0; let mut x1323: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1322, &mut x1323, x1321, x1299, x1296); let mut x1324: u32 = 0; let mut x1325: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1324, &mut x1325, x1323, x1297, x1294); let mut x1326: u32 = 0; let mut x1327: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1326, &mut x1327, x1325, x1295, x1292); let x1328: u32 = ((x1327 as u32) + x1293); let mut x1329: u32 = 0; let mut x1330: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1329, &mut x1330, 0x0, x1266, x1310); let mut x1331: u32 = 0; let mut x1332: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1331, &mut x1332, x1330, x1268, x1311); let mut x1333: u32 = 0; let mut x1334: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1333, &mut x1334, x1332, x1270, (0x0 as u32)); let mut x1335: u32 = 0; let mut x1336: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1335, &mut x1336, x1334, x1272, x1308); let mut x1337: u32 = 0; let mut x1338: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1337, &mut x1338, x1336, x1274, x1312); let mut x1339: u32 = 0; let mut x1340: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1339, &mut x1340, x1338, x1276, x1314); let mut x1341: u32 = 0; let mut x1342: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1341, &mut x1342, x1340, x1278, x1316); let mut x1343: u32 = 0; let mut x1344: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1343, &mut x1344, x1342, x1280, x1318); let mut x1345: u32 = 0; let mut x1346: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1345, &mut x1346, x1344, x1282, x1320); let mut x1347: u32 = 0; let mut x1348: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1347, &mut x1348, x1346, x1284, x1322); let mut x1349: u32 = 0; let mut x1350: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1349, &mut x1350, x1348, x1286, x1324); let mut x1351: u32 = 0; let mut x1352: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1351, &mut x1352, x1350, x1288, x1326); let mut x1353: u32 = 0; let mut x1354: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1353, &mut x1354, x1352, x1290, x1328); let x1355: u32 = ((x1354 as u32) + (x1291 as u32)); let mut x1356: u32 = 0; let mut x1357: u32 = 0; fiat_p384_mulx_u32(&mut x1356, &mut x1357, x10, (arg1[11])); let mut x1358: u32 = 0; let mut x1359: u32 = 0; fiat_p384_mulx_u32(&mut x1358, &mut x1359, x10, (arg1[10])); let mut x1360: u32 = 0; let mut x1361: u32 = 0; fiat_p384_mulx_u32(&mut x1360, &mut x1361, x10, (arg1[9])); let mut x1362: u32 = 0; let mut x1363: u32 = 0; fiat_p384_mulx_u32(&mut x1362, &mut x1363, x10, (arg1[8])); let mut x1364: u32 = 0; let mut x1365: u32 = 0; fiat_p384_mulx_u32(&mut x1364, &mut x1365, x10, (arg1[7])); let mut x1366: u32 = 0; let mut x1367: u32 = 0; fiat_p384_mulx_u32(&mut x1366, &mut x1367, x10, (arg1[6])); let mut x1368: u32 = 0; let mut x1369: u32 = 0; fiat_p384_mulx_u32(&mut x1368, &mut x1369, x10, (arg1[5])); let mut x1370: u32 = 0; let mut x1371: u32 = 0; fiat_p384_mulx_u32(&mut x1370, &mut x1371, x10, (arg1[4])); let mut x1372: u32 = 0; let mut x1373: u32 = 0; fiat_p384_mulx_u32(&mut x1372, &mut x1373, x10, (arg1[3])); let mut x1374: u32 = 0; let mut x1375: u32 = 0; fiat_p384_mulx_u32(&mut x1374, &mut x1375, x10, (arg1[2])); let mut x1376: u32 = 0; let mut x1377: u32 = 0; fiat_p384_mulx_u32(&mut x1376, &mut x1377, x10, (arg1[1])); let mut x1378: u32 = 0; let mut x1379: u32 = 0; fiat_p384_mulx_u32(&mut x1378, &mut x1379, x10, (arg1[0])); let mut x1380: u32 = 0; let mut x1381: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1380, &mut x1381, 0x0, x1379, x1376); let mut x1382: u32 = 0; let mut x1383: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1382, &mut x1383, x1381, x1377, x1374); let mut x1384: u32 = 0; let mut x1385: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1384, &mut x1385, x1383, x1375, x1372); let mut x1386: u32 = 0; let mut x1387: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1386, &mut x1387, x1385, x1373, x1370); let mut x1388: u32 = 0; let mut x1389: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1388, &mut x1389, x1387, x1371, x1368); let mut x1390: u32 = 0; let mut x1391: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1390, &mut x1391, x1389, x1369, x1366); let mut x1392: u32 = 0; let mut x1393: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1392, &mut x1393, x1391, x1367, x1364); let mut x1394: u32 = 0; let mut x1395: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1394, &mut x1395, x1393, x1365, x1362); let mut x1396: u32 = 0; let mut x1397: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1396, &mut x1397, x1395, x1363, x1360); let mut x1398: u32 = 0; let mut x1399: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1398, &mut x1399, x1397, x1361, x1358); let mut x1400: u32 = 0; let mut x1401: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1400, &mut x1401, x1399, x1359, x1356); let x1402: u32 = ((x1401 as u32) + x1357); let mut x1403: u32 = 0; let mut x1404: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1403, &mut x1404, 0x0, x1331, x1378); let mut x1405: u32 = 0; let mut x1406: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1405, &mut x1406, x1404, x1333, x1380); let mut x1407: u32 = 0; let mut x1408: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1407, &mut x1408, x1406, x1335, x1382); let mut x1409: u32 = 0; let mut x1410: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1409, &mut x1410, x1408, x1337, x1384); let mut x1411: u32 = 0; let mut x1412: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1411, &mut x1412, x1410, x1339, x1386); let mut x1413: u32 = 0; let mut x1414: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1413, &mut x1414, x1412, x1341, x1388); let mut x1415: u32 = 0; let mut x1416: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1415, &mut x1416, x1414, x1343, x1390); let mut x1417: u32 = 0; let mut x1418: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1417, &mut x1418, x1416, x1345, x1392); let mut x1419: u32 = 0; let mut x1420: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1419, &mut x1420, x1418, x1347, x1394); let mut x1421: u32 = 0; let mut x1422: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1421, &mut x1422, x1420, x1349, x1396); let mut x1423: u32 = 0; let mut x1424: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1423, &mut x1424, x1422, x1351, x1398); let mut x1425: u32 = 0; let mut x1426: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1425, &mut x1426, x1424, x1353, x1400); let mut x1427: u32 = 0; let mut x1428: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1427, &mut x1428, x1426, x1355, x1402); let mut x1429: u32 = 0; let mut x1430: u32 = 0; fiat_p384_mulx_u32(&mut x1429, &mut x1430, x1403, 0xffffffff); let mut x1431: u32 = 0; let mut x1432: u32 = 0; fiat_p384_mulx_u32(&mut x1431, &mut x1432, x1403, 0xffffffff); let mut x1433: u32 = 0; let mut x1434: u32 = 0; fiat_p384_mulx_u32(&mut x1433, &mut x1434, x1403, 0xffffffff); let mut x1435: u32 = 0; let mut x1436: u32 = 0; fiat_p384_mulx_u32(&mut x1435, &mut x1436, x1403, 0xffffffff); let mut x1437: u32 = 0; let mut x1438: u32 = 0; fiat_p384_mulx_u32(&mut x1437, &mut x1438, x1403, 0xffffffff); let mut x1439: u32 = 0; let mut x1440: u32 = 0; fiat_p384_mulx_u32(&mut x1439, &mut x1440, x1403, 0xffffffff); let mut x1441: u32 = 0; let mut x1442: u32 = 0; fiat_p384_mulx_u32(&mut x1441, &mut x1442, x1403, 0xffffffff); let mut x1443: u32 = 0; let mut x1444: u32 = 0; fiat_p384_mulx_u32(&mut x1443, &mut x1444, x1403, 0xfffffffe); let mut x1445: u32 = 0; let mut x1446: u32 = 0; fiat_p384_mulx_u32(&mut x1445, &mut x1446, x1403, 0xffffffff); let mut x1447: u32 = 0; let mut x1448: u32 = 0; fiat_p384_mulx_u32(&mut x1447, &mut x1448, x1403, 0xffffffff); let mut x1449: u32 = 0; let mut x1450: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1449, &mut x1450, 0x0, x1446, x1443); let mut x1451: u32 = 0; let mut x1452: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1451, &mut x1452, x1450, x1444, x1441); let mut x1453: u32 = 0; let mut x1454: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1453, &mut x1454, x1452, x1442, x1439); let mut x1455: u32 = 0; let mut x1456: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1455, &mut x1456, x1454, x1440, x1437); let mut x1457: u32 = 0; let mut x1458: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1457, &mut x1458, x1456, x1438, x1435); let mut x1459: u32 = 0; let mut x1460: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1459, &mut x1460, x1458, x1436, x1433); let mut x1461: u32 = 0; let mut x1462: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1461, &mut x1462, x1460, x1434, x1431); let mut x1463: u32 = 0; let mut x1464: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1463, &mut x1464, x1462, x1432, x1429); let x1465: u32 = ((x1464 as u32) + x1430); let mut x1466: u32 = 0; let mut x1467: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1466, &mut x1467, 0x0, x1403, x1447); let mut x1468: u32 = 0; let mut x1469: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1468, &mut x1469, x1467, x1405, x1448); let mut x1470: u32 = 0; let mut x1471: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1470, &mut x1471, x1469, x1407, (0x0 as u32)); let mut x1472: u32 = 0; let mut x1473: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1472, &mut x1473, x1471, x1409, x1445); let mut x1474: u32 = 0; let mut x1475: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1474, &mut x1475, x1473, x1411, x1449); let mut x1476: u32 = 0; let mut x1477: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1476, &mut x1477, x1475, x1413, x1451); let mut x1478: u32 = 0; let mut x1479: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1478, &mut x1479, x1477, x1415, x1453); let mut x1480: u32 = 0; let mut x1481: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1480, &mut x1481, x1479, x1417, x1455); let mut x1482: u32 = 0; let mut x1483: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1482, &mut x1483, x1481, x1419, x1457); let mut x1484: u32 = 0; let mut x1485: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1484, &mut x1485, x1483, x1421, x1459); let mut x1486: u32 = 0; let mut x1487: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1486, &mut x1487, x1485, x1423, x1461); let mut x1488: u32 = 0; let mut x1489: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1488, &mut x1489, x1487, x1425, x1463); let mut x1490: u32 = 0; let mut x1491: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1490, &mut x1491, x1489, x1427, x1465); let x1492: u32 = ((x1491 as u32) + (x1428 as u32)); let mut x1493: u32 = 0; let mut x1494: u32 = 0; fiat_p384_mulx_u32(&mut x1493, &mut x1494, x11, (arg1[11])); let mut x1495: u32 = 0; let mut x1496: u32 = 0; fiat_p384_mulx_u32(&mut x1495, &mut x1496, x11, (arg1[10])); let mut x1497: u32 = 0; let mut x1498: u32 = 0; fiat_p384_mulx_u32(&mut x1497, &mut x1498, x11, (arg1[9])); let mut x1499: u32 = 0; let mut x1500: u32 = 0; fiat_p384_mulx_u32(&mut x1499, &mut x1500, x11, (arg1[8])); let mut x1501: u32 = 0; let mut x1502: u32 = 0; fiat_p384_mulx_u32(&mut x1501, &mut x1502, x11, (arg1[7])); let mut x1503: u32 = 0; let mut x1504: u32 = 0; fiat_p384_mulx_u32(&mut x1503, &mut x1504, x11, (arg1[6])); let mut x1505: u32 = 0; let mut x1506: u32 = 0; fiat_p384_mulx_u32(&mut x1505, &mut x1506, x11, (arg1[5])); let mut x1507: u32 = 0; let mut x1508: u32 = 0; fiat_p384_mulx_u32(&mut x1507, &mut x1508, x11, (arg1[4])); let mut x1509: u32 = 0; let mut x1510: u32 = 0; fiat_p384_mulx_u32(&mut x1509, &mut x1510, x11, (arg1[3])); let mut x1511: u32 = 0; let mut x1512: u32 = 0; fiat_p384_mulx_u32(&mut x1511, &mut x1512, x11, (arg1[2])); let mut x1513: u32 = 0; let mut x1514: u32 = 0; fiat_p384_mulx_u32(&mut x1513, &mut x1514, x11, (arg1[1])); let mut x1515: u32 = 0; let mut x1516: u32 = 0; fiat_p384_mulx_u32(&mut x1515, &mut x1516, x11, (arg1[0])); let mut x1517: u32 = 0; let mut x1518: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1517, &mut x1518, 0x0, x1516, x1513); let mut x1519: u32 = 0; let mut x1520: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1519, &mut x1520, x1518, x1514, x1511); let mut x1521: u32 = 0; let mut x1522: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1521, &mut x1522, x1520, x1512, x1509); let mut x1523: u32 = 0; let mut x1524: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1523, &mut x1524, x1522, x1510, x1507); let mut x1525: u32 = 0; let mut x1526: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1525, &mut x1526, x1524, x1508, x1505); let mut x1527: u32 = 0; let mut x1528: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1527, &mut x1528, x1526, x1506, x1503); let mut x1529: u32 = 0; let mut x1530: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1529, &mut x1530, x1528, x1504, x1501); let mut x1531: u32 = 0; let mut x1532: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1531, &mut x1532, x1530, x1502, x1499); let mut x1533: u32 = 0; let mut x1534: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1533, &mut x1534, x1532, x1500, x1497); let mut x1535: u32 = 0; let mut x1536: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1535, &mut x1536, x1534, x1498, x1495); let mut x1537: u32 = 0; let mut x1538: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1537, &mut x1538, x1536, x1496, x1493); let x1539: u32 = ((x1538 as u32) + x1494); let mut x1540: u32 = 0; let mut x1541: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1540, &mut x1541, 0x0, x1468, x1515); let mut x1542: u32 = 0; let mut x1543: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1542, &mut x1543, x1541, x1470, x1517); let mut x1544: u32 = 0; let mut x1545: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1544, &mut x1545, x1543, x1472, x1519); let mut x1546: u32 = 0; let mut x1547: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1546, &mut x1547, x1545, x1474, x1521); let mut x1548: u32 = 0; let mut x1549: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1548, &mut x1549, x1547, x1476, x1523); let mut x1550: u32 = 0; let mut x1551: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1550, &mut x1551, x1549, x1478, x1525); let mut x1552: u32 = 0; let mut x1553: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1552, &mut x1553, x1551, x1480, x1527); let mut x1554: u32 = 0; let mut x1555: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1554, &mut x1555, x1553, x1482, x1529); let mut x1556: u32 = 0; let mut x1557: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1556, &mut x1557, x1555, x1484, x1531); let mut x1558: u32 = 0; let mut x1559: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1558, &mut x1559, x1557, x1486, x1533); let mut x1560: u32 = 0; let mut x1561: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1560, &mut x1561, x1559, x1488, x1535); let mut x1562: u32 = 0; let mut x1563: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1562, &mut x1563, x1561, x1490, x1537); let mut x1564: u32 = 0; let mut x1565: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1564, &mut x1565, x1563, x1492, x1539); let mut x1566: u32 = 0; let mut x1567: u32 = 0; fiat_p384_mulx_u32(&mut x1566, &mut x1567, x1540, 0xffffffff); let mut x1568: u32 = 0; let mut x1569: u32 = 0; fiat_p384_mulx_u32(&mut x1568, &mut x1569, x1540, 0xffffffff); let mut x1570: u32 = 0; let mut x1571: u32 = 0; fiat_p384_mulx_u32(&mut x1570, &mut x1571, x1540, 0xffffffff); let mut x1572: u32 = 0; let mut x1573: u32 = 0; fiat_p384_mulx_u32(&mut x1572, &mut x1573, x1540, 0xffffffff); let mut x1574: u32 = 0; let mut x1575: u32 = 0; fiat_p384_mulx_u32(&mut x1574, &mut x1575, x1540, 0xffffffff); let mut x1576: u32 = 0; let mut x1577: u32 = 0; fiat_p384_mulx_u32(&mut x1576, &mut x1577, x1540, 0xffffffff); let mut x1578: u32 = 0; let mut x1579: u32 = 0; fiat_p384_mulx_u32(&mut x1578, &mut x1579, x1540, 0xffffffff); let mut x1580: u32 = 0; let mut x1581: u32 = 0; fiat_p384_mulx_u32(&mut x1580, &mut x1581, x1540, 0xfffffffe); let mut x1582: u32 = 0; let mut x1583: u32 = 0; fiat_p384_mulx_u32(&mut x1582, &mut x1583, x1540, 0xffffffff); let mut x1584: u32 = 0; let mut x1585: u32 = 0; fiat_p384_mulx_u32(&mut x1584, &mut x1585, x1540, 0xffffffff); let mut x1586: u32 = 0; let mut x1587: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1586, &mut x1587, 0x0, x1583, x1580); let mut x1588: u32 = 0; let mut x1589: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1588, &mut x1589, x1587, x1581, x1578); let mut x1590: u32 = 0; let mut x1591: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1590, &mut x1591, x1589, x1579, x1576); let mut x1592: u32 = 0; let mut x1593: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1592, &mut x1593, x1591, x1577, x1574); let mut x1594: u32 = 0; let mut x1595: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1594, &mut x1595, x1593, x1575, x1572); let mut x1596: u32 = 0; let mut x1597: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1596, &mut x1597, x1595, x1573, x1570); let mut x1598: u32 = 0; let mut x1599: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1598, &mut x1599, x1597, x1571, x1568); let mut x1600: u32 = 0; let mut x1601: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1600, &mut x1601, x1599, x1569, x1566); let x1602: u32 = ((x1601 as u32) + x1567); let mut x1603: u32 = 0; let mut x1604: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1603, &mut x1604, 0x0, x1540, x1584); let mut x1605: u32 = 0; let mut x1606: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1605, &mut x1606, x1604, x1542, x1585); let mut x1607: u32 = 0; let mut x1608: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1607, &mut x1608, x1606, x1544, (0x0 as u32)); let mut x1609: u32 = 0; let mut x1610: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1609, &mut x1610, x1608, x1546, x1582); let mut x1611: u32 = 0; let mut x1612: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1611, &mut x1612, x1610, x1548, x1586); let mut x1613: u32 = 0; let mut x1614: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1613, &mut x1614, x1612, x1550, x1588); let mut x1615: u32 = 0; let mut x1616: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1615, &mut x1616, x1614, x1552, x1590); let mut x1617: u32 = 0; let mut x1618: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1617, &mut x1618, x1616, x1554, x1592); let mut x1619: u32 = 0; let mut x1620: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1619, &mut x1620, x1618, x1556, x1594); let mut x1621: u32 = 0; let mut x1622: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1621, &mut x1622, x1620, x1558, x1596); let mut x1623: u32 = 0; let mut x1624: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1623, &mut x1624, x1622, x1560, x1598); let mut x1625: u32 = 0; let mut x1626: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1625, &mut x1626, x1624, x1562, x1600); let mut x1627: u32 = 0; let mut x1628: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1627, &mut x1628, x1626, x1564, x1602); let x1629: u32 = ((x1628 as u32) + (x1565 as u32)); let mut x1630: u32 = 0; let mut x1631: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1630, &mut x1631, 0x0, x1605, 0xffffffff); let mut x1632: u32 = 0; let mut x1633: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1632, &mut x1633, x1631, x1607, (0x0 as u32)); let mut x1634: u32 = 0; let mut x1635: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1634, &mut x1635, x1633, x1609, (0x0 as u32)); let mut x1636: u32 = 0; let mut x1637: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1636, &mut x1637, x1635, x1611, 0xffffffff); let mut x1638: u32 = 0; let mut x1639: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1638, &mut x1639, x1637, x1613, 0xfffffffe); let mut x1640: u32 = 0; let mut x1641: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1640, &mut x1641, x1639, x1615, 0xffffffff); let mut x1642: u32 = 0; let mut x1643: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1642, &mut x1643, x1641, x1617, 0xffffffff); let mut x1644: u32 = 0; let mut x1645: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1644, &mut x1645, x1643, x1619, 0xffffffff); let mut x1646: u32 = 0; let mut x1647: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1646, &mut x1647, x1645, x1621, 0xffffffff); let mut x1648: u32 = 0; let mut x1649: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1648, &mut x1649, x1647, x1623, 0xffffffff); let mut x1650: u32 = 0; let mut x1651: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1650, &mut x1651, x1649, x1625, 0xffffffff); let mut x1652: u32 = 0; let mut x1653: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1652, &mut x1653, x1651, x1627, 0xffffffff); let mut x1654: u32 = 0; let mut x1655: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1654, &mut x1655, x1653, x1629, (0x0 as u32)); let mut x1656: u32 = 0; fiat_p384_cmovznz_u32(&mut x1656, x1655, x1630, x1605); let mut x1657: u32 = 0; fiat_p384_cmovznz_u32(&mut x1657, x1655, x1632, x1607); let mut x1658: u32 = 0; fiat_p384_cmovznz_u32(&mut x1658, x1655, x1634, x1609); let mut x1659: u32 = 0; fiat_p384_cmovznz_u32(&mut x1659, x1655, x1636, x1611); let mut x1660: u32 = 0; fiat_p384_cmovznz_u32(&mut x1660, x1655, x1638, x1613); let mut x1661: u32 = 0; fiat_p384_cmovznz_u32(&mut x1661, x1655, x1640, x1615); let mut x1662: u32 = 0; fiat_p384_cmovznz_u32(&mut x1662, x1655, x1642, x1617); let mut x1663: u32 = 0; fiat_p384_cmovznz_u32(&mut x1663, x1655, x1644, x1619); let mut x1664: u32 = 0; fiat_p384_cmovznz_u32(&mut x1664, x1655, x1646, x1621); let mut x1665: u32 = 0; fiat_p384_cmovznz_u32(&mut x1665, x1655, x1648, x1623); let mut x1666: u32 = 0; fiat_p384_cmovznz_u32(&mut x1666, x1655, x1650, x1625); let mut x1667: u32 = 0; fiat_p384_cmovznz_u32(&mut x1667, x1655, x1652, x1627); out1[0] = x1656; out1[1] = x1657; out1[2] = x1658; out1[3] = x1659; out1[4] = x1660; out1[5] = x1661; out1[6] = x1662; out1[7] = x1663; out1[8] = x1664; out1[9] = x1665; out1[10] = x1666; out1[11] = x1667; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_add(out1: &mut [u32; 12], arg1: &[u32; 12], arg2: &[u32; 12]) -> () { let mut x1: u32 = 0; let mut x2: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u32 = 0; let mut x4: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u32 = 0; let mut x6: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u32 = 0; let mut x8: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u32 = 0; let mut x10: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u32 = 0; let mut x12: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u32 = 0; let mut x14: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u32 = 0; let mut x16: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x15, &mut x16, x14, (arg1[7]), (arg2[7])); let mut x17: u32 = 0; let mut x18: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x17, &mut x18, x16, (arg1[8]), (arg2[8])); let mut x19: u32 = 0; let mut x20: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x19, &mut x20, x18, (arg1[9]), (arg2[9])); let mut x21: u32 = 0; let mut x22: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x21, &mut x22, x20, (arg1[10]), (arg2[10])); let mut x23: u32 = 0; let mut x24: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x23, &mut x24, x22, (arg1[11]), (arg2[11])); let mut x25: u32 = 0; let mut x26: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x25, &mut x26, 0x0, x1, 0xffffffff); let mut x27: u32 = 0; let mut x28: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x27, &mut x28, x26, x3, (0x0 as u32)); let mut x29: u32 = 0; let mut x30: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x29, &mut x30, x28, x5, (0x0 as u32)); let mut x31: u32 = 0; let mut x32: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x31, &mut x32, x30, x7, 0xffffffff); let mut x33: u32 = 0; let mut x34: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x33, &mut x34, x32, x9, 0xfffffffe); let mut x35: u32 = 0; let mut x36: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x35, &mut x36, x34, x11, 0xffffffff); let mut x37: u32 = 0; let mut x38: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x37, &mut x38, x36, x13, 0xffffffff); let mut x39: u32 = 0; let mut x40: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x39, &mut x40, x38, x15, 0xffffffff); let mut x41: u32 = 0; let mut x42: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x41, &mut x42, x40, x17, 0xffffffff); let mut x43: u32 = 0; let mut x44: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x43, &mut x44, x42, x19, 0xffffffff); let mut x45: u32 = 0; let mut x46: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x45, &mut x46, x44, x21, 0xffffffff); let mut x47: u32 = 0; let mut x48: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x47, &mut x48, x46, x23, 0xffffffff); let mut x49: u32 = 0; let mut x50: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x49, &mut x50, x48, (x24 as u32), (0x0 as u32)); let mut x51: u32 = 0; fiat_p384_cmovznz_u32(&mut x51, x50, x25, x1); let mut x52: u32 = 0; fiat_p384_cmovznz_u32(&mut x52, x50, x27, x3); let mut x53: u32 = 0; fiat_p384_cmovznz_u32(&mut x53, x50, x29, x5); let mut x54: u32 = 0; fiat_p384_cmovznz_u32(&mut x54, x50, x31, x7); let mut x55: u32 = 0; fiat_p384_cmovznz_u32(&mut x55, x50, x33, x9); let mut x56: u32 = 0; fiat_p384_cmovznz_u32(&mut x56, x50, x35, x11); let mut x57: u32 = 0; fiat_p384_cmovznz_u32(&mut x57, x50, x37, x13); let mut x58: u32 = 0; fiat_p384_cmovznz_u32(&mut x58, x50, x39, x15); let mut x59: u32 = 0; fiat_p384_cmovznz_u32(&mut x59, x50, x41, x17); let mut x60: u32 = 0; fiat_p384_cmovznz_u32(&mut x60, x50, x43, x19); let mut x61: u32 = 0; fiat_p384_cmovznz_u32(&mut x61, x50, x45, x21); let mut x62: u32 = 0; fiat_p384_cmovznz_u32(&mut x62, x50, x47, x23); out1[0] = x51; out1[1] = x52; out1[2] = x53; out1[3] = x54; out1[4] = x55; out1[5] = x56; out1[6] = x57; out1[7] = x58; out1[8] = x59; out1[9] = x60; out1[10] = x61; out1[11] = x62; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_sub(out1: &mut [u32; 12], arg1: &[u32; 12], arg2: &[u32; 12]) -> () { let mut x1: u32 = 0; let mut x2: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1, &mut x2, 0x0, (arg1[0]), (arg2[0])); let mut x3: u32 = 0; let mut x4: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x3, &mut x4, x2, (arg1[1]), (arg2[1])); let mut x5: u32 = 0; let mut x6: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x5, &mut x6, x4, (arg1[2]), (arg2[2])); let mut x7: u32 = 0; let mut x8: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x7, &mut x8, x6, (arg1[3]), (arg2[3])); let mut x9: u32 = 0; let mut x10: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x9, &mut x10, x8, (arg1[4]), (arg2[4])); let mut x11: u32 = 0; let mut x12: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x11, &mut x12, x10, (arg1[5]), (arg2[5])); let mut x13: u32 = 0; let mut x14: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x13, &mut x14, x12, (arg1[6]), (arg2[6])); let mut x15: u32 = 0; let mut x16: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x15, &mut x16, x14, (arg1[7]), (arg2[7])); let mut x17: u32 = 0; let mut x18: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x17, &mut x18, x16, (arg1[8]), (arg2[8])); let mut x19: u32 = 0; let mut x20: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x19, &mut x20, x18, (arg1[9]), (arg2[9])); let mut x21: u32 = 0; let mut x22: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x21, &mut x22, x20, (arg1[10]), (arg2[10])); let mut x23: u32 = 0; let mut x24: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x23, &mut x24, x22, (arg1[11]), (arg2[11])); let mut x25: u32 = 0; fiat_p384_cmovznz_u32(&mut x25, x24, (0x0 as u32), 0xffffffff); let mut x26: u32 = 0; let mut x27: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x26, &mut x27, 0x0, x1, x25); let mut x28: u32 = 0; let mut x29: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x28, &mut x29, x27, x3, (0x0 as u32)); let mut x30: u32 = 0; let mut x31: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x30, &mut x31, x29, x5, (0x0 as u32)); let mut x32: u32 = 0; let mut x33: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x32, &mut x33, x31, x7, x25); let mut x34: u32 = 0; let mut x35: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x34, &mut x35, x33, x9, (x25 & 0xfffffffe)); let mut x36: u32 = 0; let mut x37: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x36, &mut x37, x35, x11, x25); let mut x38: u32 = 0; let mut x39: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x38, &mut x39, x37, x13, x25); let mut x40: u32 = 0; let mut x41: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x40, &mut x41, x39, x15, x25); let mut x42: u32 = 0; let mut x43: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x42, &mut x43, x41, x17, x25); let mut x44: u32 = 0; let mut x45: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x44, &mut x45, x43, x19, x25); let mut x46: u32 = 0; let mut x47: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x46, &mut x47, x45, x21, x25); let mut x48: u32 = 0; let mut x49: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x48, &mut x49, x47, x23, x25); out1[0] = x26; out1[1] = x28; out1[2] = x30; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x38; out1[7] = x40; out1[8] = x42; out1[9] = x44; out1[10] = x46; out1[11] = x48; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_opp(out1: &mut [u32; 12], arg1: &[u32; 12]) -> () { let mut x1: u32 = 0; let mut x2: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1, &mut x2, 0x0, (0x0 as u32), (arg1[0])); let mut x3: u32 = 0; let mut x4: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x3, &mut x4, x2, (0x0 as u32), (arg1[1])); let mut x5: u32 = 0; let mut x6: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x5, &mut x6, x4, (0x0 as u32), (arg1[2])); let mut x7: u32 = 0; let mut x8: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x7, &mut x8, x6, (0x0 as u32), (arg1[3])); let mut x9: u32 = 0; let mut x10: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x9, &mut x10, x8, (0x0 as u32), (arg1[4])); let mut x11: u32 = 0; let mut x12: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x11, &mut x12, x10, (0x0 as u32), (arg1[5])); let mut x13: u32 = 0; let mut x14: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x13, &mut x14, x12, (0x0 as u32), (arg1[6])); let mut x15: u32 = 0; let mut x16: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x15, &mut x16, x14, (0x0 as u32), (arg1[7])); let mut x17: u32 = 0; let mut x18: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x17, &mut x18, x16, (0x0 as u32), (arg1[8])); let mut x19: u32 = 0; let mut x20: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x19, &mut x20, x18, (0x0 as u32), (arg1[9])); let mut x21: u32 = 0; let mut x22: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x21, &mut x22, x20, (0x0 as u32), (arg1[10])); let mut x23: u32 = 0; let mut x24: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x23, &mut x24, x22, (0x0 as u32), (arg1[11])); let mut x25: u32 = 0; fiat_p384_cmovznz_u32(&mut x25, x24, (0x0 as u32), 0xffffffff); let mut x26: u32 = 0; let mut x27: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x26, &mut x27, 0x0, x1, x25); let mut x28: u32 = 0; let mut x29: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x28, &mut x29, x27, x3, (0x0 as u32)); let mut x30: u32 = 0; let mut x31: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x30, &mut x31, x29, x5, (0x0 as u32)); let mut x32: u32 = 0; let mut x33: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x32, &mut x33, x31, x7, x25); let mut x34: u32 = 0; let mut x35: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x34, &mut x35, x33, x9, (x25 & 0xfffffffe)); let mut x36: u32 = 0; let mut x37: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x36, &mut x37, x35, x11, x25); let mut x38: u32 = 0; let mut x39: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x38, &mut x39, x37, x13, x25); let mut x40: u32 = 0; let mut x41: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x40, &mut x41, x39, x15, x25); let mut x42: u32 = 0; let mut x43: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x42, &mut x43, x41, x17, x25); let mut x44: u32 = 0; let mut x45: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x44, &mut x45, x43, x19, x25); let mut x46: u32 = 0; let mut x47: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x46, &mut x47, x45, x21, x25); let mut x48: u32 = 0; let mut x49: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x48, &mut x49, x47, x23, x25); out1[0] = x26; out1[1] = x28; out1[2] = x30; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x38; out1[7] = x40; out1[8] = x42; out1[9] = x44; out1[10] = x46; out1[11] = x48; } /// The function fiat_p384_from_montgomery translates a field element out of the Montgomery domain. /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^32)⁻¹ mod m)^12) mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_from_montgomery(out1: &mut [u32; 12], arg1: &[u32; 12]) -> () { let x1: u32 = (arg1[0]); let mut x2: u32 = 0; let mut x3: u32 = 0; fiat_p384_mulx_u32(&mut x2, &mut x3, x1, 0xffffffff); let mut x4: u32 = 0; let mut x5: u32 = 0; fiat_p384_mulx_u32(&mut x4, &mut x5, x1, 0xffffffff); let mut x6: u32 = 0; let mut x7: u32 = 0; fiat_p384_mulx_u32(&mut x6, &mut x7, x1, 0xffffffff); let mut x8: u32 = 0; let mut x9: u32 = 0; fiat_p384_mulx_u32(&mut x8, &mut x9, x1, 0xffffffff); let mut x10: u32 = 0; let mut x11: u32 = 0; fiat_p384_mulx_u32(&mut x10, &mut x11, x1, 0xffffffff); let mut x12: u32 = 0; let mut x13: u32 = 0; fiat_p384_mulx_u32(&mut x12, &mut x13, x1, 0xffffffff); let mut x14: u32 = 0; let mut x15: u32 = 0; fiat_p384_mulx_u32(&mut x14, &mut x15, x1, 0xffffffff); let mut x16: u32 = 0; let mut x17: u32 = 0; fiat_p384_mulx_u32(&mut x16, &mut x17, x1, 0xfffffffe); let mut x18: u32 = 0; let mut x19: u32 = 0; fiat_p384_mulx_u32(&mut x18, &mut x19, x1, 0xffffffff); let mut x20: u32 = 0; let mut x21: u32 = 0; fiat_p384_mulx_u32(&mut x20, &mut x21, x1, 0xffffffff); let mut x22: u32 = 0; let mut x23: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x22, &mut x23, 0x0, x19, x16); let mut x24: u32 = 0; let mut x25: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x24, &mut x25, x23, x17, x14); let mut x26: u32 = 0; let mut x27: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x26, &mut x27, x25, x15, x12); let mut x28: u32 = 0; let mut x29: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x28, &mut x29, x27, x13, x10); let mut x30: u32 = 0; let mut x31: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x30, &mut x31, x29, x11, x8); let mut x32: u32 = 0; let mut x33: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x32, &mut x33, x31, x9, x6); let mut x34: u32 = 0; let mut x35: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x34, &mut x35, x33, x7, x4); let mut x36: u32 = 0; let mut x37: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x36, &mut x37, x35, x5, x2); let mut x38: u32 = 0; let mut x39: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x38, &mut x39, 0x0, x1, x20); let mut x40: u32 = 0; let mut x41: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x40, &mut x41, 0x0, ((x39 as u32) + x21), (arg1[1])); let mut x42: u32 = 0; let mut x43: u32 = 0; fiat_p384_mulx_u32(&mut x42, &mut x43, x40, 0xffffffff); let mut x44: u32 = 0; let mut x45: u32 = 0; fiat_p384_mulx_u32(&mut x44, &mut x45, x40, 0xffffffff); let mut x46: u32 = 0; let mut x47: u32 = 0; fiat_p384_mulx_u32(&mut x46, &mut x47, x40, 0xffffffff); let mut x48: u32 = 0; let mut x49: u32 = 0; fiat_p384_mulx_u32(&mut x48, &mut x49, x40, 0xffffffff); let mut x50: u32 = 0; let mut x51: u32 = 0; fiat_p384_mulx_u32(&mut x50, &mut x51, x40, 0xffffffff); let mut x52: u32 = 0; let mut x53: u32 = 0; fiat_p384_mulx_u32(&mut x52, &mut x53, x40, 0xffffffff); let mut x54: u32 = 0; let mut x55: u32 = 0; fiat_p384_mulx_u32(&mut x54, &mut x55, x40, 0xffffffff); let mut x56: u32 = 0; let mut x57: u32 = 0; fiat_p384_mulx_u32(&mut x56, &mut x57, x40, 0xfffffffe); let mut x58: u32 = 0; let mut x59: u32 = 0; fiat_p384_mulx_u32(&mut x58, &mut x59, x40, 0xffffffff); let mut x60: u32 = 0; let mut x61: u32 = 0; fiat_p384_mulx_u32(&mut x60, &mut x61, x40, 0xffffffff); let mut x62: u32 = 0; let mut x63: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x62, &mut x63, 0x0, x59, x56); let mut x64: u32 = 0; let mut x65: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x64, &mut x65, x63, x57, x54); let mut x66: u32 = 0; let mut x67: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x66, &mut x67, x65, x55, x52); let mut x68: u32 = 0; let mut x69: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x68, &mut x69, x67, x53, x50); let mut x70: u32 = 0; let mut x71: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x70, &mut x71, x69, x51, x48); let mut x72: u32 = 0; let mut x73: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x72, &mut x73, x71, x49, x46); let mut x74: u32 = 0; let mut x75: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x74, &mut x75, x73, x47, x44); let mut x76: u32 = 0; let mut x77: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x76, &mut x77, x75, x45, x42); let mut x78: u32 = 0; let mut x79: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x78, &mut x79, 0x0, x40, x60); let mut x80: u32 = 0; let mut x81: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x80, &mut x81, x79, (x41 as u32), x61); let mut x82: u32 = 0; let mut x83: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x82, &mut x83, x81, x18, (0x0 as u32)); let mut x84: u32 = 0; let mut x85: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x84, &mut x85, x83, x22, x58); let mut x86: u32 = 0; let mut x87: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x86, &mut x87, x85, x24, x62); let mut x88: u32 = 0; let mut x89: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x88, &mut x89, x87, x26, x64); let mut x90: u32 = 0; let mut x91: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x90, &mut x91, x89, x28, x66); let mut x92: u32 = 0; let mut x93: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x92, &mut x93, x91, x30, x68); let mut x94: u32 = 0; let mut x95: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x94, &mut x95, x93, x32, x70); let mut x96: u32 = 0; let mut x97: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x96, &mut x97, x95, x34, x72); let mut x98: u32 = 0; let mut x99: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x98, &mut x99, x97, x36, x74); let mut x100: u32 = 0; let mut x101: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x100, &mut x101, x99, ((x37 as u32) + x3), x76); let mut x102: u32 = 0; let mut x103: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x102, &mut x103, x101, (0x0 as u32), ((x77 as u32) + x43)); let mut x104: u32 = 0; let mut x105: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x104, &mut x105, 0x0, x80, (arg1[2])); let mut x106: u32 = 0; let mut x107: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x106, &mut x107, x105, x82, (0x0 as u32)); let mut x108: u32 = 0; let mut x109: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x108, &mut x109, x107, x84, (0x0 as u32)); let mut x110: u32 = 0; let mut x111: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x110, &mut x111, x109, x86, (0x0 as u32)); let mut x112: u32 = 0; let mut x113: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x112, &mut x113, x111, x88, (0x0 as u32)); let mut x114: u32 = 0; let mut x115: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x114, &mut x115, x113, x90, (0x0 as u32)); let mut x116: u32 = 0; let mut x117: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x116, &mut x117, x115, x92, (0x0 as u32)); let mut x118: u32 = 0; let mut x119: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x118, &mut x119, x117, x94, (0x0 as u32)); let mut x120: u32 = 0; let mut x121: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x120, &mut x121, x119, x96, (0x0 as u32)); let mut x122: u32 = 0; let mut x123: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x122, &mut x123, x121, x98, (0x0 as u32)); let mut x124: u32 = 0; let mut x125: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x124, &mut x125, x123, x100, (0x0 as u32)); let mut x126: u32 = 0; let mut x127: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x126, &mut x127, x125, x102, (0x0 as u32)); let mut x128: u32 = 0; let mut x129: u32 = 0; fiat_p384_mulx_u32(&mut x128, &mut x129, x104, 0xffffffff); let mut x130: u32 = 0; let mut x131: u32 = 0; fiat_p384_mulx_u32(&mut x130, &mut x131, x104, 0xffffffff); let mut x132: u32 = 0; let mut x133: u32 = 0; fiat_p384_mulx_u32(&mut x132, &mut x133, x104, 0xffffffff); let mut x134: u32 = 0; let mut x135: u32 = 0; fiat_p384_mulx_u32(&mut x134, &mut x135, x104, 0xffffffff); let mut x136: u32 = 0; let mut x137: u32 = 0; fiat_p384_mulx_u32(&mut x136, &mut x137, x104, 0xffffffff); let mut x138: u32 = 0; let mut x139: u32 = 0; fiat_p384_mulx_u32(&mut x138, &mut x139, x104, 0xffffffff); let mut x140: u32 = 0; let mut x141: u32 = 0; fiat_p384_mulx_u32(&mut x140, &mut x141, x104, 0xffffffff); let mut x142: u32 = 0; let mut x143: u32 = 0; fiat_p384_mulx_u32(&mut x142, &mut x143, x104, 0xfffffffe); let mut x144: u32 = 0; let mut x145: u32 = 0; fiat_p384_mulx_u32(&mut x144, &mut x145, x104, 0xffffffff); let mut x146: u32 = 0; let mut x147: u32 = 0; fiat_p384_mulx_u32(&mut x146, &mut x147, x104, 0xffffffff); let mut x148: u32 = 0; let mut x149: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x148, &mut x149, 0x0, x145, x142); let mut x150: u32 = 0; let mut x151: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x150, &mut x151, x149, x143, x140); let mut x152: u32 = 0; let mut x153: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x152, &mut x153, x151, x141, x138); let mut x154: u32 = 0; let mut x155: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x154, &mut x155, x153, x139, x136); let mut x156: u32 = 0; let mut x157: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x156, &mut x157, x155, x137, x134); let mut x158: u32 = 0; let mut x159: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x158, &mut x159, x157, x135, x132); let mut x160: u32 = 0; let mut x161: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x160, &mut x161, x159, x133, x130); let mut x162: u32 = 0; let mut x163: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x162, &mut x163, x161, x131, x128); let mut x164: u32 = 0; let mut x165: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x164, &mut x165, 0x0, x104, x146); let mut x166: u32 = 0; let mut x167: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x166, &mut x167, x165, x106, x147); let mut x168: u32 = 0; let mut x169: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x168, &mut x169, x167, x108, (0x0 as u32)); let mut x170: u32 = 0; let mut x171: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x170, &mut x171, x169, x110, x144); let mut x172: u32 = 0; let mut x173: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x172, &mut x173, x171, x112, x148); let mut x174: u32 = 0; let mut x175: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x174, &mut x175, x173, x114, x150); let mut x176: u32 = 0; let mut x177: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x176, &mut x177, x175, x116, x152); let mut x178: u32 = 0; let mut x179: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x178, &mut x179, x177, x118, x154); let mut x180: u32 = 0; let mut x181: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x180, &mut x181, x179, x120, x156); let mut x182: u32 = 0; let mut x183: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x182, &mut x183, x181, x122, x158); let mut x184: u32 = 0; let mut x185: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x184, &mut x185, x183, x124, x160); let mut x186: u32 = 0; let mut x187: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x186, &mut x187, x185, x126, x162); let mut x188: u32 = 0; let mut x189: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x188, &mut x189, x187, ((x127 as u32) + (x103 as u32)), ((x163 as u32) + x129)); let mut x190: u32 = 0; let mut x191: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x190, &mut x191, 0x0, x166, (arg1[3])); let mut x192: u32 = 0; let mut x193: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x192, &mut x193, x191, x168, (0x0 as u32)); let mut x194: u32 = 0; let mut x195: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x194, &mut x195, x193, x170, (0x0 as u32)); let mut x196: u32 = 0; let mut x197: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x196, &mut x197, x195, x172, (0x0 as u32)); let mut x198: u32 = 0; let mut x199: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x198, &mut x199, x197, x174, (0x0 as u32)); let mut x200: u32 = 0; let mut x201: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x200, &mut x201, x199, x176, (0x0 as u32)); let mut x202: u32 = 0; let mut x203: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x202, &mut x203, x201, x178, (0x0 as u32)); let mut x204: u32 = 0; let mut x205: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x204, &mut x205, x203, x180, (0x0 as u32)); let mut x206: u32 = 0; let mut x207: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x206, &mut x207, x205, x182, (0x0 as u32)); let mut x208: u32 = 0; let mut x209: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x208, &mut x209, x207, x184, (0x0 as u32)); let mut x210: u32 = 0; let mut x211: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x210, &mut x211, x209, x186, (0x0 as u32)); let mut x212: u32 = 0; let mut x213: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x212, &mut x213, x211, x188, (0x0 as u32)); let mut x214: u32 = 0; let mut x215: u32 = 0; fiat_p384_mulx_u32(&mut x214, &mut x215, x190, 0xffffffff); let mut x216: u32 = 0; let mut x217: u32 = 0; fiat_p384_mulx_u32(&mut x216, &mut x217, x190, 0xffffffff); let mut x218: u32 = 0; let mut x219: u32 = 0; fiat_p384_mulx_u32(&mut x218, &mut x219, x190, 0xffffffff); let mut x220: u32 = 0; let mut x221: u32 = 0; fiat_p384_mulx_u32(&mut x220, &mut x221, x190, 0xffffffff); let mut x222: u32 = 0; let mut x223: u32 = 0; fiat_p384_mulx_u32(&mut x222, &mut x223, x190, 0xffffffff); let mut x224: u32 = 0; let mut x225: u32 = 0; fiat_p384_mulx_u32(&mut x224, &mut x225, x190, 0xffffffff); let mut x226: u32 = 0; let mut x227: u32 = 0; fiat_p384_mulx_u32(&mut x226, &mut x227, x190, 0xffffffff); let mut x228: u32 = 0; let mut x229: u32 = 0; fiat_p384_mulx_u32(&mut x228, &mut x229, x190, 0xfffffffe); let mut x230: u32 = 0; let mut x231: u32 = 0; fiat_p384_mulx_u32(&mut x230, &mut x231, x190, 0xffffffff); let mut x232: u32 = 0; let mut x233: u32 = 0; fiat_p384_mulx_u32(&mut x232, &mut x233, x190, 0xffffffff); let mut x234: u32 = 0; let mut x235: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x234, &mut x235, 0x0, x231, x228); let mut x236: u32 = 0; let mut x237: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x236, &mut x237, x235, x229, x226); let mut x238: u32 = 0; let mut x239: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x238, &mut x239, x237, x227, x224); let mut x240: u32 = 0; let mut x241: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x240, &mut x241, x239, x225, x222); let mut x242: u32 = 0; let mut x243: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x242, &mut x243, x241, x223, x220); let mut x244: u32 = 0; let mut x245: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x244, &mut x245, x243, x221, x218); let mut x246: u32 = 0; let mut x247: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x246, &mut x247, x245, x219, x216); let mut x248: u32 = 0; let mut x249: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x248, &mut x249, x247, x217, x214); let mut x250: u32 = 0; let mut x251: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x250, &mut x251, 0x0, x190, x232); let mut x252: u32 = 0; let mut x253: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x252, &mut x253, x251, x192, x233); let mut x254: u32 = 0; let mut x255: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x254, &mut x255, x253, x194, (0x0 as u32)); let mut x256: u32 = 0; let mut x257: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x256, &mut x257, x255, x196, x230); let mut x258: u32 = 0; let mut x259: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x258, &mut x259, x257, x198, x234); let mut x260: u32 = 0; let mut x261: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x260, &mut x261, x259, x200, x236); let mut x262: u32 = 0; let mut x263: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x262, &mut x263, x261, x202, x238); let mut x264: u32 = 0; let mut x265: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x264, &mut x265, x263, x204, x240); let mut x266: u32 = 0; let mut x267: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x266, &mut x267, x265, x206, x242); let mut x268: u32 = 0; let mut x269: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x268, &mut x269, x267, x208, x244); let mut x270: u32 = 0; let mut x271: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x270, &mut x271, x269, x210, x246); let mut x272: u32 = 0; let mut x273: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x272, &mut x273, x271, x212, x248); let mut x274: u32 = 0; let mut x275: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x274, &mut x275, x273, ((x213 as u32) + (x189 as u32)), ((x249 as u32) + x215)); let mut x276: u32 = 0; let mut x277: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x276, &mut x277, 0x0, x252, (arg1[4])); let mut x278: u32 = 0; let mut x279: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x278, &mut x279, x277, x254, (0x0 as u32)); let mut x280: u32 = 0; let mut x281: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x280, &mut x281, x279, x256, (0x0 as u32)); let mut x282: u32 = 0; let mut x283: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x282, &mut x283, x281, x258, (0x0 as u32)); let mut x284: u32 = 0; let mut x285: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x284, &mut x285, x283, x260, (0x0 as u32)); let mut x286: u32 = 0; let mut x287: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x286, &mut x287, x285, x262, (0x0 as u32)); let mut x288: u32 = 0; let mut x289: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x288, &mut x289, x287, x264, (0x0 as u32)); let mut x290: u32 = 0; let mut x291: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x290, &mut x291, x289, x266, (0x0 as u32)); let mut x292: u32 = 0; let mut x293: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x292, &mut x293, x291, x268, (0x0 as u32)); let mut x294: u32 = 0; let mut x295: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x294, &mut x295, x293, x270, (0x0 as u32)); let mut x296: u32 = 0; let mut x297: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x296, &mut x297, x295, x272, (0x0 as u32)); let mut x298: u32 = 0; let mut x299: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x298, &mut x299, x297, x274, (0x0 as u32)); let mut x300: u32 = 0; let mut x301: u32 = 0; fiat_p384_mulx_u32(&mut x300, &mut x301, x276, 0xffffffff); let mut x302: u32 = 0; let mut x303: u32 = 0; fiat_p384_mulx_u32(&mut x302, &mut x303, x276, 0xffffffff); let mut x304: u32 = 0; let mut x305: u32 = 0; fiat_p384_mulx_u32(&mut x304, &mut x305, x276, 0xffffffff); let mut x306: u32 = 0; let mut x307: u32 = 0; fiat_p384_mulx_u32(&mut x306, &mut x307, x276, 0xffffffff); let mut x308: u32 = 0; let mut x309: u32 = 0; fiat_p384_mulx_u32(&mut x308, &mut x309, x276, 0xffffffff); let mut x310: u32 = 0; let mut x311: u32 = 0; fiat_p384_mulx_u32(&mut x310, &mut x311, x276, 0xffffffff); let mut x312: u32 = 0; let mut x313: u32 = 0; fiat_p384_mulx_u32(&mut x312, &mut x313, x276, 0xffffffff); let mut x314: u32 = 0; let mut x315: u32 = 0; fiat_p384_mulx_u32(&mut x314, &mut x315, x276, 0xfffffffe); let mut x316: u32 = 0; let mut x317: u32 = 0; fiat_p384_mulx_u32(&mut x316, &mut x317, x276, 0xffffffff); let mut x318: u32 = 0; let mut x319: u32 = 0; fiat_p384_mulx_u32(&mut x318, &mut x319, x276, 0xffffffff); let mut x320: u32 = 0; let mut x321: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x320, &mut x321, 0x0, x317, x314); let mut x322: u32 = 0; let mut x323: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x322, &mut x323, x321, x315, x312); let mut x324: u32 = 0; let mut x325: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x324, &mut x325, x323, x313, x310); let mut x326: u32 = 0; let mut x327: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x326, &mut x327, x325, x311, x308); let mut x328: u32 = 0; let mut x329: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x328, &mut x329, x327, x309, x306); let mut x330: u32 = 0; let mut x331: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x330, &mut x331, x329, x307, x304); let mut x332: u32 = 0; let mut x333: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x332, &mut x333, x331, x305, x302); let mut x334: u32 = 0; let mut x335: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x334, &mut x335, x333, x303, x300); let mut x336: u32 = 0; let mut x337: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x336, &mut x337, 0x0, x276, x318); let mut x338: u32 = 0; let mut x339: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x338, &mut x339, x337, x278, x319); let mut x340: u32 = 0; let mut x341: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x340, &mut x341, x339, x280, (0x0 as u32)); let mut x342: u32 = 0; let mut x343: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x342, &mut x343, x341, x282, x316); let mut x344: u32 = 0; let mut x345: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x344, &mut x345, x343, x284, x320); let mut x346: u32 = 0; let mut x347: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x346, &mut x347, x345, x286, x322); let mut x348: u32 = 0; let mut x349: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x348, &mut x349, x347, x288, x324); let mut x350: u32 = 0; let mut x351: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x350, &mut x351, x349, x290, x326); let mut x352: u32 = 0; let mut x353: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x352, &mut x353, x351, x292, x328); let mut x354: u32 = 0; let mut x355: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x354, &mut x355, x353, x294, x330); let mut x356: u32 = 0; let mut x357: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x356, &mut x357, x355, x296, x332); let mut x358: u32 = 0; let mut x359: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x358, &mut x359, x357, x298, x334); let mut x360: u32 = 0; let mut x361: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x360, &mut x361, x359, ((x299 as u32) + (x275 as u32)), ((x335 as u32) + x301)); let mut x362: u32 = 0; let mut x363: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x362, &mut x363, 0x0, x338, (arg1[5])); let mut x364: u32 = 0; let mut x365: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x364, &mut x365, x363, x340, (0x0 as u32)); let mut x366: u32 = 0; let mut x367: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x366, &mut x367, x365, x342, (0x0 as u32)); let mut x368: u32 = 0; let mut x369: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x368, &mut x369, x367, x344, (0x0 as u32)); let mut x370: u32 = 0; let mut x371: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x370, &mut x371, x369, x346, (0x0 as u32)); let mut x372: u32 = 0; let mut x373: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x372, &mut x373, x371, x348, (0x0 as u32)); let mut x374: u32 = 0; let mut x375: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x374, &mut x375, x373, x350, (0x0 as u32)); let mut x376: u32 = 0; let mut x377: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x376, &mut x377, x375, x352, (0x0 as u32)); let mut x378: u32 = 0; let mut x379: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x378, &mut x379, x377, x354, (0x0 as u32)); let mut x380: u32 = 0; let mut x381: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x380, &mut x381, x379, x356, (0x0 as u32)); let mut x382: u32 = 0; let mut x383: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x382, &mut x383, x381, x358, (0x0 as u32)); let mut x384: u32 = 0; let mut x385: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x384, &mut x385, x383, x360, (0x0 as u32)); let mut x386: u32 = 0; let mut x387: u32 = 0; fiat_p384_mulx_u32(&mut x386, &mut x387, x362, 0xffffffff); let mut x388: u32 = 0; let mut x389: u32 = 0; fiat_p384_mulx_u32(&mut x388, &mut x389, x362, 0xffffffff); let mut x390: u32 = 0; let mut x391: u32 = 0; fiat_p384_mulx_u32(&mut x390, &mut x391, x362, 0xffffffff); let mut x392: u32 = 0; let mut x393: u32 = 0; fiat_p384_mulx_u32(&mut x392, &mut x393, x362, 0xffffffff); let mut x394: u32 = 0; let mut x395: u32 = 0; fiat_p384_mulx_u32(&mut x394, &mut x395, x362, 0xffffffff); let mut x396: u32 = 0; let mut x397: u32 = 0; fiat_p384_mulx_u32(&mut x396, &mut x397, x362, 0xffffffff); let mut x398: u32 = 0; let mut x399: u32 = 0; fiat_p384_mulx_u32(&mut x398, &mut x399, x362, 0xffffffff); let mut x400: u32 = 0; let mut x401: u32 = 0; fiat_p384_mulx_u32(&mut x400, &mut x401, x362, 0xfffffffe); let mut x402: u32 = 0; let mut x403: u32 = 0; fiat_p384_mulx_u32(&mut x402, &mut x403, x362, 0xffffffff); let mut x404: u32 = 0; let mut x405: u32 = 0; fiat_p384_mulx_u32(&mut x404, &mut x405, x362, 0xffffffff); let mut x406: u32 = 0; let mut x407: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x406, &mut x407, 0x0, x403, x400); let mut x408: u32 = 0; let mut x409: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x408, &mut x409, x407, x401, x398); let mut x410: u32 = 0; let mut x411: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x410, &mut x411, x409, x399, x396); let mut x412: u32 = 0; let mut x413: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x412, &mut x413, x411, x397, x394); let mut x414: u32 = 0; let mut x415: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x414, &mut x415, x413, x395, x392); let mut x416: u32 = 0; let mut x417: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x416, &mut x417, x415, x393, x390); let mut x418: u32 = 0; let mut x419: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x418, &mut x419, x417, x391, x388); let mut x420: u32 = 0; let mut x421: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x420, &mut x421, x419, x389, x386); let mut x422: u32 = 0; let mut x423: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x422, &mut x423, 0x0, x362, x404); let mut x424: u32 = 0; let mut x425: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x424, &mut x425, x423, x364, x405); let mut x426: u32 = 0; let mut x427: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x426, &mut x427, x425, x366, (0x0 as u32)); let mut x428: u32 = 0; let mut x429: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x428, &mut x429, x427, x368, x402); let mut x430: u32 = 0; let mut x431: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x430, &mut x431, x429, x370, x406); let mut x432: u32 = 0; let mut x433: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x432, &mut x433, x431, x372, x408); let mut x434: u32 = 0; let mut x435: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x434, &mut x435, x433, x374, x410); let mut x436: u32 = 0; let mut x437: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x436, &mut x437, x435, x376, x412); let mut x438: u32 = 0; let mut x439: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x438, &mut x439, x437, x378, x414); let mut x440: u32 = 0; let mut x441: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x440, &mut x441, x439, x380, x416); let mut x442: u32 = 0; let mut x443: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x442, &mut x443, x441, x382, x418); let mut x444: u32 = 0; let mut x445: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x444, &mut x445, x443, x384, x420); let mut x446: u32 = 0; let mut x447: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x446, &mut x447, x445, ((x385 as u32) + (x361 as u32)), ((x421 as u32) + x387)); let mut x448: u32 = 0; let mut x449: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x448, &mut x449, 0x0, x424, (arg1[6])); let mut x450: u32 = 0; let mut x451: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x450, &mut x451, x449, x426, (0x0 as u32)); let mut x452: u32 = 0; let mut x453: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x452, &mut x453, x451, x428, (0x0 as u32)); let mut x454: u32 = 0; let mut x455: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x454, &mut x455, x453, x430, (0x0 as u32)); let mut x456: u32 = 0; let mut x457: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x456, &mut x457, x455, x432, (0x0 as u32)); let mut x458: u32 = 0; let mut x459: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x458, &mut x459, x457, x434, (0x0 as u32)); let mut x460: u32 = 0; let mut x461: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x460, &mut x461, x459, x436, (0x0 as u32)); let mut x462: u32 = 0; let mut x463: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x462, &mut x463, x461, x438, (0x0 as u32)); let mut x464: u32 = 0; let mut x465: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x464, &mut x465, x463, x440, (0x0 as u32)); let mut x466: u32 = 0; let mut x467: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x466, &mut x467, x465, x442, (0x0 as u32)); let mut x468: u32 = 0; let mut x469: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x468, &mut x469, x467, x444, (0x0 as u32)); let mut x470: u32 = 0; let mut x471: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x470, &mut x471, x469, x446, (0x0 as u32)); let mut x472: u32 = 0; let mut x473: u32 = 0; fiat_p384_mulx_u32(&mut x472, &mut x473, x448, 0xffffffff); let mut x474: u32 = 0; let mut x475: u32 = 0; fiat_p384_mulx_u32(&mut x474, &mut x475, x448, 0xffffffff); let mut x476: u32 = 0; let mut x477: u32 = 0; fiat_p384_mulx_u32(&mut x476, &mut x477, x448, 0xffffffff); let mut x478: u32 = 0; let mut x479: u32 = 0; fiat_p384_mulx_u32(&mut x478, &mut x479, x448, 0xffffffff); let mut x480: u32 = 0; let mut x481: u32 = 0; fiat_p384_mulx_u32(&mut x480, &mut x481, x448, 0xffffffff); let mut x482: u32 = 0; let mut x483: u32 = 0; fiat_p384_mulx_u32(&mut x482, &mut x483, x448, 0xffffffff); let mut x484: u32 = 0; let mut x485: u32 = 0; fiat_p384_mulx_u32(&mut x484, &mut x485, x448, 0xffffffff); let mut x486: u32 = 0; let mut x487: u32 = 0; fiat_p384_mulx_u32(&mut x486, &mut x487, x448, 0xfffffffe); let mut x488: u32 = 0; let mut x489: u32 = 0; fiat_p384_mulx_u32(&mut x488, &mut x489, x448, 0xffffffff); let mut x490: u32 = 0; let mut x491: u32 = 0; fiat_p384_mulx_u32(&mut x490, &mut x491, x448, 0xffffffff); let mut x492: u32 = 0; let mut x493: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x492, &mut x493, 0x0, x489, x486); let mut x494: u32 = 0; let mut x495: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x494, &mut x495, x493, x487, x484); let mut x496: u32 = 0; let mut x497: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x496, &mut x497, x495, x485, x482); let mut x498: u32 = 0; let mut x499: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x498, &mut x499, x497, x483, x480); let mut x500: u32 = 0; let mut x501: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x500, &mut x501, x499, x481, x478); let mut x502: u32 = 0; let mut x503: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x502, &mut x503, x501, x479, x476); let mut x504: u32 = 0; let mut x505: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x504, &mut x505, x503, x477, x474); let mut x506: u32 = 0; let mut x507: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x506, &mut x507, x505, x475, x472); let mut x508: u32 = 0; let mut x509: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x508, &mut x509, 0x0, x448, x490); let mut x510: u32 = 0; let mut x511: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x510, &mut x511, x509, x450, x491); let mut x512: u32 = 0; let mut x513: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x512, &mut x513, x511, x452, (0x0 as u32)); let mut x514: u32 = 0; let mut x515: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x514, &mut x515, x513, x454, x488); let mut x516: u32 = 0; let mut x517: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x516, &mut x517, x515, x456, x492); let mut x518: u32 = 0; let mut x519: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x518, &mut x519, x517, x458, x494); let mut x520: u32 = 0; let mut x521: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x520, &mut x521, x519, x460, x496); let mut x522: u32 = 0; let mut x523: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x522, &mut x523, x521, x462, x498); let mut x524: u32 = 0; let mut x525: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x524, &mut x525, x523, x464, x500); let mut x526: u32 = 0; let mut x527: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x526, &mut x527, x525, x466, x502); let mut x528: u32 = 0; let mut x529: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x528, &mut x529, x527, x468, x504); let mut x530: u32 = 0; let mut x531: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x530, &mut x531, x529, x470, x506); let mut x532: u32 = 0; let mut x533: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x532, &mut x533, x531, ((x471 as u32) + (x447 as u32)), ((x507 as u32) + x473)); let mut x534: u32 = 0; let mut x535: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x534, &mut x535, 0x0, x510, (arg1[7])); let mut x536: u32 = 0; let mut x537: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x536, &mut x537, x535, x512, (0x0 as u32)); let mut x538: u32 = 0; let mut x539: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x538, &mut x539, x537, x514, (0x0 as u32)); let mut x540: u32 = 0; let mut x541: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x540, &mut x541, x539, x516, (0x0 as u32)); let mut x542: u32 = 0; let mut x543: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x542, &mut x543, x541, x518, (0x0 as u32)); let mut x544: u32 = 0; let mut x545: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x544, &mut x545, x543, x520, (0x0 as u32)); let mut x546: u32 = 0; let mut x547: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x546, &mut x547, x545, x522, (0x0 as u32)); let mut x548: u32 = 0; let mut x549: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x548, &mut x549, x547, x524, (0x0 as u32)); let mut x550: u32 = 0; let mut x551: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x550, &mut x551, x549, x526, (0x0 as u32)); let mut x552: u32 = 0; let mut x553: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x552, &mut x553, x551, x528, (0x0 as u32)); let mut x554: u32 = 0; let mut x555: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x554, &mut x555, x553, x530, (0x0 as u32)); let mut x556: u32 = 0; let mut x557: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x556, &mut x557, x555, x532, (0x0 as u32)); let mut x558: u32 = 0; let mut x559: u32 = 0; fiat_p384_mulx_u32(&mut x558, &mut x559, x534, 0xffffffff); let mut x560: u32 = 0; let mut x561: u32 = 0; fiat_p384_mulx_u32(&mut x560, &mut x561, x534, 0xffffffff); let mut x562: u32 = 0; let mut x563: u32 = 0; fiat_p384_mulx_u32(&mut x562, &mut x563, x534, 0xffffffff); let mut x564: u32 = 0; let mut x565: u32 = 0; fiat_p384_mulx_u32(&mut x564, &mut x565, x534, 0xffffffff); let mut x566: u32 = 0; let mut x567: u32 = 0; fiat_p384_mulx_u32(&mut x566, &mut x567, x534, 0xffffffff); let mut x568: u32 = 0; let mut x569: u32 = 0; fiat_p384_mulx_u32(&mut x568, &mut x569, x534, 0xffffffff); let mut x570: u32 = 0; let mut x571: u32 = 0; fiat_p384_mulx_u32(&mut x570, &mut x571, x534, 0xffffffff); let mut x572: u32 = 0; let mut x573: u32 = 0; fiat_p384_mulx_u32(&mut x572, &mut x573, x534, 0xfffffffe); let mut x574: u32 = 0; let mut x575: u32 = 0; fiat_p384_mulx_u32(&mut x574, &mut x575, x534, 0xffffffff); let mut x576: u32 = 0; let mut x577: u32 = 0; fiat_p384_mulx_u32(&mut x576, &mut x577, x534, 0xffffffff); let mut x578: u32 = 0; let mut x579: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x578, &mut x579, 0x0, x575, x572); let mut x580: u32 = 0; let mut x581: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x580, &mut x581, x579, x573, x570); let mut x582: u32 = 0; let mut x583: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x582, &mut x583, x581, x571, x568); let mut x584: u32 = 0; let mut x585: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x584, &mut x585, x583, x569, x566); let mut x586: u32 = 0; let mut x587: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x586, &mut x587, x585, x567, x564); let mut x588: u32 = 0; let mut x589: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x588, &mut x589, x587, x565, x562); let mut x590: u32 = 0; let mut x591: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x590, &mut x591, x589, x563, x560); let mut x592: u32 = 0; let mut x593: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x592, &mut x593, x591, x561, x558); let mut x594: u32 = 0; let mut x595: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x594, &mut x595, 0x0, x534, x576); let mut x596: u32 = 0; let mut x597: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x596, &mut x597, x595, x536, x577); let mut x598: u32 = 0; let mut x599: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x598, &mut x599, x597, x538, (0x0 as u32)); let mut x600: u32 = 0; let mut x601: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x600, &mut x601, x599, x540, x574); let mut x602: u32 = 0; let mut x603: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x602, &mut x603, x601, x542, x578); let mut x604: u32 = 0; let mut x605: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x604, &mut x605, x603, x544, x580); let mut x606: u32 = 0; let mut x607: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x606, &mut x607, x605, x546, x582); let mut x608: u32 = 0; let mut x609: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x608, &mut x609, x607, x548, x584); let mut x610: u32 = 0; let mut x611: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x610, &mut x611, x609, x550, x586); let mut x612: u32 = 0; let mut x613: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x612, &mut x613, x611, x552, x588); let mut x614: u32 = 0; let mut x615: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x614, &mut x615, x613, x554, x590); let mut x616: u32 = 0; let mut x617: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x616, &mut x617, x615, x556, x592); let mut x618: u32 = 0; let mut x619: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x618, &mut x619, x617, ((x557 as u32) + (x533 as u32)), ((x593 as u32) + x559)); let mut x620: u32 = 0; let mut x621: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x620, &mut x621, 0x0, x596, (arg1[8])); let mut x622: u32 = 0; let mut x623: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x622, &mut x623, x621, x598, (0x0 as u32)); let mut x624: u32 = 0; let mut x625: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x624, &mut x625, x623, x600, (0x0 as u32)); let mut x626: u32 = 0; let mut x627: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x626, &mut x627, x625, x602, (0x0 as u32)); let mut x628: u32 = 0; let mut x629: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x628, &mut x629, x627, x604, (0x0 as u32)); let mut x630: u32 = 0; let mut x631: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x630, &mut x631, x629, x606, (0x0 as u32)); let mut x632: u32 = 0; let mut x633: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x632, &mut x633, x631, x608, (0x0 as u32)); let mut x634: u32 = 0; let mut x635: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x634, &mut x635, x633, x610, (0x0 as u32)); let mut x636: u32 = 0; let mut x637: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x636, &mut x637, x635, x612, (0x0 as u32)); let mut x638: u32 = 0; let mut x639: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x638, &mut x639, x637, x614, (0x0 as u32)); let mut x640: u32 = 0; let mut x641: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x640, &mut x641, x639, x616, (0x0 as u32)); let mut x642: u32 = 0; let mut x643: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x642, &mut x643, x641, x618, (0x0 as u32)); let mut x644: u32 = 0; let mut x645: u32 = 0; fiat_p384_mulx_u32(&mut x644, &mut x645, x620, 0xffffffff); let mut x646: u32 = 0; let mut x647: u32 = 0; fiat_p384_mulx_u32(&mut x646, &mut x647, x620, 0xffffffff); let mut x648: u32 = 0; let mut x649: u32 = 0; fiat_p384_mulx_u32(&mut x648, &mut x649, x620, 0xffffffff); let mut x650: u32 = 0; let mut x651: u32 = 0; fiat_p384_mulx_u32(&mut x650, &mut x651, x620, 0xffffffff); let mut x652: u32 = 0; let mut x653: u32 = 0; fiat_p384_mulx_u32(&mut x652, &mut x653, x620, 0xffffffff); let mut x654: u32 = 0; let mut x655: u32 = 0; fiat_p384_mulx_u32(&mut x654, &mut x655, x620, 0xffffffff); let mut x656: u32 = 0; let mut x657: u32 = 0; fiat_p384_mulx_u32(&mut x656, &mut x657, x620, 0xffffffff); let mut x658: u32 = 0; let mut x659: u32 = 0; fiat_p384_mulx_u32(&mut x658, &mut x659, x620, 0xfffffffe); let mut x660: u32 = 0; let mut x661: u32 = 0; fiat_p384_mulx_u32(&mut x660, &mut x661, x620, 0xffffffff); let mut x662: u32 = 0; let mut x663: u32 = 0; fiat_p384_mulx_u32(&mut x662, &mut x663, x620, 0xffffffff); let mut x664: u32 = 0; let mut x665: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x664, &mut x665, 0x0, x661, x658); let mut x666: u32 = 0; let mut x667: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x666, &mut x667, x665, x659, x656); let mut x668: u32 = 0; let mut x669: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x668, &mut x669, x667, x657, x654); let mut x670: u32 = 0; let mut x671: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x670, &mut x671, x669, x655, x652); let mut x672: u32 = 0; let mut x673: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x672, &mut x673, x671, x653, x650); let mut x674: u32 = 0; let mut x675: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x674, &mut x675, x673, x651, x648); let mut x676: u32 = 0; let mut x677: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x676, &mut x677, x675, x649, x646); let mut x678: u32 = 0; let mut x679: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x678, &mut x679, x677, x647, x644); let mut x680: u32 = 0; let mut x681: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x680, &mut x681, 0x0, x620, x662); let mut x682: u32 = 0; let mut x683: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x682, &mut x683, x681, x622, x663); let mut x684: u32 = 0; let mut x685: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x684, &mut x685, x683, x624, (0x0 as u32)); let mut x686: u32 = 0; let mut x687: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x686, &mut x687, x685, x626, x660); let mut x688: u32 = 0; let mut x689: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x688, &mut x689, x687, x628, x664); let mut x690: u32 = 0; let mut x691: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x690, &mut x691, x689, x630, x666); let mut x692: u32 = 0; let mut x693: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x692, &mut x693, x691, x632, x668); let mut x694: u32 = 0; let mut x695: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x694, &mut x695, x693, x634, x670); let mut x696: u32 = 0; let mut x697: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x696, &mut x697, x695, x636, x672); let mut x698: u32 = 0; let mut x699: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x698, &mut x699, x697, x638, x674); let mut x700: u32 = 0; let mut x701: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x700, &mut x701, x699, x640, x676); let mut x702: u32 = 0; let mut x703: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x702, &mut x703, x701, x642, x678); let mut x704: u32 = 0; let mut x705: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x704, &mut x705, x703, ((x643 as u32) + (x619 as u32)), ((x679 as u32) + x645)); let mut x706: u32 = 0; let mut x707: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x706, &mut x707, 0x0, x682, (arg1[9])); let mut x708: u32 = 0; let mut x709: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x708, &mut x709, x707, x684, (0x0 as u32)); let mut x710: u32 = 0; let mut x711: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x710, &mut x711, x709, x686, (0x0 as u32)); let mut x712: u32 = 0; let mut x713: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x712, &mut x713, x711, x688, (0x0 as u32)); let mut x714: u32 = 0; let mut x715: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x714, &mut x715, x713, x690, (0x0 as u32)); let mut x716: u32 = 0; let mut x717: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x716, &mut x717, x715, x692, (0x0 as u32)); let mut x718: u32 = 0; let mut x719: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x718, &mut x719, x717, x694, (0x0 as u32)); let mut x720: u32 = 0; let mut x721: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x720, &mut x721, x719, x696, (0x0 as u32)); let mut x722: u32 = 0; let mut x723: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x722, &mut x723, x721, x698, (0x0 as u32)); let mut x724: u32 = 0; let mut x725: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x724, &mut x725, x723, x700, (0x0 as u32)); let mut x726: u32 = 0; let mut x727: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x726, &mut x727, x725, x702, (0x0 as u32)); let mut x728: u32 = 0; let mut x729: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x728, &mut x729, x727, x704, (0x0 as u32)); let mut x730: u32 = 0; let mut x731: u32 = 0; fiat_p384_mulx_u32(&mut x730, &mut x731, x706, 0xffffffff); let mut x732: u32 = 0; let mut x733: u32 = 0; fiat_p384_mulx_u32(&mut x732, &mut x733, x706, 0xffffffff); let mut x734: u32 = 0; let mut x735: u32 = 0; fiat_p384_mulx_u32(&mut x734, &mut x735, x706, 0xffffffff); let mut x736: u32 = 0; let mut x737: u32 = 0; fiat_p384_mulx_u32(&mut x736, &mut x737, x706, 0xffffffff); let mut x738: u32 = 0; let mut x739: u32 = 0; fiat_p384_mulx_u32(&mut x738, &mut x739, x706, 0xffffffff); let mut x740: u32 = 0; let mut x741: u32 = 0; fiat_p384_mulx_u32(&mut x740, &mut x741, x706, 0xffffffff); let mut x742: u32 = 0; let mut x743: u32 = 0; fiat_p384_mulx_u32(&mut x742, &mut x743, x706, 0xffffffff); let mut x744: u32 = 0; let mut x745: u32 = 0; fiat_p384_mulx_u32(&mut x744, &mut x745, x706, 0xfffffffe); let mut x746: u32 = 0; let mut x747: u32 = 0; fiat_p384_mulx_u32(&mut x746, &mut x747, x706, 0xffffffff); let mut x748: u32 = 0; let mut x749: u32 = 0; fiat_p384_mulx_u32(&mut x748, &mut x749, x706, 0xffffffff); let mut x750: u32 = 0; let mut x751: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x750, &mut x751, 0x0, x747, x744); let mut x752: u32 = 0; let mut x753: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x752, &mut x753, x751, x745, x742); let mut x754: u32 = 0; let mut x755: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x754, &mut x755, x753, x743, x740); let mut x756: u32 = 0; let mut x757: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x756, &mut x757, x755, x741, x738); let mut x758: u32 = 0; let mut x759: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x758, &mut x759, x757, x739, x736); let mut x760: u32 = 0; let mut x761: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x760, &mut x761, x759, x737, x734); let mut x762: u32 = 0; let mut x763: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x762, &mut x763, x761, x735, x732); let mut x764: u32 = 0; let mut x765: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x764, &mut x765, x763, x733, x730); let mut x766: u32 = 0; let mut x767: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x766, &mut x767, 0x0, x706, x748); let mut x768: u32 = 0; let mut x769: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x768, &mut x769, x767, x708, x749); let mut x770: u32 = 0; let mut x771: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x770, &mut x771, x769, x710, (0x0 as u32)); let mut x772: u32 = 0; let mut x773: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x772, &mut x773, x771, x712, x746); let mut x774: u32 = 0; let mut x775: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x774, &mut x775, x773, x714, x750); let mut x776: u32 = 0; let mut x777: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x776, &mut x777, x775, x716, x752); let mut x778: u32 = 0; let mut x779: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x778, &mut x779, x777, x718, x754); let mut x780: u32 = 0; let mut x781: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x780, &mut x781, x779, x720, x756); let mut x782: u32 = 0; let mut x783: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x782, &mut x783, x781, x722, x758); let mut x784: u32 = 0; let mut x785: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x784, &mut x785, x783, x724, x760); let mut x786: u32 = 0; let mut x787: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x786, &mut x787, x785, x726, x762); let mut x788: u32 = 0; let mut x789: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x788, &mut x789, x787, x728, x764); let mut x790: u32 = 0; let mut x791: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x790, &mut x791, x789, ((x729 as u32) + (x705 as u32)), ((x765 as u32) + x731)); let mut x792: u32 = 0; let mut x793: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x792, &mut x793, 0x0, x768, (arg1[10])); let mut x794: u32 = 0; let mut x795: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x794, &mut x795, x793, x770, (0x0 as u32)); let mut x796: u32 = 0; let mut x797: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x796, &mut x797, x795, x772, (0x0 as u32)); let mut x798: u32 = 0; let mut x799: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x798, &mut x799, x797, x774, (0x0 as u32)); let mut x800: u32 = 0; let mut x801: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x800, &mut x801, x799, x776, (0x0 as u32)); let mut x802: u32 = 0; let mut x803: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x802, &mut x803, x801, x778, (0x0 as u32)); let mut x804: u32 = 0; let mut x805: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x804, &mut x805, x803, x780, (0x0 as u32)); let mut x806: u32 = 0; let mut x807: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x806, &mut x807, x805, x782, (0x0 as u32)); let mut x808: u32 = 0; let mut x809: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x808, &mut x809, x807, x784, (0x0 as u32)); let mut x810: u32 = 0; let mut x811: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x810, &mut x811, x809, x786, (0x0 as u32)); let mut x812: u32 = 0; let mut x813: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x812, &mut x813, x811, x788, (0x0 as u32)); let mut x814: u32 = 0; let mut x815: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x814, &mut x815, x813, x790, (0x0 as u32)); let mut x816: u32 = 0; let mut x817: u32 = 0; fiat_p384_mulx_u32(&mut x816, &mut x817, x792, 0xffffffff); let mut x818: u32 = 0; let mut x819: u32 = 0; fiat_p384_mulx_u32(&mut x818, &mut x819, x792, 0xffffffff); let mut x820: u32 = 0; let mut x821: u32 = 0; fiat_p384_mulx_u32(&mut x820, &mut x821, x792, 0xffffffff); let mut x822: u32 = 0; let mut x823: u32 = 0; fiat_p384_mulx_u32(&mut x822, &mut x823, x792, 0xffffffff); let mut x824: u32 = 0; let mut x825: u32 = 0; fiat_p384_mulx_u32(&mut x824, &mut x825, x792, 0xffffffff); let mut x826: u32 = 0; let mut x827: u32 = 0; fiat_p384_mulx_u32(&mut x826, &mut x827, x792, 0xffffffff); let mut x828: u32 = 0; let mut x829: u32 = 0; fiat_p384_mulx_u32(&mut x828, &mut x829, x792, 0xffffffff); let mut x830: u32 = 0; let mut x831: u32 = 0; fiat_p384_mulx_u32(&mut x830, &mut x831, x792, 0xfffffffe); let mut x832: u32 = 0; let mut x833: u32 = 0; fiat_p384_mulx_u32(&mut x832, &mut x833, x792, 0xffffffff); let mut x834: u32 = 0; let mut x835: u32 = 0; fiat_p384_mulx_u32(&mut x834, &mut x835, x792, 0xffffffff); let mut x836: u32 = 0; let mut x837: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x836, &mut x837, 0x0, x833, x830); let mut x838: u32 = 0; let mut x839: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x838, &mut x839, x837, x831, x828); let mut x840: u32 = 0; let mut x841: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x840, &mut x841, x839, x829, x826); let mut x842: u32 = 0; let mut x843: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x842, &mut x843, x841, x827, x824); let mut x844: u32 = 0; let mut x845: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x844, &mut x845, x843, x825, x822); let mut x846: u32 = 0; let mut x847: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x846, &mut x847, x845, x823, x820); let mut x848: u32 = 0; let mut x849: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x848, &mut x849, x847, x821, x818); let mut x850: u32 = 0; let mut x851: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x850, &mut x851, x849, x819, x816); let mut x852: u32 = 0; let mut x853: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x852, &mut x853, 0x0, x792, x834); let mut x854: u32 = 0; let mut x855: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x854, &mut x855, x853, x794, x835); let mut x856: u32 = 0; let mut x857: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x856, &mut x857, x855, x796, (0x0 as u32)); let mut x858: u32 = 0; let mut x859: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x858, &mut x859, x857, x798, x832); let mut x860: u32 = 0; let mut x861: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x860, &mut x861, x859, x800, x836); let mut x862: u32 = 0; let mut x863: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x862, &mut x863, x861, x802, x838); let mut x864: u32 = 0; let mut x865: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x864, &mut x865, x863, x804, x840); let mut x866: u32 = 0; let mut x867: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x866, &mut x867, x865, x806, x842); let mut x868: u32 = 0; let mut x869: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x868, &mut x869, x867, x808, x844); let mut x870: u32 = 0; let mut x871: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x870, &mut x871, x869, x810, x846); let mut x872: u32 = 0; let mut x873: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x872, &mut x873, x871, x812, x848); let mut x874: u32 = 0; let mut x875: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x874, &mut x875, x873, x814, x850); let mut x876: u32 = 0; let mut x877: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x876, &mut x877, x875, ((x815 as u32) + (x791 as u32)), ((x851 as u32) + x817)); let mut x878: u32 = 0; let mut x879: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x878, &mut x879, 0x0, x854, (arg1[11])); let mut x880: u32 = 0; let mut x881: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x880, &mut x881, x879, x856, (0x0 as u32)); let mut x882: u32 = 0; let mut x883: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x882, &mut x883, x881, x858, (0x0 as u32)); let mut x884: u32 = 0; let mut x885: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x884, &mut x885, x883, x860, (0x0 as u32)); let mut x886: u32 = 0; let mut x887: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x886, &mut x887, x885, x862, (0x0 as u32)); let mut x888: u32 = 0; let mut x889: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x888, &mut x889, x887, x864, (0x0 as u32)); let mut x890: u32 = 0; let mut x891: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x890, &mut x891, x889, x866, (0x0 as u32)); let mut x892: u32 = 0; let mut x893: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x892, &mut x893, x891, x868, (0x0 as u32)); let mut x894: u32 = 0; let mut x895: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x894, &mut x895, x893, x870, (0x0 as u32)); let mut x896: u32 = 0; let mut x897: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x896, &mut x897, x895, x872, (0x0 as u32)); let mut x898: u32 = 0; let mut x899: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x898, &mut x899, x897, x874, (0x0 as u32)); let mut x900: u32 = 0; let mut x901: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x900, &mut x901, x899, x876, (0x0 as u32)); let mut x902: u32 = 0; let mut x903: u32 = 0; fiat_p384_mulx_u32(&mut x902, &mut x903, x878, 0xffffffff); let mut x904: u32 = 0; let mut x905: u32 = 0; fiat_p384_mulx_u32(&mut x904, &mut x905, x878, 0xffffffff); let mut x906: u32 = 0; let mut x907: u32 = 0; fiat_p384_mulx_u32(&mut x906, &mut x907, x878, 0xffffffff); let mut x908: u32 = 0; let mut x909: u32 = 0; fiat_p384_mulx_u32(&mut x908, &mut x909, x878, 0xffffffff); let mut x910: u32 = 0; let mut x911: u32 = 0; fiat_p384_mulx_u32(&mut x910, &mut x911, x878, 0xffffffff); let mut x912: u32 = 0; let mut x913: u32 = 0; fiat_p384_mulx_u32(&mut x912, &mut x913, x878, 0xffffffff); let mut x914: u32 = 0; let mut x915: u32 = 0; fiat_p384_mulx_u32(&mut x914, &mut x915, x878, 0xffffffff); let mut x916: u32 = 0; let mut x917: u32 = 0; fiat_p384_mulx_u32(&mut x916, &mut x917, x878, 0xfffffffe); let mut x918: u32 = 0; let mut x919: u32 = 0; fiat_p384_mulx_u32(&mut x918, &mut x919, x878, 0xffffffff); let mut x920: u32 = 0; let mut x921: u32 = 0; fiat_p384_mulx_u32(&mut x920, &mut x921, x878, 0xffffffff); let mut x922: u32 = 0; let mut x923: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x922, &mut x923, 0x0, x919, x916); let mut x924: u32 = 0; let mut x925: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x924, &mut x925, x923, x917, x914); let mut x926: u32 = 0; let mut x927: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x926, &mut x927, x925, x915, x912); let mut x928: u32 = 0; let mut x929: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x928, &mut x929, x927, x913, x910); let mut x930: u32 = 0; let mut x931: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x930, &mut x931, x929, x911, x908); let mut x932: u32 = 0; let mut x933: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x932, &mut x933, x931, x909, x906); let mut x934: u32 = 0; let mut x935: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x934, &mut x935, x933, x907, x904); let mut x936: u32 = 0; let mut x937: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x936, &mut x937, x935, x905, x902); let mut x938: u32 = 0; let mut x939: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x938, &mut x939, 0x0, x878, x920); let mut x940: u32 = 0; let mut x941: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x940, &mut x941, x939, x880, x921); let mut x942: u32 = 0; let mut x943: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x942, &mut x943, x941, x882, (0x0 as u32)); let mut x944: u32 = 0; let mut x945: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x944, &mut x945, x943, x884, x918); let mut x946: u32 = 0; let mut x947: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x946, &mut x947, x945, x886, x922); let mut x948: u32 = 0; let mut x949: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x948, &mut x949, x947, x888, x924); let mut x950: u32 = 0; let mut x951: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x950, &mut x951, x949, x890, x926); let mut x952: u32 = 0; let mut x953: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x952, &mut x953, x951, x892, x928); let mut x954: u32 = 0; let mut x955: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x954, &mut x955, x953, x894, x930); let mut x956: u32 = 0; let mut x957: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x956, &mut x957, x955, x896, x932); let mut x958: u32 = 0; let mut x959: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x958, &mut x959, x957, x898, x934); let mut x960: u32 = 0; let mut x961: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x960, &mut x961, x959, x900, x936); let mut x962: u32 = 0; let mut x963: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x962, &mut x963, x961, ((x901 as u32) + (x877 as u32)), ((x937 as u32) + x903)); let mut x964: u32 = 0; let mut x965: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x964, &mut x965, 0x0, x940, 0xffffffff); let mut x966: u32 = 0; let mut x967: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x966, &mut x967, x965, x942, (0x0 as u32)); let mut x968: u32 = 0; let mut x969: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x968, &mut x969, x967, x944, (0x0 as u32)); let mut x970: u32 = 0; let mut x971: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x970, &mut x971, x969, x946, 0xffffffff); let mut x972: u32 = 0; let mut x973: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x972, &mut x973, x971, x948, 0xfffffffe); let mut x974: u32 = 0; let mut x975: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x974, &mut x975, x973, x950, 0xffffffff); let mut x976: u32 = 0; let mut x977: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x976, &mut x977, x975, x952, 0xffffffff); let mut x978: u32 = 0; let mut x979: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x978, &mut x979, x977, x954, 0xffffffff); let mut x980: u32 = 0; let mut x981: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x980, &mut x981, x979, x956, 0xffffffff); let mut x982: u32 = 0; let mut x983: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x982, &mut x983, x981, x958, 0xffffffff); let mut x984: u32 = 0; let mut x985: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x984, &mut x985, x983, x960, 0xffffffff); let mut x986: u32 = 0; let mut x987: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x986, &mut x987, x985, x962, 0xffffffff); let mut x988: u32 = 0; let mut x989: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x988, &mut x989, x987, (x963 as u32), (0x0 as u32)); let mut x990: u32 = 0; fiat_p384_cmovznz_u32(&mut x990, x989, x964, x940); let mut x991: u32 = 0; fiat_p384_cmovznz_u32(&mut x991, x989, x966, x942); let mut x992: u32 = 0; fiat_p384_cmovznz_u32(&mut x992, x989, x968, x944); let mut x993: u32 = 0; fiat_p384_cmovznz_u32(&mut x993, x989, x970, x946); let mut x994: u32 = 0; fiat_p384_cmovznz_u32(&mut x994, x989, x972, x948); let mut x995: u32 = 0; fiat_p384_cmovznz_u32(&mut x995, x989, x974, x950); let mut x996: u32 = 0; fiat_p384_cmovznz_u32(&mut x996, x989, x976, x952); let mut x997: u32 = 0; fiat_p384_cmovznz_u32(&mut x997, x989, x978, x954); let mut x998: u32 = 0; fiat_p384_cmovznz_u32(&mut x998, x989, x980, x956); let mut x999: u32 = 0; fiat_p384_cmovznz_u32(&mut x999, x989, x982, x958); let mut x1000: u32 = 0; fiat_p384_cmovznz_u32(&mut x1000, x989, x984, x960); let mut x1001: u32 = 0; fiat_p384_cmovznz_u32(&mut x1001, x989, x986, x962); out1[0] = x990; out1[1] = x991; out1[2] = x992; out1[3] = x993; out1[4] = x994; out1[5] = x995; out1[6] = x996; out1[7] = x997; out1[8] = x998; out1[9] = x999; out1[10] = x1000; out1[11] = x1001; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_to_montgomery(out1: &mut [u32; 12], arg1: &[u32; 12]) -> () { let x1: u32 = (arg1[1]); let x2: u32 = (arg1[2]); let x3: u32 = (arg1[3]); let x4: u32 = (arg1[4]); let x5: u32 = (arg1[5]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[7]); let x8: u32 = (arg1[8]); let x9: u32 = (arg1[9]); let x10: u32 = (arg1[10]); let x11: u32 = (arg1[11]); let x12: u32 = (arg1[0]); let mut x13: u32 = 0; let mut x14: u32 = 0; fiat_p384_mulx_u32(&mut x13, &mut x14, x12, 0x2); let mut x15: u32 = 0; let mut x16: u32 = 0; fiat_p384_mulx_u32(&mut x15, &mut x16, x12, 0xfffffffe); let mut x17: u32 = 0; let mut x18: u32 = 0; fiat_p384_mulx_u32(&mut x17, &mut x18, x12, 0x2); let mut x19: u32 = 0; let mut x20: u32 = 0; fiat_p384_mulx_u32(&mut x19, &mut x20, x12, 0xfffffffe); let mut x21: u32 = 0; let mut x22: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x21, &mut x22, 0x0, ((x14 as fiat_p384_u1) as u32), x12); let mut x23: u32 = 0; let mut x24: u32 = 0; fiat_p384_mulx_u32(&mut x23, &mut x24, x12, 0xffffffff); let mut x25: u32 = 0; let mut x26: u32 = 0; fiat_p384_mulx_u32(&mut x25, &mut x26, x12, 0xffffffff); let mut x27: u32 = 0; let mut x28: u32 = 0; fiat_p384_mulx_u32(&mut x27, &mut x28, x12, 0xffffffff); let mut x29: u32 = 0; let mut x30: u32 = 0; fiat_p384_mulx_u32(&mut x29, &mut x30, x12, 0xffffffff); let mut x31: u32 = 0; let mut x32: u32 = 0; fiat_p384_mulx_u32(&mut x31, &mut x32, x12, 0xffffffff); let mut x33: u32 = 0; let mut x34: u32 = 0; fiat_p384_mulx_u32(&mut x33, &mut x34, x12, 0xffffffff); let mut x35: u32 = 0; let mut x36: u32 = 0; fiat_p384_mulx_u32(&mut x35, &mut x36, x12, 0xffffffff); let mut x37: u32 = 0; let mut x38: u32 = 0; fiat_p384_mulx_u32(&mut x37, &mut x38, x12, 0xfffffffe); let mut x39: u32 = 0; let mut x40: u32 = 0; fiat_p384_mulx_u32(&mut x39, &mut x40, x12, 0xffffffff); let mut x41: u32 = 0; let mut x42: u32 = 0; fiat_p384_mulx_u32(&mut x41, &mut x42, x12, 0xffffffff); let mut x43: u32 = 0; let mut x44: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x43, &mut x44, 0x0, x40, x37); let mut x45: u32 = 0; let mut x46: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x45, &mut x46, x44, x38, x35); let mut x47: u32 = 0; let mut x48: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x47, &mut x48, x46, x36, x33); let mut x49: u32 = 0; let mut x50: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x49, &mut x50, x48, x34, x31); let mut x51: u32 = 0; let mut x52: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x51, &mut x52, x50, x32, x29); let mut x53: u32 = 0; let mut x54: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x53, &mut x54, x52, x30, x27); let mut x55: u32 = 0; let mut x56: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x55, &mut x56, x54, x28, x25); let mut x57: u32 = 0; let mut x58: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x57, &mut x58, x56, x26, x23); let mut x59: u32 = 0; let mut x60: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x59, &mut x60, 0x0, x12, x41); let mut x61: u32 = 0; let mut x62: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x61, &mut x62, x60, x19, x42); let mut x63: u32 = 0; let mut x64: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x63, &mut x64, 0x0, x17, x39); let mut x65: u32 = 0; let mut x66: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x65, &mut x66, x64, ((x18 as fiat_p384_u1) as u32), x43); let mut x67: u32 = 0; let mut x68: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x67, &mut x68, x66, x15, x45); let mut x69: u32 = 0; let mut x70: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x69, &mut x70, x68, x16, x47); let mut x71: u32 = 0; let mut x72: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x71, &mut x72, x70, x13, x49); let mut x73: u32 = 0; let mut x74: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x73, &mut x74, x72, x21, x51); let mut x75: u32 = 0; let mut x76: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x75, &mut x76, x74, (x22 as u32), x53); let mut x77: u32 = 0; let mut x78: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x77, &mut x78, x76, (0x0 as u32), x55); let mut x79: u32 = 0; let mut x80: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x79, &mut x80, x78, (0x0 as u32), x57); let mut x81: u32 = 0; let mut x82: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x81, &mut x82, x80, (0x0 as u32), ((x58 as u32) + x24)); let mut x83: u32 = 0; let mut x84: u32 = 0; fiat_p384_mulx_u32(&mut x83, &mut x84, x1, 0x2); let mut x85: u32 = 0; let mut x86: u32 = 0; fiat_p384_mulx_u32(&mut x85, &mut x86, x1, 0xfffffffe); let mut x87: u32 = 0; let mut x88: u32 = 0; fiat_p384_mulx_u32(&mut x87, &mut x88, x1, 0x2); let mut x89: u32 = 0; let mut x90: u32 = 0; fiat_p384_mulx_u32(&mut x89, &mut x90, x1, 0xfffffffe); let mut x91: u32 = 0; let mut x92: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x91, &mut x92, 0x0, ((x84 as fiat_p384_u1) as u32), x1); let mut x93: u32 = 0; let mut x94: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x93, &mut x94, 0x0, x61, x1); let mut x95: u32 = 0; let mut x96: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x95, &mut x96, x94, ((x62 as u32) + x20), x89); let mut x97: u32 = 0; let mut x98: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x97, &mut x98, x96, x63, x90); let mut x99: u32 = 0; let mut x100: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x99, &mut x100, x98, x65, x87); let mut x101: u32 = 0; let mut x102: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x101, &mut x102, x100, x67, ((x88 as fiat_p384_u1) as u32)); let mut x103: u32 = 0; let mut x104: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x103, &mut x104, x102, x69, x85); let mut x105: u32 = 0; let mut x106: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x105, &mut x106, x104, x71, x86); let mut x107: u32 = 0; let mut x108: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x107, &mut x108, x106, x73, x83); let mut x109: u32 = 0; let mut x110: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x109, &mut x110, x108, x75, x91); let mut x111: u32 = 0; let mut x112: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x111, &mut x112, x110, x77, (x92 as u32)); let mut x113: u32 = 0; let mut x114: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x113, &mut x114, x112, x79, (0x0 as u32)); let mut x115: u32 = 0; let mut x116: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x115, &mut x116, x114, x81, (0x0 as u32)); let mut x117: u32 = 0; let mut x118: u32 = 0; fiat_p384_mulx_u32(&mut x117, &mut x118, x93, 0xffffffff); let mut x119: u32 = 0; let mut x120: u32 = 0; fiat_p384_mulx_u32(&mut x119, &mut x120, x93, 0xffffffff); let mut x121: u32 = 0; let mut x122: u32 = 0; fiat_p384_mulx_u32(&mut x121, &mut x122, x93, 0xffffffff); let mut x123: u32 = 0; let mut x124: u32 = 0; fiat_p384_mulx_u32(&mut x123, &mut x124, x93, 0xffffffff); let mut x125: u32 = 0; let mut x126: u32 = 0; fiat_p384_mulx_u32(&mut x125, &mut x126, x93, 0xffffffff); let mut x127: u32 = 0; let mut x128: u32 = 0; fiat_p384_mulx_u32(&mut x127, &mut x128, x93, 0xffffffff); let mut x129: u32 = 0; let mut x130: u32 = 0; fiat_p384_mulx_u32(&mut x129, &mut x130, x93, 0xffffffff); let mut x131: u32 = 0; let mut x132: u32 = 0; fiat_p384_mulx_u32(&mut x131, &mut x132, x93, 0xfffffffe); let mut x133: u32 = 0; let mut x134: u32 = 0; fiat_p384_mulx_u32(&mut x133, &mut x134, x93, 0xffffffff); let mut x135: u32 = 0; let mut x136: u32 = 0; fiat_p384_mulx_u32(&mut x135, &mut x136, x93, 0xffffffff); let mut x137: u32 = 0; let mut x138: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x137, &mut x138, 0x0, x134, x131); let mut x139: u32 = 0; let mut x140: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x139, &mut x140, x138, x132, x129); let mut x141: u32 = 0; let mut x142: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x141, &mut x142, x140, x130, x127); let mut x143: u32 = 0; let mut x144: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x143, &mut x144, x142, x128, x125); let mut x145: u32 = 0; let mut x146: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x145, &mut x146, x144, x126, x123); let mut x147: u32 = 0; let mut x148: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x147, &mut x148, x146, x124, x121); let mut x149: u32 = 0; let mut x150: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x149, &mut x150, x148, x122, x119); let mut x151: u32 = 0; let mut x152: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x151, &mut x152, x150, x120, x117); let mut x153: u32 = 0; let mut x154: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x153, &mut x154, 0x0, x93, x135); let mut x155: u32 = 0; let mut x156: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x155, &mut x156, x154, x95, x136); let mut x157: u32 = 0; let mut x158: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x157, &mut x158, x156, x97, (0x0 as u32)); let mut x159: u32 = 0; let mut x160: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x159, &mut x160, x158, x99, x133); let mut x161: u32 = 0; let mut x162: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x161, &mut x162, x160, x101, x137); let mut x163: u32 = 0; let mut x164: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x163, &mut x164, x162, x103, x139); let mut x165: u32 = 0; let mut x166: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x165, &mut x166, x164, x105, x141); let mut x167: u32 = 0; let mut x168: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x167, &mut x168, x166, x107, x143); let mut x169: u32 = 0; let mut x170: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x169, &mut x170, x168, x109, x145); let mut x171: u32 = 0; let mut x172: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x171, &mut x172, x170, x111, x147); let mut x173: u32 = 0; let mut x174: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x173, &mut x174, x172, x113, x149); let mut x175: u32 = 0; let mut x176: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x175, &mut x176, x174, x115, x151); let mut x177: u32 = 0; let mut x178: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x177, &mut x178, x176, ((x116 as u32) + (x82 as u32)), ((x152 as u32) + x118)); let mut x179: u32 = 0; let mut x180: u32 = 0; fiat_p384_mulx_u32(&mut x179, &mut x180, x2, 0x2); let mut x181: u32 = 0; let mut x182: u32 = 0; fiat_p384_mulx_u32(&mut x181, &mut x182, x2, 0xfffffffe); let mut x183: u32 = 0; let mut x184: u32 = 0; fiat_p384_mulx_u32(&mut x183, &mut x184, x2, 0x2); let mut x185: u32 = 0; let mut x186: u32 = 0; fiat_p384_mulx_u32(&mut x185, &mut x186, x2, 0xfffffffe); let mut x187: u32 = 0; let mut x188: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x187, &mut x188, 0x0, ((x180 as fiat_p384_u1) as u32), x2); let mut x189: u32 = 0; let mut x190: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x189, &mut x190, 0x0, x155, x2); let mut x191: u32 = 0; let mut x192: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x191, &mut x192, x190, x157, x185); let mut x193: u32 = 0; let mut x194: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x193, &mut x194, x192, x159, x186); let mut x195: u32 = 0; let mut x196: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x195, &mut x196, x194, x161, x183); let mut x197: u32 = 0; let mut x198: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x197, &mut x198, x196, x163, ((x184 as fiat_p384_u1) as u32)); let mut x199: u32 = 0; let mut x200: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x199, &mut x200, x198, x165, x181); let mut x201: u32 = 0; let mut x202: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x201, &mut x202, x200, x167, x182); let mut x203: u32 = 0; let mut x204: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x203, &mut x204, x202, x169, x179); let mut x205: u32 = 0; let mut x206: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x205, &mut x206, x204, x171, x187); let mut x207: u32 = 0; let mut x208: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x207, &mut x208, x206, x173, (x188 as u32)); let mut x209: u32 = 0; let mut x210: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x209, &mut x210, x208, x175, (0x0 as u32)); let mut x211: u32 = 0; let mut x212: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x211, &mut x212, x210, x177, (0x0 as u32)); let mut x213: u32 = 0; let mut x214: u32 = 0; fiat_p384_mulx_u32(&mut x213, &mut x214, x189, 0xffffffff); let mut x215: u32 = 0; let mut x216: u32 = 0; fiat_p384_mulx_u32(&mut x215, &mut x216, x189, 0xffffffff); let mut x217: u32 = 0; let mut x218: u32 = 0; fiat_p384_mulx_u32(&mut x217, &mut x218, x189, 0xffffffff); let mut x219: u32 = 0; let mut x220: u32 = 0; fiat_p384_mulx_u32(&mut x219, &mut x220, x189, 0xffffffff); let mut x221: u32 = 0; let mut x222: u32 = 0; fiat_p384_mulx_u32(&mut x221, &mut x222, x189, 0xffffffff); let mut x223: u32 = 0; let mut x224: u32 = 0; fiat_p384_mulx_u32(&mut x223, &mut x224, x189, 0xffffffff); let mut x225: u32 = 0; let mut x226: u32 = 0; fiat_p384_mulx_u32(&mut x225, &mut x226, x189, 0xffffffff); let mut x227: u32 = 0; let mut x228: u32 = 0; fiat_p384_mulx_u32(&mut x227, &mut x228, x189, 0xfffffffe); let mut x229: u32 = 0; let mut x230: u32 = 0; fiat_p384_mulx_u32(&mut x229, &mut x230, x189, 0xffffffff); let mut x231: u32 = 0; let mut x232: u32 = 0; fiat_p384_mulx_u32(&mut x231, &mut x232, x189, 0xffffffff); let mut x233: u32 = 0; let mut x234: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x233, &mut x234, 0x0, x230, x227); let mut x235: u32 = 0; let mut x236: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x235, &mut x236, x234, x228, x225); let mut x237: u32 = 0; let mut x238: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x237, &mut x238, x236, x226, x223); let mut x239: u32 = 0; let mut x240: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x239, &mut x240, x238, x224, x221); let mut x241: u32 = 0; let mut x242: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x241, &mut x242, x240, x222, x219); let mut x243: u32 = 0; let mut x244: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x243, &mut x244, x242, x220, x217); let mut x245: u32 = 0; let mut x246: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x245, &mut x246, x244, x218, x215); let mut x247: u32 = 0; let mut x248: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x247, &mut x248, x246, x216, x213); let mut x249: u32 = 0; let mut x250: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x249, &mut x250, 0x0, x189, x231); let mut x251: u32 = 0; let mut x252: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x251, &mut x252, x250, x191, x232); let mut x253: u32 = 0; let mut x254: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x253, &mut x254, x252, x193, (0x0 as u32)); let mut x255: u32 = 0; let mut x256: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x255, &mut x256, x254, x195, x229); let mut x257: u32 = 0; let mut x258: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x257, &mut x258, x256, x197, x233); let mut x259: u32 = 0; let mut x260: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x259, &mut x260, x258, x199, x235); let mut x261: u32 = 0; let mut x262: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x261, &mut x262, x260, x201, x237); let mut x263: u32 = 0; let mut x264: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x263, &mut x264, x262, x203, x239); let mut x265: u32 = 0; let mut x266: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x265, &mut x266, x264, x205, x241); let mut x267: u32 = 0; let mut x268: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x267, &mut x268, x266, x207, x243); let mut x269: u32 = 0; let mut x270: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x269, &mut x270, x268, x209, x245); let mut x271: u32 = 0; let mut x272: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x271, &mut x272, x270, x211, x247); let mut x273: u32 = 0; let mut x274: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x273, &mut x274, x272, ((x212 as u32) + (x178 as u32)), ((x248 as u32) + x214)); let mut x275: u32 = 0; let mut x276: u32 = 0; fiat_p384_mulx_u32(&mut x275, &mut x276, x3, 0x2); let mut x277: u32 = 0; let mut x278: u32 = 0; fiat_p384_mulx_u32(&mut x277, &mut x278, x3, 0xfffffffe); let mut x279: u32 = 0; let mut x280: u32 = 0; fiat_p384_mulx_u32(&mut x279, &mut x280, x3, 0x2); let mut x281: u32 = 0; let mut x282: u32 = 0; fiat_p384_mulx_u32(&mut x281, &mut x282, x3, 0xfffffffe); let mut x283: u32 = 0; let mut x284: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x283, &mut x284, 0x0, ((x276 as fiat_p384_u1) as u32), x3); let mut x285: u32 = 0; let mut x286: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x285, &mut x286, 0x0, x251, x3); let mut x287: u32 = 0; let mut x288: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x287, &mut x288, x286, x253, x281); let mut x289: u32 = 0; let mut x290: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x289, &mut x290, x288, x255, x282); let mut x291: u32 = 0; let mut x292: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x291, &mut x292, x290, x257, x279); let mut x293: u32 = 0; let mut x294: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x293, &mut x294, x292, x259, ((x280 as fiat_p384_u1) as u32)); let mut x295: u32 = 0; let mut x296: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x295, &mut x296, x294, x261, x277); let mut x297: u32 = 0; let mut x298: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x297, &mut x298, x296, x263, x278); let mut x299: u32 = 0; let mut x300: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x299, &mut x300, x298, x265, x275); let mut x301: u32 = 0; let mut x302: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x301, &mut x302, x300, x267, x283); let mut x303: u32 = 0; let mut x304: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x303, &mut x304, x302, x269, (x284 as u32)); let mut x305: u32 = 0; let mut x306: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x305, &mut x306, x304, x271, (0x0 as u32)); let mut x307: u32 = 0; let mut x308: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x307, &mut x308, x306, x273, (0x0 as u32)); let mut x309: u32 = 0; let mut x310: u32 = 0; fiat_p384_mulx_u32(&mut x309, &mut x310, x285, 0xffffffff); let mut x311: u32 = 0; let mut x312: u32 = 0; fiat_p384_mulx_u32(&mut x311, &mut x312, x285, 0xffffffff); let mut x313: u32 = 0; let mut x314: u32 = 0; fiat_p384_mulx_u32(&mut x313, &mut x314, x285, 0xffffffff); let mut x315: u32 = 0; let mut x316: u32 = 0; fiat_p384_mulx_u32(&mut x315, &mut x316, x285, 0xffffffff); let mut x317: u32 = 0; let mut x318: u32 = 0; fiat_p384_mulx_u32(&mut x317, &mut x318, x285, 0xffffffff); let mut x319: u32 = 0; let mut x320: u32 = 0; fiat_p384_mulx_u32(&mut x319, &mut x320, x285, 0xffffffff); let mut x321: u32 = 0; let mut x322: u32 = 0; fiat_p384_mulx_u32(&mut x321, &mut x322, x285, 0xffffffff); let mut x323: u32 = 0; let mut x324: u32 = 0; fiat_p384_mulx_u32(&mut x323, &mut x324, x285, 0xfffffffe); let mut x325: u32 = 0; let mut x326: u32 = 0; fiat_p384_mulx_u32(&mut x325, &mut x326, x285, 0xffffffff); let mut x327: u32 = 0; let mut x328: u32 = 0; fiat_p384_mulx_u32(&mut x327, &mut x328, x285, 0xffffffff); let mut x329: u32 = 0; let mut x330: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x329, &mut x330, 0x0, x326, x323); let mut x331: u32 = 0; let mut x332: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x331, &mut x332, x330, x324, x321); let mut x333: u32 = 0; let mut x334: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x333, &mut x334, x332, x322, x319); let mut x335: u32 = 0; let mut x336: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x335, &mut x336, x334, x320, x317); let mut x337: u32 = 0; let mut x338: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x337, &mut x338, x336, x318, x315); let mut x339: u32 = 0; let mut x340: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x339, &mut x340, x338, x316, x313); let mut x341: u32 = 0; let mut x342: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x341, &mut x342, x340, x314, x311); let mut x343: u32 = 0; let mut x344: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x343, &mut x344, x342, x312, x309); let mut x345: u32 = 0; let mut x346: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x345, &mut x346, 0x0, x285, x327); let mut x347: u32 = 0; let mut x348: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x347, &mut x348, x346, x287, x328); let mut x349: u32 = 0; let mut x350: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x349, &mut x350, x348, x289, (0x0 as u32)); let mut x351: u32 = 0; let mut x352: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x351, &mut x352, x350, x291, x325); let mut x353: u32 = 0; let mut x354: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x353, &mut x354, x352, x293, x329); let mut x355: u32 = 0; let mut x356: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x355, &mut x356, x354, x295, x331); let mut x357: u32 = 0; let mut x358: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x357, &mut x358, x356, x297, x333); let mut x359: u32 = 0; let mut x360: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x359, &mut x360, x358, x299, x335); let mut x361: u32 = 0; let mut x362: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x361, &mut x362, x360, x301, x337); let mut x363: u32 = 0; let mut x364: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x363, &mut x364, x362, x303, x339); let mut x365: u32 = 0; let mut x366: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x365, &mut x366, x364, x305, x341); let mut x367: u32 = 0; let mut x368: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x367, &mut x368, x366, x307, x343); let mut x369: u32 = 0; let mut x370: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x369, &mut x370, x368, ((x308 as u32) + (x274 as u32)), ((x344 as u32) + x310)); let mut x371: u32 = 0; let mut x372: u32 = 0; fiat_p384_mulx_u32(&mut x371, &mut x372, x4, 0x2); let mut x373: u32 = 0; let mut x374: u32 = 0; fiat_p384_mulx_u32(&mut x373, &mut x374, x4, 0xfffffffe); let mut x375: u32 = 0; let mut x376: u32 = 0; fiat_p384_mulx_u32(&mut x375, &mut x376, x4, 0x2); let mut x377: u32 = 0; let mut x378: u32 = 0; fiat_p384_mulx_u32(&mut x377, &mut x378, x4, 0xfffffffe); let mut x379: u32 = 0; let mut x380: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x379, &mut x380, 0x0, ((x372 as fiat_p384_u1) as u32), x4); let mut x381: u32 = 0; let mut x382: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x381, &mut x382, 0x0, x347, x4); let mut x383: u32 = 0; let mut x384: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x383, &mut x384, x382, x349, x377); let mut x385: u32 = 0; let mut x386: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x385, &mut x386, x384, x351, x378); let mut x387: u32 = 0; let mut x388: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x387, &mut x388, x386, x353, x375); let mut x389: u32 = 0; let mut x390: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x389, &mut x390, x388, x355, ((x376 as fiat_p384_u1) as u32)); let mut x391: u32 = 0; let mut x392: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x391, &mut x392, x390, x357, x373); let mut x393: u32 = 0; let mut x394: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x393, &mut x394, x392, x359, x374); let mut x395: u32 = 0; let mut x396: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x395, &mut x396, x394, x361, x371); let mut x397: u32 = 0; let mut x398: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x397, &mut x398, x396, x363, x379); let mut x399: u32 = 0; let mut x400: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x399, &mut x400, x398, x365, (x380 as u32)); let mut x401: u32 = 0; let mut x402: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x401, &mut x402, x400, x367, (0x0 as u32)); let mut x403: u32 = 0; let mut x404: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x403, &mut x404, x402, x369, (0x0 as u32)); let mut x405: u32 = 0; let mut x406: u32 = 0; fiat_p384_mulx_u32(&mut x405, &mut x406, x381, 0xffffffff); let mut x407: u32 = 0; let mut x408: u32 = 0; fiat_p384_mulx_u32(&mut x407, &mut x408, x381, 0xffffffff); let mut x409: u32 = 0; let mut x410: u32 = 0; fiat_p384_mulx_u32(&mut x409, &mut x410, x381, 0xffffffff); let mut x411: u32 = 0; let mut x412: u32 = 0; fiat_p384_mulx_u32(&mut x411, &mut x412, x381, 0xffffffff); let mut x413: u32 = 0; let mut x414: u32 = 0; fiat_p384_mulx_u32(&mut x413, &mut x414, x381, 0xffffffff); let mut x415: u32 = 0; let mut x416: u32 = 0; fiat_p384_mulx_u32(&mut x415, &mut x416, x381, 0xffffffff); let mut x417: u32 = 0; let mut x418: u32 = 0; fiat_p384_mulx_u32(&mut x417, &mut x418, x381, 0xffffffff); let mut x419: u32 = 0; let mut x420: u32 = 0; fiat_p384_mulx_u32(&mut x419, &mut x420, x381, 0xfffffffe); let mut x421: u32 = 0; let mut x422: u32 = 0; fiat_p384_mulx_u32(&mut x421, &mut x422, x381, 0xffffffff); let mut x423: u32 = 0; let mut x424: u32 = 0; fiat_p384_mulx_u32(&mut x423, &mut x424, x381, 0xffffffff); let mut x425: u32 = 0; let mut x426: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x425, &mut x426, 0x0, x422, x419); let mut x427: u32 = 0; let mut x428: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x427, &mut x428, x426, x420, x417); let mut x429: u32 = 0; let mut x430: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x429, &mut x430, x428, x418, x415); let mut x431: u32 = 0; let mut x432: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x431, &mut x432, x430, x416, x413); let mut x433: u32 = 0; let mut x434: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x433, &mut x434, x432, x414, x411); let mut x435: u32 = 0; let mut x436: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x435, &mut x436, x434, x412, x409); let mut x437: u32 = 0; let mut x438: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x437, &mut x438, x436, x410, x407); let mut x439: u32 = 0; let mut x440: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x439, &mut x440, x438, x408, x405); let mut x441: u32 = 0; let mut x442: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x441, &mut x442, 0x0, x381, x423); let mut x443: u32 = 0; let mut x444: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x443, &mut x444, x442, x383, x424); let mut x445: u32 = 0; let mut x446: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x445, &mut x446, x444, x385, (0x0 as u32)); let mut x447: u32 = 0; let mut x448: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x447, &mut x448, x446, x387, x421); let mut x449: u32 = 0; let mut x450: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x449, &mut x450, x448, x389, x425); let mut x451: u32 = 0; let mut x452: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x451, &mut x452, x450, x391, x427); let mut x453: u32 = 0; let mut x454: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x453, &mut x454, x452, x393, x429); let mut x455: u32 = 0; let mut x456: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x455, &mut x456, x454, x395, x431); let mut x457: u32 = 0; let mut x458: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x457, &mut x458, x456, x397, x433); let mut x459: u32 = 0; let mut x460: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x459, &mut x460, x458, x399, x435); let mut x461: u32 = 0; let mut x462: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x461, &mut x462, x460, x401, x437); let mut x463: u32 = 0; let mut x464: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x463, &mut x464, x462, x403, x439); let mut x465: u32 = 0; let mut x466: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x465, &mut x466, x464, ((x404 as u32) + (x370 as u32)), ((x440 as u32) + x406)); let mut x467: u32 = 0; let mut x468: u32 = 0; fiat_p384_mulx_u32(&mut x467, &mut x468, x5, 0x2); let mut x469: u32 = 0; let mut x470: u32 = 0; fiat_p384_mulx_u32(&mut x469, &mut x470, x5, 0xfffffffe); let mut x471: u32 = 0; let mut x472: u32 = 0; fiat_p384_mulx_u32(&mut x471, &mut x472, x5, 0x2); let mut x473: u32 = 0; let mut x474: u32 = 0; fiat_p384_mulx_u32(&mut x473, &mut x474, x5, 0xfffffffe); let mut x475: u32 = 0; let mut x476: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x475, &mut x476, 0x0, ((x468 as fiat_p384_u1) as u32), x5); let mut x477: u32 = 0; let mut x478: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x477, &mut x478, 0x0, x443, x5); let mut x479: u32 = 0; let mut x480: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x479, &mut x480, x478, x445, x473); let mut x481: u32 = 0; let mut x482: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x481, &mut x482, x480, x447, x474); let mut x483: u32 = 0; let mut x484: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x483, &mut x484, x482, x449, x471); let mut x485: u32 = 0; let mut x486: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x485, &mut x486, x484, x451, ((x472 as fiat_p384_u1) as u32)); let mut x487: u32 = 0; let mut x488: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x487, &mut x488, x486, x453, x469); let mut x489: u32 = 0; let mut x490: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x489, &mut x490, x488, x455, x470); let mut x491: u32 = 0; let mut x492: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x491, &mut x492, x490, x457, x467); let mut x493: u32 = 0; let mut x494: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x493, &mut x494, x492, x459, x475); let mut x495: u32 = 0; let mut x496: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x495, &mut x496, x494, x461, (x476 as u32)); let mut x497: u32 = 0; let mut x498: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x497, &mut x498, x496, x463, (0x0 as u32)); let mut x499: u32 = 0; let mut x500: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x499, &mut x500, x498, x465, (0x0 as u32)); let mut x501: u32 = 0; let mut x502: u32 = 0; fiat_p384_mulx_u32(&mut x501, &mut x502, x477, 0xffffffff); let mut x503: u32 = 0; let mut x504: u32 = 0; fiat_p384_mulx_u32(&mut x503, &mut x504, x477, 0xffffffff); let mut x505: u32 = 0; let mut x506: u32 = 0; fiat_p384_mulx_u32(&mut x505, &mut x506, x477, 0xffffffff); let mut x507: u32 = 0; let mut x508: u32 = 0; fiat_p384_mulx_u32(&mut x507, &mut x508, x477, 0xffffffff); let mut x509: u32 = 0; let mut x510: u32 = 0; fiat_p384_mulx_u32(&mut x509, &mut x510, x477, 0xffffffff); let mut x511: u32 = 0; let mut x512: u32 = 0; fiat_p384_mulx_u32(&mut x511, &mut x512, x477, 0xffffffff); let mut x513: u32 = 0; let mut x514: u32 = 0; fiat_p384_mulx_u32(&mut x513, &mut x514, x477, 0xffffffff); let mut x515: u32 = 0; let mut x516: u32 = 0; fiat_p384_mulx_u32(&mut x515, &mut x516, x477, 0xfffffffe); let mut x517: u32 = 0; let mut x518: u32 = 0; fiat_p384_mulx_u32(&mut x517, &mut x518, x477, 0xffffffff); let mut x519: u32 = 0; let mut x520: u32 = 0; fiat_p384_mulx_u32(&mut x519, &mut x520, x477, 0xffffffff); let mut x521: u32 = 0; let mut x522: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x521, &mut x522, 0x0, x518, x515); let mut x523: u32 = 0; let mut x524: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x523, &mut x524, x522, x516, x513); let mut x525: u32 = 0; let mut x526: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x525, &mut x526, x524, x514, x511); let mut x527: u32 = 0; let mut x528: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x527, &mut x528, x526, x512, x509); let mut x529: u32 = 0; let mut x530: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x529, &mut x530, x528, x510, x507); let mut x531: u32 = 0; let mut x532: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x531, &mut x532, x530, x508, x505); let mut x533: u32 = 0; let mut x534: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x533, &mut x534, x532, x506, x503); let mut x535: u32 = 0; let mut x536: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x535, &mut x536, x534, x504, x501); let mut x537: u32 = 0; let mut x538: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x537, &mut x538, 0x0, x477, x519); let mut x539: u32 = 0; let mut x540: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x539, &mut x540, x538, x479, x520); let mut x541: u32 = 0; let mut x542: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x541, &mut x542, x540, x481, (0x0 as u32)); let mut x543: u32 = 0; let mut x544: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x543, &mut x544, x542, x483, x517); let mut x545: u32 = 0; let mut x546: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x545, &mut x546, x544, x485, x521); let mut x547: u32 = 0; let mut x548: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x547, &mut x548, x546, x487, x523); let mut x549: u32 = 0; let mut x550: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x549, &mut x550, x548, x489, x525); let mut x551: u32 = 0; let mut x552: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x551, &mut x552, x550, x491, x527); let mut x553: u32 = 0; let mut x554: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x553, &mut x554, x552, x493, x529); let mut x555: u32 = 0; let mut x556: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x555, &mut x556, x554, x495, x531); let mut x557: u32 = 0; let mut x558: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x557, &mut x558, x556, x497, x533); let mut x559: u32 = 0; let mut x560: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x559, &mut x560, x558, x499, x535); let mut x561: u32 = 0; let mut x562: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x561, &mut x562, x560, ((x500 as u32) + (x466 as u32)), ((x536 as u32) + x502)); let mut x563: u32 = 0; let mut x564: u32 = 0; fiat_p384_mulx_u32(&mut x563, &mut x564, x6, 0x2); let mut x565: u32 = 0; let mut x566: u32 = 0; fiat_p384_mulx_u32(&mut x565, &mut x566, x6, 0xfffffffe); let mut x567: u32 = 0; let mut x568: u32 = 0; fiat_p384_mulx_u32(&mut x567, &mut x568, x6, 0x2); let mut x569: u32 = 0; let mut x570: u32 = 0; fiat_p384_mulx_u32(&mut x569, &mut x570, x6, 0xfffffffe); let mut x571: u32 = 0; let mut x572: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x571, &mut x572, 0x0, ((x564 as fiat_p384_u1) as u32), x6); let mut x573: u32 = 0; let mut x574: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x573, &mut x574, 0x0, x539, x6); let mut x575: u32 = 0; let mut x576: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x575, &mut x576, x574, x541, x569); let mut x577: u32 = 0; let mut x578: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x577, &mut x578, x576, x543, x570); let mut x579: u32 = 0; let mut x580: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x579, &mut x580, x578, x545, x567); let mut x581: u32 = 0; let mut x582: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x581, &mut x582, x580, x547, ((x568 as fiat_p384_u1) as u32)); let mut x583: u32 = 0; let mut x584: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x583, &mut x584, x582, x549, x565); let mut x585: u32 = 0; let mut x586: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x585, &mut x586, x584, x551, x566); let mut x587: u32 = 0; let mut x588: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x587, &mut x588, x586, x553, x563); let mut x589: u32 = 0; let mut x590: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x589, &mut x590, x588, x555, x571); let mut x591: u32 = 0; let mut x592: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x591, &mut x592, x590, x557, (x572 as u32)); let mut x593: u32 = 0; let mut x594: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x593, &mut x594, x592, x559, (0x0 as u32)); let mut x595: u32 = 0; let mut x596: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x595, &mut x596, x594, x561, (0x0 as u32)); let mut x597: u32 = 0; let mut x598: u32 = 0; fiat_p384_mulx_u32(&mut x597, &mut x598, x573, 0xffffffff); let mut x599: u32 = 0; let mut x600: u32 = 0; fiat_p384_mulx_u32(&mut x599, &mut x600, x573, 0xffffffff); let mut x601: u32 = 0; let mut x602: u32 = 0; fiat_p384_mulx_u32(&mut x601, &mut x602, x573, 0xffffffff); let mut x603: u32 = 0; let mut x604: u32 = 0; fiat_p384_mulx_u32(&mut x603, &mut x604, x573, 0xffffffff); let mut x605: u32 = 0; let mut x606: u32 = 0; fiat_p384_mulx_u32(&mut x605, &mut x606, x573, 0xffffffff); let mut x607: u32 = 0; let mut x608: u32 = 0; fiat_p384_mulx_u32(&mut x607, &mut x608, x573, 0xffffffff); let mut x609: u32 = 0; let mut x610: u32 = 0; fiat_p384_mulx_u32(&mut x609, &mut x610, x573, 0xffffffff); let mut x611: u32 = 0; let mut x612: u32 = 0; fiat_p384_mulx_u32(&mut x611, &mut x612, x573, 0xfffffffe); let mut x613: u32 = 0; let mut x614: u32 = 0; fiat_p384_mulx_u32(&mut x613, &mut x614, x573, 0xffffffff); let mut x615: u32 = 0; let mut x616: u32 = 0; fiat_p384_mulx_u32(&mut x615, &mut x616, x573, 0xffffffff); let mut x617: u32 = 0; let mut x618: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x617, &mut x618, 0x0, x614, x611); let mut x619: u32 = 0; let mut x620: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x619, &mut x620, x618, x612, x609); let mut x621: u32 = 0; let mut x622: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x621, &mut x622, x620, x610, x607); let mut x623: u32 = 0; let mut x624: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x623, &mut x624, x622, x608, x605); let mut x625: u32 = 0; let mut x626: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x625, &mut x626, x624, x606, x603); let mut x627: u32 = 0; let mut x628: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x627, &mut x628, x626, x604, x601); let mut x629: u32 = 0; let mut x630: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x629, &mut x630, x628, x602, x599); let mut x631: u32 = 0; let mut x632: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x631, &mut x632, x630, x600, x597); let mut x633: u32 = 0; let mut x634: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x633, &mut x634, 0x0, x573, x615); let mut x635: u32 = 0; let mut x636: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x635, &mut x636, x634, x575, x616); let mut x637: u32 = 0; let mut x638: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x637, &mut x638, x636, x577, (0x0 as u32)); let mut x639: u32 = 0; let mut x640: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x639, &mut x640, x638, x579, x613); let mut x641: u32 = 0; let mut x642: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x641, &mut x642, x640, x581, x617); let mut x643: u32 = 0; let mut x644: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x643, &mut x644, x642, x583, x619); let mut x645: u32 = 0; let mut x646: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x645, &mut x646, x644, x585, x621); let mut x647: u32 = 0; let mut x648: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x647, &mut x648, x646, x587, x623); let mut x649: u32 = 0; let mut x650: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x649, &mut x650, x648, x589, x625); let mut x651: u32 = 0; let mut x652: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x651, &mut x652, x650, x591, x627); let mut x653: u32 = 0; let mut x654: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x653, &mut x654, x652, x593, x629); let mut x655: u32 = 0; let mut x656: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x655, &mut x656, x654, x595, x631); let mut x657: u32 = 0; let mut x658: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x657, &mut x658, x656, ((x596 as u32) + (x562 as u32)), ((x632 as u32) + x598)); let mut x659: u32 = 0; let mut x660: u32 = 0; fiat_p384_mulx_u32(&mut x659, &mut x660, x7, 0x2); let mut x661: u32 = 0; let mut x662: u32 = 0; fiat_p384_mulx_u32(&mut x661, &mut x662, x7, 0xfffffffe); let mut x663: u32 = 0; let mut x664: u32 = 0; fiat_p384_mulx_u32(&mut x663, &mut x664, x7, 0x2); let mut x665: u32 = 0; let mut x666: u32 = 0; fiat_p384_mulx_u32(&mut x665, &mut x666, x7, 0xfffffffe); let mut x667: u32 = 0; let mut x668: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x667, &mut x668, 0x0, ((x660 as fiat_p384_u1) as u32), x7); let mut x669: u32 = 0; let mut x670: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x669, &mut x670, 0x0, x635, x7); let mut x671: u32 = 0; let mut x672: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x671, &mut x672, x670, x637, x665); let mut x673: u32 = 0; let mut x674: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x673, &mut x674, x672, x639, x666); let mut x675: u32 = 0; let mut x676: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x675, &mut x676, x674, x641, x663); let mut x677: u32 = 0; let mut x678: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x677, &mut x678, x676, x643, ((x664 as fiat_p384_u1) as u32)); let mut x679: u32 = 0; let mut x680: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x679, &mut x680, x678, x645, x661); let mut x681: u32 = 0; let mut x682: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x681, &mut x682, x680, x647, x662); let mut x683: u32 = 0; let mut x684: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x683, &mut x684, x682, x649, x659); let mut x685: u32 = 0; let mut x686: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x685, &mut x686, x684, x651, x667); let mut x687: u32 = 0; let mut x688: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x687, &mut x688, x686, x653, (x668 as u32)); let mut x689: u32 = 0; let mut x690: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x689, &mut x690, x688, x655, (0x0 as u32)); let mut x691: u32 = 0; let mut x692: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x691, &mut x692, x690, x657, (0x0 as u32)); let mut x693: u32 = 0; let mut x694: u32 = 0; fiat_p384_mulx_u32(&mut x693, &mut x694, x669, 0xffffffff); let mut x695: u32 = 0; let mut x696: u32 = 0; fiat_p384_mulx_u32(&mut x695, &mut x696, x669, 0xffffffff); let mut x697: u32 = 0; let mut x698: u32 = 0; fiat_p384_mulx_u32(&mut x697, &mut x698, x669, 0xffffffff); let mut x699: u32 = 0; let mut x700: u32 = 0; fiat_p384_mulx_u32(&mut x699, &mut x700, x669, 0xffffffff); let mut x701: u32 = 0; let mut x702: u32 = 0; fiat_p384_mulx_u32(&mut x701, &mut x702, x669, 0xffffffff); let mut x703: u32 = 0; let mut x704: u32 = 0; fiat_p384_mulx_u32(&mut x703, &mut x704, x669, 0xffffffff); let mut x705: u32 = 0; let mut x706: u32 = 0; fiat_p384_mulx_u32(&mut x705, &mut x706, x669, 0xffffffff); let mut x707: u32 = 0; let mut x708: u32 = 0; fiat_p384_mulx_u32(&mut x707, &mut x708, x669, 0xfffffffe); let mut x709: u32 = 0; let mut x710: u32 = 0; fiat_p384_mulx_u32(&mut x709, &mut x710, x669, 0xffffffff); let mut x711: u32 = 0; let mut x712: u32 = 0; fiat_p384_mulx_u32(&mut x711, &mut x712, x669, 0xffffffff); let mut x713: u32 = 0; let mut x714: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x713, &mut x714, 0x0, x710, x707); let mut x715: u32 = 0; let mut x716: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x715, &mut x716, x714, x708, x705); let mut x717: u32 = 0; let mut x718: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x717, &mut x718, x716, x706, x703); let mut x719: u32 = 0; let mut x720: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x719, &mut x720, x718, x704, x701); let mut x721: u32 = 0; let mut x722: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x721, &mut x722, x720, x702, x699); let mut x723: u32 = 0; let mut x724: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x723, &mut x724, x722, x700, x697); let mut x725: u32 = 0; let mut x726: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x725, &mut x726, x724, x698, x695); let mut x727: u32 = 0; let mut x728: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x727, &mut x728, x726, x696, x693); let mut x729: u32 = 0; let mut x730: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x729, &mut x730, 0x0, x669, x711); let mut x731: u32 = 0; let mut x732: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x731, &mut x732, x730, x671, x712); let mut x733: u32 = 0; let mut x734: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x733, &mut x734, x732, x673, (0x0 as u32)); let mut x735: u32 = 0; let mut x736: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x735, &mut x736, x734, x675, x709); let mut x737: u32 = 0; let mut x738: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x737, &mut x738, x736, x677, x713); let mut x739: u32 = 0; let mut x740: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x739, &mut x740, x738, x679, x715); let mut x741: u32 = 0; let mut x742: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x741, &mut x742, x740, x681, x717); let mut x743: u32 = 0; let mut x744: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x743, &mut x744, x742, x683, x719); let mut x745: u32 = 0; let mut x746: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x745, &mut x746, x744, x685, x721); let mut x747: u32 = 0; let mut x748: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x747, &mut x748, x746, x687, x723); let mut x749: u32 = 0; let mut x750: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x749, &mut x750, x748, x689, x725); let mut x751: u32 = 0; let mut x752: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x751, &mut x752, x750, x691, x727); let mut x753: u32 = 0; let mut x754: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x753, &mut x754, x752, ((x692 as u32) + (x658 as u32)), ((x728 as u32) + x694)); let mut x755: u32 = 0; let mut x756: u32 = 0; fiat_p384_mulx_u32(&mut x755, &mut x756, x8, 0x2); let mut x757: u32 = 0; let mut x758: u32 = 0; fiat_p384_mulx_u32(&mut x757, &mut x758, x8, 0xfffffffe); let mut x759: u32 = 0; let mut x760: u32 = 0; fiat_p384_mulx_u32(&mut x759, &mut x760, x8, 0x2); let mut x761: u32 = 0; let mut x762: u32 = 0; fiat_p384_mulx_u32(&mut x761, &mut x762, x8, 0xfffffffe); let mut x763: u32 = 0; let mut x764: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x763, &mut x764, 0x0, ((x756 as fiat_p384_u1) as u32), x8); let mut x765: u32 = 0; let mut x766: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x765, &mut x766, 0x0, x731, x8); let mut x767: u32 = 0; let mut x768: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x767, &mut x768, x766, x733, x761); let mut x769: u32 = 0; let mut x770: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x769, &mut x770, x768, x735, x762); let mut x771: u32 = 0; let mut x772: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x771, &mut x772, x770, x737, x759); let mut x773: u32 = 0; let mut x774: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x773, &mut x774, x772, x739, ((x760 as fiat_p384_u1) as u32)); let mut x775: u32 = 0; let mut x776: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x775, &mut x776, x774, x741, x757); let mut x777: u32 = 0; let mut x778: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x777, &mut x778, x776, x743, x758); let mut x779: u32 = 0; let mut x780: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x779, &mut x780, x778, x745, x755); let mut x781: u32 = 0; let mut x782: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x781, &mut x782, x780, x747, x763); let mut x783: u32 = 0; let mut x784: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x783, &mut x784, x782, x749, (x764 as u32)); let mut x785: u32 = 0; let mut x786: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x785, &mut x786, x784, x751, (0x0 as u32)); let mut x787: u32 = 0; let mut x788: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x787, &mut x788, x786, x753, (0x0 as u32)); let mut x789: u32 = 0; let mut x790: u32 = 0; fiat_p384_mulx_u32(&mut x789, &mut x790, x765, 0xffffffff); let mut x791: u32 = 0; let mut x792: u32 = 0; fiat_p384_mulx_u32(&mut x791, &mut x792, x765, 0xffffffff); let mut x793: u32 = 0; let mut x794: u32 = 0; fiat_p384_mulx_u32(&mut x793, &mut x794, x765, 0xffffffff); let mut x795: u32 = 0; let mut x796: u32 = 0; fiat_p384_mulx_u32(&mut x795, &mut x796, x765, 0xffffffff); let mut x797: u32 = 0; let mut x798: u32 = 0; fiat_p384_mulx_u32(&mut x797, &mut x798, x765, 0xffffffff); let mut x799: u32 = 0; let mut x800: u32 = 0; fiat_p384_mulx_u32(&mut x799, &mut x800, x765, 0xffffffff); let mut x801: u32 = 0; let mut x802: u32 = 0; fiat_p384_mulx_u32(&mut x801, &mut x802, x765, 0xffffffff); let mut x803: u32 = 0; let mut x804: u32 = 0; fiat_p384_mulx_u32(&mut x803, &mut x804, x765, 0xfffffffe); let mut x805: u32 = 0; let mut x806: u32 = 0; fiat_p384_mulx_u32(&mut x805, &mut x806, x765, 0xffffffff); let mut x807: u32 = 0; let mut x808: u32 = 0; fiat_p384_mulx_u32(&mut x807, &mut x808, x765, 0xffffffff); let mut x809: u32 = 0; let mut x810: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x809, &mut x810, 0x0, x806, x803); let mut x811: u32 = 0; let mut x812: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x811, &mut x812, x810, x804, x801); let mut x813: u32 = 0; let mut x814: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x813, &mut x814, x812, x802, x799); let mut x815: u32 = 0; let mut x816: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x815, &mut x816, x814, x800, x797); let mut x817: u32 = 0; let mut x818: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x817, &mut x818, x816, x798, x795); let mut x819: u32 = 0; let mut x820: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x819, &mut x820, x818, x796, x793); let mut x821: u32 = 0; let mut x822: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x821, &mut x822, x820, x794, x791); let mut x823: u32 = 0; let mut x824: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x823, &mut x824, x822, x792, x789); let mut x825: u32 = 0; let mut x826: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x825, &mut x826, 0x0, x765, x807); let mut x827: u32 = 0; let mut x828: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x827, &mut x828, x826, x767, x808); let mut x829: u32 = 0; let mut x830: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x829, &mut x830, x828, x769, (0x0 as u32)); let mut x831: u32 = 0; let mut x832: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x831, &mut x832, x830, x771, x805); let mut x833: u32 = 0; let mut x834: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x833, &mut x834, x832, x773, x809); let mut x835: u32 = 0; let mut x836: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x835, &mut x836, x834, x775, x811); let mut x837: u32 = 0; let mut x838: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x837, &mut x838, x836, x777, x813); let mut x839: u32 = 0; let mut x840: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x839, &mut x840, x838, x779, x815); let mut x841: u32 = 0; let mut x842: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x841, &mut x842, x840, x781, x817); let mut x843: u32 = 0; let mut x844: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x843, &mut x844, x842, x783, x819); let mut x845: u32 = 0; let mut x846: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x845, &mut x846, x844, x785, x821); let mut x847: u32 = 0; let mut x848: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x847, &mut x848, x846, x787, x823); let mut x849: u32 = 0; let mut x850: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x849, &mut x850, x848, ((x788 as u32) + (x754 as u32)), ((x824 as u32) + x790)); let mut x851: u32 = 0; let mut x852: u32 = 0; fiat_p384_mulx_u32(&mut x851, &mut x852, x9, 0x2); let mut x853: u32 = 0; let mut x854: u32 = 0; fiat_p384_mulx_u32(&mut x853, &mut x854, x9, 0xfffffffe); let mut x855: u32 = 0; let mut x856: u32 = 0; fiat_p384_mulx_u32(&mut x855, &mut x856, x9, 0x2); let mut x857: u32 = 0; let mut x858: u32 = 0; fiat_p384_mulx_u32(&mut x857, &mut x858, x9, 0xfffffffe); let mut x859: u32 = 0; let mut x860: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x859, &mut x860, 0x0, ((x852 as fiat_p384_u1) as u32), x9); let mut x861: u32 = 0; let mut x862: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x861, &mut x862, 0x0, x827, x9); let mut x863: u32 = 0; let mut x864: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x863, &mut x864, x862, x829, x857); let mut x865: u32 = 0; let mut x866: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x865, &mut x866, x864, x831, x858); let mut x867: u32 = 0; let mut x868: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x867, &mut x868, x866, x833, x855); let mut x869: u32 = 0; let mut x870: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x869, &mut x870, x868, x835, ((x856 as fiat_p384_u1) as u32)); let mut x871: u32 = 0; let mut x872: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x871, &mut x872, x870, x837, x853); let mut x873: u32 = 0; let mut x874: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x873, &mut x874, x872, x839, x854); let mut x875: u32 = 0; let mut x876: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x875, &mut x876, x874, x841, x851); let mut x877: u32 = 0; let mut x878: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x877, &mut x878, x876, x843, x859); let mut x879: u32 = 0; let mut x880: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x879, &mut x880, x878, x845, (x860 as u32)); let mut x881: u32 = 0; let mut x882: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x881, &mut x882, x880, x847, (0x0 as u32)); let mut x883: u32 = 0; let mut x884: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x883, &mut x884, x882, x849, (0x0 as u32)); let mut x885: u32 = 0; let mut x886: u32 = 0; fiat_p384_mulx_u32(&mut x885, &mut x886, x861, 0xffffffff); let mut x887: u32 = 0; let mut x888: u32 = 0; fiat_p384_mulx_u32(&mut x887, &mut x888, x861, 0xffffffff); let mut x889: u32 = 0; let mut x890: u32 = 0; fiat_p384_mulx_u32(&mut x889, &mut x890, x861, 0xffffffff); let mut x891: u32 = 0; let mut x892: u32 = 0; fiat_p384_mulx_u32(&mut x891, &mut x892, x861, 0xffffffff); let mut x893: u32 = 0; let mut x894: u32 = 0; fiat_p384_mulx_u32(&mut x893, &mut x894, x861, 0xffffffff); let mut x895: u32 = 0; let mut x896: u32 = 0; fiat_p384_mulx_u32(&mut x895, &mut x896, x861, 0xffffffff); let mut x897: u32 = 0; let mut x898: u32 = 0; fiat_p384_mulx_u32(&mut x897, &mut x898, x861, 0xffffffff); let mut x899: u32 = 0; let mut x900: u32 = 0; fiat_p384_mulx_u32(&mut x899, &mut x900, x861, 0xfffffffe); let mut x901: u32 = 0; let mut x902: u32 = 0; fiat_p384_mulx_u32(&mut x901, &mut x902, x861, 0xffffffff); let mut x903: u32 = 0; let mut x904: u32 = 0; fiat_p384_mulx_u32(&mut x903, &mut x904, x861, 0xffffffff); let mut x905: u32 = 0; let mut x906: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x905, &mut x906, 0x0, x902, x899); let mut x907: u32 = 0; let mut x908: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x907, &mut x908, x906, x900, x897); let mut x909: u32 = 0; let mut x910: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x909, &mut x910, x908, x898, x895); let mut x911: u32 = 0; let mut x912: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x911, &mut x912, x910, x896, x893); let mut x913: u32 = 0; let mut x914: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x913, &mut x914, x912, x894, x891); let mut x915: u32 = 0; let mut x916: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x915, &mut x916, x914, x892, x889); let mut x917: u32 = 0; let mut x918: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x917, &mut x918, x916, x890, x887); let mut x919: u32 = 0; let mut x920: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x919, &mut x920, x918, x888, x885); let mut x921: u32 = 0; let mut x922: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x921, &mut x922, 0x0, x861, x903); let mut x923: u32 = 0; let mut x924: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x923, &mut x924, x922, x863, x904); let mut x925: u32 = 0; let mut x926: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x925, &mut x926, x924, x865, (0x0 as u32)); let mut x927: u32 = 0; let mut x928: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x927, &mut x928, x926, x867, x901); let mut x929: u32 = 0; let mut x930: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x929, &mut x930, x928, x869, x905); let mut x931: u32 = 0; let mut x932: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x931, &mut x932, x930, x871, x907); let mut x933: u32 = 0; let mut x934: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x933, &mut x934, x932, x873, x909); let mut x935: u32 = 0; let mut x936: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x935, &mut x936, x934, x875, x911); let mut x937: u32 = 0; let mut x938: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x937, &mut x938, x936, x877, x913); let mut x939: u32 = 0; let mut x940: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x939, &mut x940, x938, x879, x915); let mut x941: u32 = 0; let mut x942: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x941, &mut x942, x940, x881, x917); let mut x943: u32 = 0; let mut x944: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x943, &mut x944, x942, x883, x919); let mut x945: u32 = 0; let mut x946: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x945, &mut x946, x944, ((x884 as u32) + (x850 as u32)), ((x920 as u32) + x886)); let mut x947: u32 = 0; let mut x948: u32 = 0; fiat_p384_mulx_u32(&mut x947, &mut x948, x10, 0x2); let mut x949: u32 = 0; let mut x950: u32 = 0; fiat_p384_mulx_u32(&mut x949, &mut x950, x10, 0xfffffffe); let mut x951: u32 = 0; let mut x952: u32 = 0; fiat_p384_mulx_u32(&mut x951, &mut x952, x10, 0x2); let mut x953: u32 = 0; let mut x954: u32 = 0; fiat_p384_mulx_u32(&mut x953, &mut x954, x10, 0xfffffffe); let mut x955: u32 = 0; let mut x956: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x955, &mut x956, 0x0, ((x948 as fiat_p384_u1) as u32), x10); let mut x957: u32 = 0; let mut x958: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x957, &mut x958, 0x0, x923, x10); let mut x959: u32 = 0; let mut x960: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x959, &mut x960, x958, x925, x953); let mut x961: u32 = 0; let mut x962: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x961, &mut x962, x960, x927, x954); let mut x963: u32 = 0; let mut x964: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x963, &mut x964, x962, x929, x951); let mut x965: u32 = 0; let mut x966: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x965, &mut x966, x964, x931, ((x952 as fiat_p384_u1) as u32)); let mut x967: u32 = 0; let mut x968: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x967, &mut x968, x966, x933, x949); let mut x969: u32 = 0; let mut x970: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x969, &mut x970, x968, x935, x950); let mut x971: u32 = 0; let mut x972: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x971, &mut x972, x970, x937, x947); let mut x973: u32 = 0; let mut x974: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x973, &mut x974, x972, x939, x955); let mut x975: u32 = 0; let mut x976: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x975, &mut x976, x974, x941, (x956 as u32)); let mut x977: u32 = 0; let mut x978: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x977, &mut x978, x976, x943, (0x0 as u32)); let mut x979: u32 = 0; let mut x980: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x979, &mut x980, x978, x945, (0x0 as u32)); let mut x981: u32 = 0; let mut x982: u32 = 0; fiat_p384_mulx_u32(&mut x981, &mut x982, x957, 0xffffffff); let mut x983: u32 = 0; let mut x984: u32 = 0; fiat_p384_mulx_u32(&mut x983, &mut x984, x957, 0xffffffff); let mut x985: u32 = 0; let mut x986: u32 = 0; fiat_p384_mulx_u32(&mut x985, &mut x986, x957, 0xffffffff); let mut x987: u32 = 0; let mut x988: u32 = 0; fiat_p384_mulx_u32(&mut x987, &mut x988, x957, 0xffffffff); let mut x989: u32 = 0; let mut x990: u32 = 0; fiat_p384_mulx_u32(&mut x989, &mut x990, x957, 0xffffffff); let mut x991: u32 = 0; let mut x992: u32 = 0; fiat_p384_mulx_u32(&mut x991, &mut x992, x957, 0xffffffff); let mut x993: u32 = 0; let mut x994: u32 = 0; fiat_p384_mulx_u32(&mut x993, &mut x994, x957, 0xffffffff); let mut x995: u32 = 0; let mut x996: u32 = 0; fiat_p384_mulx_u32(&mut x995, &mut x996, x957, 0xfffffffe); let mut x997: u32 = 0; let mut x998: u32 = 0; fiat_p384_mulx_u32(&mut x997, &mut x998, x957, 0xffffffff); let mut x999: u32 = 0; let mut x1000: u32 = 0; fiat_p384_mulx_u32(&mut x999, &mut x1000, x957, 0xffffffff); let mut x1001: u32 = 0; let mut x1002: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1001, &mut x1002, 0x0, x998, x995); let mut x1003: u32 = 0; let mut x1004: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1003, &mut x1004, x1002, x996, x993); let mut x1005: u32 = 0; let mut x1006: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1005, &mut x1006, x1004, x994, x991); let mut x1007: u32 = 0; let mut x1008: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1007, &mut x1008, x1006, x992, x989); let mut x1009: u32 = 0; let mut x1010: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1009, &mut x1010, x1008, x990, x987); let mut x1011: u32 = 0; let mut x1012: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1011, &mut x1012, x1010, x988, x985); let mut x1013: u32 = 0; let mut x1014: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1013, &mut x1014, x1012, x986, x983); let mut x1015: u32 = 0; let mut x1016: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1015, &mut x1016, x1014, x984, x981); let mut x1017: u32 = 0; let mut x1018: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1017, &mut x1018, 0x0, x957, x999); let mut x1019: u32 = 0; let mut x1020: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1019, &mut x1020, x1018, x959, x1000); let mut x1021: u32 = 0; let mut x1022: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1021, &mut x1022, x1020, x961, (0x0 as u32)); let mut x1023: u32 = 0; let mut x1024: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1023, &mut x1024, x1022, x963, x997); let mut x1025: u32 = 0; let mut x1026: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1025, &mut x1026, x1024, x965, x1001); let mut x1027: u32 = 0; let mut x1028: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1027, &mut x1028, x1026, x967, x1003); let mut x1029: u32 = 0; let mut x1030: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1029, &mut x1030, x1028, x969, x1005); let mut x1031: u32 = 0; let mut x1032: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1031, &mut x1032, x1030, x971, x1007); let mut x1033: u32 = 0; let mut x1034: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1033, &mut x1034, x1032, x973, x1009); let mut x1035: u32 = 0; let mut x1036: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1035, &mut x1036, x1034, x975, x1011); let mut x1037: u32 = 0; let mut x1038: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1037, &mut x1038, x1036, x977, x1013); let mut x1039: u32 = 0; let mut x1040: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1039, &mut x1040, x1038, x979, x1015); let mut x1041: u32 = 0; let mut x1042: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1041, &mut x1042, x1040, ((x980 as u32) + (x946 as u32)), ((x1016 as u32) + x982)); let mut x1043: u32 = 0; let mut x1044: u32 = 0; fiat_p384_mulx_u32(&mut x1043, &mut x1044, x11, 0x2); let mut x1045: u32 = 0; let mut x1046: u32 = 0; fiat_p384_mulx_u32(&mut x1045, &mut x1046, x11, 0xfffffffe); let mut x1047: u32 = 0; let mut x1048: u32 = 0; fiat_p384_mulx_u32(&mut x1047, &mut x1048, x11, 0x2); let mut x1049: u32 = 0; let mut x1050: u32 = 0; fiat_p384_mulx_u32(&mut x1049, &mut x1050, x11, 0xfffffffe); let mut x1051: u32 = 0; let mut x1052: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1051, &mut x1052, 0x0, ((x1044 as fiat_p384_u1) as u32), x11); let mut x1053: u32 = 0; let mut x1054: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1053, &mut x1054, 0x0, x1019, x11); let mut x1055: u32 = 0; let mut x1056: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1055, &mut x1056, x1054, x1021, x1049); let mut x1057: u32 = 0; let mut x1058: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1057, &mut x1058, x1056, x1023, x1050); let mut x1059: u32 = 0; let mut x1060: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1059, &mut x1060, x1058, x1025, x1047); let mut x1061: u32 = 0; let mut x1062: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1061, &mut x1062, x1060, x1027, ((x1048 as fiat_p384_u1) as u32)); let mut x1063: u32 = 0; let mut x1064: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1063, &mut x1064, x1062, x1029, x1045); let mut x1065: u32 = 0; let mut x1066: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1065, &mut x1066, x1064, x1031, x1046); let mut x1067: u32 = 0; let mut x1068: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1067, &mut x1068, x1066, x1033, x1043); let mut x1069: u32 = 0; let mut x1070: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1069, &mut x1070, x1068, x1035, x1051); let mut x1071: u32 = 0; let mut x1072: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1071, &mut x1072, x1070, x1037, (x1052 as u32)); let mut x1073: u32 = 0; let mut x1074: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1073, &mut x1074, x1072, x1039, (0x0 as u32)); let mut x1075: u32 = 0; let mut x1076: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1075, &mut x1076, x1074, x1041, (0x0 as u32)); let mut x1077: u32 = 0; let mut x1078: u32 = 0; fiat_p384_mulx_u32(&mut x1077, &mut x1078, x1053, 0xffffffff); let mut x1079: u32 = 0; let mut x1080: u32 = 0; fiat_p384_mulx_u32(&mut x1079, &mut x1080, x1053, 0xffffffff); let mut x1081: u32 = 0; let mut x1082: u32 = 0; fiat_p384_mulx_u32(&mut x1081, &mut x1082, x1053, 0xffffffff); let mut x1083: u32 = 0; let mut x1084: u32 = 0; fiat_p384_mulx_u32(&mut x1083, &mut x1084, x1053, 0xffffffff); let mut x1085: u32 = 0; let mut x1086: u32 = 0; fiat_p384_mulx_u32(&mut x1085, &mut x1086, x1053, 0xffffffff); let mut x1087: u32 = 0; let mut x1088: u32 = 0; fiat_p384_mulx_u32(&mut x1087, &mut x1088, x1053, 0xffffffff); let mut x1089: u32 = 0; let mut x1090: u32 = 0; fiat_p384_mulx_u32(&mut x1089, &mut x1090, x1053, 0xffffffff); let mut x1091: u32 = 0; let mut x1092: u32 = 0; fiat_p384_mulx_u32(&mut x1091, &mut x1092, x1053, 0xfffffffe); let mut x1093: u32 = 0; let mut x1094: u32 = 0; fiat_p384_mulx_u32(&mut x1093, &mut x1094, x1053, 0xffffffff); let mut x1095: u32 = 0; let mut x1096: u32 = 0; fiat_p384_mulx_u32(&mut x1095, &mut x1096, x1053, 0xffffffff); let mut x1097: u32 = 0; let mut x1098: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1097, &mut x1098, 0x0, x1094, x1091); let mut x1099: u32 = 0; let mut x1100: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1099, &mut x1100, x1098, x1092, x1089); let mut x1101: u32 = 0; let mut x1102: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1101, &mut x1102, x1100, x1090, x1087); let mut x1103: u32 = 0; let mut x1104: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1103, &mut x1104, x1102, x1088, x1085); let mut x1105: u32 = 0; let mut x1106: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1105, &mut x1106, x1104, x1086, x1083); let mut x1107: u32 = 0; let mut x1108: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1107, &mut x1108, x1106, x1084, x1081); let mut x1109: u32 = 0; let mut x1110: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1109, &mut x1110, x1108, x1082, x1079); let mut x1111: u32 = 0; let mut x1112: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1111, &mut x1112, x1110, x1080, x1077); let mut x1113: u32 = 0; let mut x1114: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1113, &mut x1114, 0x0, x1053, x1095); let mut x1115: u32 = 0; let mut x1116: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1115, &mut x1116, x1114, x1055, x1096); let mut x1117: u32 = 0; let mut x1118: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1117, &mut x1118, x1116, x1057, (0x0 as u32)); let mut x1119: u32 = 0; let mut x1120: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1119, &mut x1120, x1118, x1059, x1093); let mut x1121: u32 = 0; let mut x1122: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1121, &mut x1122, x1120, x1061, x1097); let mut x1123: u32 = 0; let mut x1124: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1123, &mut x1124, x1122, x1063, x1099); let mut x1125: u32 = 0; let mut x1126: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1125, &mut x1126, x1124, x1065, x1101); let mut x1127: u32 = 0; let mut x1128: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1127, &mut x1128, x1126, x1067, x1103); let mut x1129: u32 = 0; let mut x1130: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1129, &mut x1130, x1128, x1069, x1105); let mut x1131: u32 = 0; let mut x1132: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1131, &mut x1132, x1130, x1071, x1107); let mut x1133: u32 = 0; let mut x1134: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1133, &mut x1134, x1132, x1073, x1109); let mut x1135: u32 = 0; let mut x1136: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1135, &mut x1136, x1134, x1075, x1111); let mut x1137: u32 = 0; let mut x1138: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1137, &mut x1138, x1136, ((x1076 as u32) + (x1042 as u32)), ((x1112 as u32) + x1078)); let mut x1139: u32 = 0; let mut x1140: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1139, &mut x1140, 0x0, x1115, 0xffffffff); let mut x1141: u32 = 0; let mut x1142: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1141, &mut x1142, x1140, x1117, (0x0 as u32)); let mut x1143: u32 = 0; let mut x1144: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1143, &mut x1144, x1142, x1119, (0x0 as u32)); let mut x1145: u32 = 0; let mut x1146: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1145, &mut x1146, x1144, x1121, 0xffffffff); let mut x1147: u32 = 0; let mut x1148: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1147, &mut x1148, x1146, x1123, 0xfffffffe); let mut x1149: u32 = 0; let mut x1150: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1149, &mut x1150, x1148, x1125, 0xffffffff); let mut x1151: u32 = 0; let mut x1152: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1151, &mut x1152, x1150, x1127, 0xffffffff); let mut x1153: u32 = 0; let mut x1154: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1153, &mut x1154, x1152, x1129, 0xffffffff); let mut x1155: u32 = 0; let mut x1156: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1155, &mut x1156, x1154, x1131, 0xffffffff); let mut x1157: u32 = 0; let mut x1158: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1157, &mut x1158, x1156, x1133, 0xffffffff); let mut x1159: u32 = 0; let mut x1160: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1159, &mut x1160, x1158, x1135, 0xffffffff); let mut x1161: u32 = 0; let mut x1162: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1161, &mut x1162, x1160, x1137, 0xffffffff); let mut x1163: u32 = 0; let mut x1164: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x1163, &mut x1164, x1162, (x1138 as u32), (0x0 as u32)); let mut x1165: u32 = 0; fiat_p384_cmovznz_u32(&mut x1165, x1164, x1139, x1115); let mut x1166: u32 = 0; fiat_p384_cmovznz_u32(&mut x1166, x1164, x1141, x1117); let mut x1167: u32 = 0; fiat_p384_cmovznz_u32(&mut x1167, x1164, x1143, x1119); let mut x1168: u32 = 0; fiat_p384_cmovznz_u32(&mut x1168, x1164, x1145, x1121); let mut x1169: u32 = 0; fiat_p384_cmovznz_u32(&mut x1169, x1164, x1147, x1123); let mut x1170: u32 = 0; fiat_p384_cmovznz_u32(&mut x1170, x1164, x1149, x1125); let mut x1171: u32 = 0; fiat_p384_cmovznz_u32(&mut x1171, x1164, x1151, x1127); let mut x1172: u32 = 0; fiat_p384_cmovznz_u32(&mut x1172, x1164, x1153, x1129); let mut x1173: u32 = 0; fiat_p384_cmovznz_u32(&mut x1173, x1164, x1155, x1131); let mut x1174: u32 = 0; fiat_p384_cmovznz_u32(&mut x1174, x1164, x1157, x1133); let mut x1175: u32 = 0; fiat_p384_cmovznz_u32(&mut x1175, x1164, x1159, x1135); let mut x1176: u32 = 0; fiat_p384_cmovznz_u32(&mut x1176, x1164, x1161, x1137); out1[0] = x1165; out1[1] = x1166; out1[2] = x1167; out1[3] = x1168; out1[4] = x1169; out1[5] = x1170; out1[6] = x1171; out1[7] = x1172; out1[8] = x1173; out1[9] = x1174; out1[10] = x1175; out1[11] = x1176; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] #[inline] pub fn fiat_p384_nonzero(out1: &mut u32, arg1: &[u32; 12]) -> () { let x1: u32 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | ((arg1[6]) | ((arg1[7]) | ((arg1[8]) | ((arg1[9]) | ((arg1[10]) | (arg1[11])))))))))))); *out1 = x1; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_selectznz(out1: &mut [u32; 12], arg1: fiat_p384_u1, arg2: &[u32; 12], arg3: &[u32; 12]) -> () { let mut x1: u32 = 0; fiat_p384_cmovznz_u32(&mut x1, arg1, (arg2[0]), (arg3[0])); let mut x2: u32 = 0; fiat_p384_cmovznz_u32(&mut x2, arg1, (arg2[1]), (arg3[1])); let mut x3: u32 = 0; fiat_p384_cmovznz_u32(&mut x3, arg1, (arg2[2]), (arg3[2])); let mut x4: u32 = 0; fiat_p384_cmovznz_u32(&mut x4, arg1, (arg2[3]), (arg3[3])); let mut x5: u32 = 0; fiat_p384_cmovznz_u32(&mut x5, arg1, (arg2[4]), (arg3[4])); let mut x6: u32 = 0; fiat_p384_cmovznz_u32(&mut x6, arg1, (arg2[5]), (arg3[5])); let mut x7: u32 = 0; fiat_p384_cmovznz_u32(&mut x7, arg1, (arg2[6]), (arg3[6])); let mut x8: u32 = 0; fiat_p384_cmovznz_u32(&mut x8, arg1, (arg2[7]), (arg3[7])); let mut x9: u32 = 0; fiat_p384_cmovznz_u32(&mut x9, arg1, (arg2[8]), (arg3[8])); let mut x10: u32 = 0; fiat_p384_cmovznz_u32(&mut x10, arg1, (arg2[9]), (arg3[9])); let mut x11: u32 = 0; fiat_p384_cmovznz_u32(&mut x11, arg1, (arg2[10]), (arg3[10])); let mut x12: u32 = 0; fiat_p384_cmovznz_u32(&mut x12, arg1, (arg2[11]), (arg3[11])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; out1[7] = x8; out1[8] = x9; out1[9] = x10; out1[10] = x11; out1[11] = x12; } /// The function fiat_p384_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..47] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// 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]] #[inline] pub fn fiat_p384_to_bytes(out1: &mut [u8; 48], arg1: &[u32; 12]) -> () { let x1: u32 = (arg1[11]); let x2: u32 = (arg1[10]); let x3: u32 = (arg1[9]); let x4: u32 = (arg1[8]); let x5: u32 = (arg1[7]); let x6: u32 = (arg1[6]); let x7: u32 = (arg1[5]); let x8: u32 = (arg1[4]); let x9: u32 = (arg1[3]); let x10: u32 = (arg1[2]); let x11: u32 = (arg1[1]); let x12: u32 = (arg1[0]); let x13: u8 = ((x12 & (0xff as u32)) as u8); let x14: u32 = (x12 >> 8); let x15: u8 = ((x14 & (0xff as u32)) as u8); let x16: u32 = (x14 >> 8); let x17: u8 = ((x16 & (0xff as u32)) as u8); let x18: u8 = ((x16 >> 8) as u8); let x19: u8 = ((x11 & (0xff as u32)) as u8); let x20: u32 = (x11 >> 8); let x21: u8 = ((x20 & (0xff as u32)) as u8); let x22: u32 = (x20 >> 8); let x23: u8 = ((x22 & (0xff as u32)) as u8); let x24: u8 = ((x22 >> 8) as u8); let x25: u8 = ((x10 & (0xff as u32)) as u8); let x26: u32 = (x10 >> 8); let x27: u8 = ((x26 & (0xff as u32)) as u8); let x28: u32 = (x26 >> 8); let x29: u8 = ((x28 & (0xff as u32)) as u8); let x30: u8 = ((x28 >> 8) as u8); let x31: u8 = ((x9 & (0xff as u32)) as u8); let x32: u32 = (x9 >> 8); let x33: u8 = ((x32 & (0xff as u32)) as u8); let x34: u32 = (x32 >> 8); let x35: u8 = ((x34 & (0xff as u32)) as u8); let x36: u8 = ((x34 >> 8) as u8); let x37: u8 = ((x8 & (0xff as u32)) as u8); let x38: u32 = (x8 >> 8); let x39: u8 = ((x38 & (0xff as u32)) as u8); let x40: u32 = (x38 >> 8); let x41: u8 = ((x40 & (0xff as u32)) as u8); let x42: u8 = ((x40 >> 8) as u8); let x43: u8 = ((x7 & (0xff as u32)) as u8); let x44: u32 = (x7 >> 8); let x45: u8 = ((x44 & (0xff as u32)) as u8); let x46: u32 = (x44 >> 8); let x47: u8 = ((x46 & (0xff as u32)) as u8); let x48: u8 = ((x46 >> 8) as u8); let x49: u8 = ((x6 & (0xff as u32)) as u8); let x50: u32 = (x6 >> 8); let x51: u8 = ((x50 & (0xff as u32)) as u8); let x52: u32 = (x50 >> 8); let x53: u8 = ((x52 & (0xff as u32)) as u8); let x54: u8 = ((x52 >> 8) as u8); let x55: u8 = ((x5 & (0xff as u32)) as u8); let x56: u32 = (x5 >> 8); let x57: u8 = ((x56 & (0xff as u32)) as u8); let x58: u32 = (x56 >> 8); let x59: u8 = ((x58 & (0xff as u32)) as u8); let x60: u8 = ((x58 >> 8) as u8); let x61: u8 = ((x4 & (0xff as u32)) as u8); let x62: u32 = (x4 >> 8); let x63: u8 = ((x62 & (0xff as u32)) as u8); let x64: u32 = (x62 >> 8); let x65: u8 = ((x64 & (0xff as u32)) as u8); let x66: u8 = ((x64 >> 8) as u8); let x67: u8 = ((x3 & (0xff as u32)) as u8); let x68: u32 = (x3 >> 8); let x69: u8 = ((x68 & (0xff as u32)) as u8); let x70: u32 = (x68 >> 8); let x71: u8 = ((x70 & (0xff as u32)) as u8); let x72: u8 = ((x70 >> 8) as u8); let x73: u8 = ((x2 & (0xff as u32)) as u8); let x74: u32 = (x2 >> 8); let x75: u8 = ((x74 & (0xff as u32)) as u8); let x76: u32 = (x74 >> 8); let x77: u8 = ((x76 & (0xff as u32)) as u8); let x78: u8 = ((x76 >> 8) as u8); let x79: u8 = ((x1 & (0xff as u32)) as u8); let x80: u32 = (x1 >> 8); let x81: u8 = ((x80 & (0xff as u32)) as u8); let x82: u32 = (x80 >> 8); let x83: u8 = ((x82 & (0xff as u32)) as u8); let x84: u8 = ((x82 >> 8) as u8); out1[0] = x13; out1[1] = x15; out1[2] = x17; out1[3] = x18; out1[4] = x19; out1[5] = x21; out1[6] = x23; out1[7] = x24; out1[8] = x25; out1[9] = x27; out1[10] = x29; out1[11] = x30; out1[12] = x31; out1[13] = x33; out1[14] = x35; out1[15] = x36; out1[16] = x37; out1[17] = x39; out1[18] = x41; out1[19] = x42; out1[20] = x43; out1[21] = x45; out1[22] = x47; out1[23] = x48; out1[24] = x49; out1[25] = x51; out1[26] = x53; out1[27] = x54; out1[28] = x55; out1[29] = x57; out1[30] = x59; out1[31] = x60; out1[32] = x61; out1[33] = x63; out1[34] = x65; out1[35] = x66; out1[36] = x67; out1[37] = x69; out1[38] = x71; out1[39] = x72; out1[40] = x73; out1[41] = x75; out1[42] = x77; out1[43] = x78; out1[44] = x79; out1[45] = x81; out1[46] = x83; out1[47] = x84; } /// The function fiat_p384_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]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_from_bytes(out1: &mut [u32; 12], arg1: &[u8; 48]) -> () { let x1: u32 = (((arg1[47]) as u32) << 24); let x2: u32 = (((arg1[46]) as u32) << 16); let x3: u32 = (((arg1[45]) as u32) << 8); let x4: u8 = (arg1[44]); let x5: u32 = (((arg1[43]) as u32) << 24); let x6: u32 = (((arg1[42]) as u32) << 16); let x7: u32 = (((arg1[41]) as u32) << 8); let x8: u8 = (arg1[40]); let x9: u32 = (((arg1[39]) as u32) << 24); let x10: u32 = (((arg1[38]) as u32) << 16); let x11: u32 = (((arg1[37]) as u32) << 8); let x12: u8 = (arg1[36]); let x13: u32 = (((arg1[35]) as u32) << 24); let x14: u32 = (((arg1[34]) as u32) << 16); let x15: u32 = (((arg1[33]) as u32) << 8); let x16: u8 = (arg1[32]); let x17: u32 = (((arg1[31]) as u32) << 24); let x18: u32 = (((arg1[30]) as u32) << 16); let x19: u32 = (((arg1[29]) as u32) << 8); let x20: u8 = (arg1[28]); let x21: u32 = (((arg1[27]) as u32) << 24); let x22: u32 = (((arg1[26]) as u32) << 16); let x23: u32 = (((arg1[25]) as u32) << 8); let x24: u8 = (arg1[24]); let x25: u32 = (((arg1[23]) as u32) << 24); let x26: u32 = (((arg1[22]) as u32) << 16); let x27: u32 = (((arg1[21]) as u32) << 8); let x28: u8 = (arg1[20]); let x29: u32 = (((arg1[19]) as u32) << 24); let x30: u32 = (((arg1[18]) as u32) << 16); let x31: u32 = (((arg1[17]) as u32) << 8); let x32: u8 = (arg1[16]); let x33: u32 = (((arg1[15]) as u32) << 24); let x34: u32 = (((arg1[14]) as u32) << 16); let x35: u32 = (((arg1[13]) as u32) << 8); let x36: u8 = (arg1[12]); let x37: u32 = (((arg1[11]) as u32) << 24); let x38: u32 = (((arg1[10]) as u32) << 16); let x39: u32 = (((arg1[9]) as u32) << 8); let x40: u8 = (arg1[8]); let x41: u32 = (((arg1[7]) as u32) << 24); let x42: u32 = (((arg1[6]) as u32) << 16); let x43: u32 = (((arg1[5]) as u32) << 8); let x44: u8 = (arg1[4]); let x45: u32 = (((arg1[3]) as u32) << 24); let x46: u32 = (((arg1[2]) as u32) << 16); let x47: u32 = (((arg1[1]) as u32) << 8); let x48: u8 = (arg1[0]); let x49: u32 = (x47 + (x48 as u32)); let x50: u32 = (x46 + x49); let x51: u32 = (x45 + x50); let x52: u32 = (x43 + (x44 as u32)); let x53: u32 = (x42 + x52); let x54: u32 = (x41 + x53); let x55: u32 = (x39 + (x40 as u32)); let x56: u32 = (x38 + x55); let x57: u32 = (x37 + x56); let x58: u32 = (x35 + (x36 as u32)); let x59: u32 = (x34 + x58); let x60: u32 = (x33 + x59); let x61: u32 = (x31 + (x32 as u32)); let x62: u32 = (x30 + x61); let x63: u32 = (x29 + x62); let x64: u32 = (x27 + (x28 as u32)); let x65: u32 = (x26 + x64); let x66: u32 = (x25 + x65); let x67: u32 = (x23 + (x24 as u32)); let x68: u32 = (x22 + x67); let x69: u32 = (x21 + x68); let x70: u32 = (x19 + (x20 as u32)); let x71: u32 = (x18 + x70); let x72: u32 = (x17 + x71); let x73: u32 = (x15 + (x16 as u32)); let x74: u32 = (x14 + x73); let x75: u32 = (x13 + x74); let x76: u32 = (x11 + (x12 as u32)); let x77: u32 = (x10 + x76); let x78: u32 = (x9 + x77); let x79: u32 = (x7 + (x8 as u32)); let x80: u32 = (x6 + x79); let x81: u32 = (x5 + x80); let x82: u32 = (x3 + (x4 as u32)); let x83: u32 = (x2 + x82); let x84: u32 = (x1 + x83); out1[0] = x51; out1[1] = x54; out1[2] = x57; out1[3] = x60; out1[4] = x63; out1[5] = x66; out1[6] = x69; out1[7] = x72; out1[8] = x75; out1[9] = x78; out1[10] = x81; out1[11] = x84; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_set_one(out1: &mut [u32; 12]) -> () { out1[0] = (0x1 as u32); out1[1] = 0xffffffff; out1[2] = 0xffffffff; out1[3] = (0x0 as u32); out1[4] = (0x1 as u32); out1[5] = (0x0 as u32); out1[6] = (0x0 as u32); out1[7] = (0x0 as u32); out1[8] = (0x0 as u32); out1[9] = (0x0 as u32); out1[10] = (0x0 as u32); out1[11] = (0x0 as u32); } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_msat(out1: &mut [u32; 13]) -> () { out1[0] = 0xffffffff; out1[1] = (0x0 as u32); out1[2] = (0x0 as u32); out1[3] = 0xffffffff; out1[4] = 0xfffffffe; out1[5] = 0xffffffff; out1[6] = 0xffffffff; out1[7] = 0xffffffff; out1[8] = 0xffffffff; out1[9] = 0xffffffff; out1[10] = 0xffffffff; out1[11] = 0xffffffff; out1[12] = (0x0 as u32); } /// The function fiat_p384_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 ~> 0xffffffff] /// arg2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// arg5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffff] /// out2: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out3: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out4: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] /// out5: [[0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_divstep(out1: &mut u32, out2: &mut [u32; 13], out3: &mut [u32; 13], out4: &mut [u32; 12], out5: &mut [u32; 12], arg1: u32, arg2: &[u32; 13], arg3: &[u32; 13], arg4: &[u32; 12], arg5: &[u32; 12]) -> () { let mut x1: u32 = 0; let mut x2: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x1, &mut x2, 0x0, (!arg1), (0x1 as u32)); let x3: fiat_p384_u1 = (((x1 >> 31) as fiat_p384_u1) & (((arg3[0]) & (0x1 as u32)) as fiat_p384_u1)); let mut x4: u32 = 0; let mut x5: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x4, &mut x5, 0x0, (!arg1), (0x1 as u32)); let mut x6: u32 = 0; fiat_p384_cmovznz_u32(&mut x6, x3, arg1, x4); let mut x7: u32 = 0; fiat_p384_cmovznz_u32(&mut x7, x3, (arg2[0]), (arg3[0])); let mut x8: u32 = 0; fiat_p384_cmovznz_u32(&mut x8, x3, (arg2[1]), (arg3[1])); let mut x9: u32 = 0; fiat_p384_cmovznz_u32(&mut x9, x3, (arg2[2]), (arg3[2])); let mut x10: u32 = 0; fiat_p384_cmovznz_u32(&mut x10, x3, (arg2[3]), (arg3[3])); let mut x11: u32 = 0; fiat_p384_cmovznz_u32(&mut x11, x3, (arg2[4]), (arg3[4])); let mut x12: u32 = 0; fiat_p384_cmovznz_u32(&mut x12, x3, (arg2[5]), (arg3[5])); let mut x13: u32 = 0; fiat_p384_cmovznz_u32(&mut x13, x3, (arg2[6]), (arg3[6])); let mut x14: u32 = 0; fiat_p384_cmovznz_u32(&mut x14, x3, (arg2[7]), (arg3[7])); let mut x15: u32 = 0; fiat_p384_cmovznz_u32(&mut x15, x3, (arg2[8]), (arg3[8])); let mut x16: u32 = 0; fiat_p384_cmovznz_u32(&mut x16, x3, (arg2[9]), (arg3[9])); let mut x17: u32 = 0; fiat_p384_cmovznz_u32(&mut x17, x3, (arg2[10]), (arg3[10])); let mut x18: u32 = 0; fiat_p384_cmovznz_u32(&mut x18, x3, (arg2[11]), (arg3[11])); let mut x19: u32 = 0; fiat_p384_cmovznz_u32(&mut x19, x3, (arg2[12]), (arg3[12])); let mut x20: u32 = 0; let mut x21: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x20, &mut x21, 0x0, (0x1 as u32), (!(arg2[0]))); let mut x22: u32 = 0; let mut x23: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x22, &mut x23, x21, (0x0 as u32), (!(arg2[1]))); let mut x24: u32 = 0; let mut x25: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x24, &mut x25, x23, (0x0 as u32), (!(arg2[2]))); let mut x26: u32 = 0; let mut x27: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x26, &mut x27, x25, (0x0 as u32), (!(arg2[3]))); let mut x28: u32 = 0; let mut x29: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x28, &mut x29, x27, (0x0 as u32), (!(arg2[4]))); let mut x30: u32 = 0; let mut x31: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x30, &mut x31, x29, (0x0 as u32), (!(arg2[5]))); let mut x32: u32 = 0; let mut x33: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x32, &mut x33, x31, (0x0 as u32), (!(arg2[6]))); let mut x34: u32 = 0; let mut x35: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x34, &mut x35, x33, (0x0 as u32), (!(arg2[7]))); let mut x36: u32 = 0; let mut x37: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x36, &mut x37, x35, (0x0 as u32), (!(arg2[8]))); let mut x38: u32 = 0; let mut x39: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x38, &mut x39, x37, (0x0 as u32), (!(arg2[9]))); let mut x40: u32 = 0; let mut x41: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x40, &mut x41, x39, (0x0 as u32), (!(arg2[10]))); let mut x42: u32 = 0; let mut x43: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x42, &mut x43, x41, (0x0 as u32), (!(arg2[11]))); let mut x44: u32 = 0; let mut x45: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x44, &mut x45, x43, (0x0 as u32), (!(arg2[12]))); let mut x46: u32 = 0; fiat_p384_cmovznz_u32(&mut x46, x3, (arg3[0]), x20); let mut x47: u32 = 0; fiat_p384_cmovznz_u32(&mut x47, x3, (arg3[1]), x22); let mut x48: u32 = 0; fiat_p384_cmovznz_u32(&mut x48, x3, (arg3[2]), x24); let mut x49: u32 = 0; fiat_p384_cmovznz_u32(&mut x49, x3, (arg3[3]), x26); let mut x50: u32 = 0; fiat_p384_cmovznz_u32(&mut x50, x3, (arg3[4]), x28); let mut x51: u32 = 0; fiat_p384_cmovznz_u32(&mut x51, x3, (arg3[5]), x30); let mut x52: u32 = 0; fiat_p384_cmovznz_u32(&mut x52, x3, (arg3[6]), x32); let mut x53: u32 = 0; fiat_p384_cmovznz_u32(&mut x53, x3, (arg3[7]), x34); let mut x54: u32 = 0; fiat_p384_cmovznz_u32(&mut x54, x3, (arg3[8]), x36); let mut x55: u32 = 0; fiat_p384_cmovznz_u32(&mut x55, x3, (arg3[9]), x38); let mut x56: u32 = 0; fiat_p384_cmovznz_u32(&mut x56, x3, (arg3[10]), x40); let mut x57: u32 = 0; fiat_p384_cmovznz_u32(&mut x57, x3, (arg3[11]), x42); let mut x58: u32 = 0; fiat_p384_cmovznz_u32(&mut x58, x3, (arg3[12]), x44); let mut x59: u32 = 0; fiat_p384_cmovznz_u32(&mut x59, x3, (arg4[0]), (arg5[0])); let mut x60: u32 = 0; fiat_p384_cmovznz_u32(&mut x60, x3, (arg4[1]), (arg5[1])); let mut x61: u32 = 0; fiat_p384_cmovznz_u32(&mut x61, x3, (arg4[2]), (arg5[2])); let mut x62: u32 = 0; fiat_p384_cmovznz_u32(&mut x62, x3, (arg4[3]), (arg5[3])); let mut x63: u32 = 0; fiat_p384_cmovznz_u32(&mut x63, x3, (arg4[4]), (arg5[4])); let mut x64: u32 = 0; fiat_p384_cmovznz_u32(&mut x64, x3, (arg4[5]), (arg5[5])); let mut x65: u32 = 0; fiat_p384_cmovznz_u32(&mut x65, x3, (arg4[6]), (arg5[6])); let mut x66: u32 = 0; fiat_p384_cmovznz_u32(&mut x66, x3, (arg4[7]), (arg5[7])); let mut x67: u32 = 0; fiat_p384_cmovznz_u32(&mut x67, x3, (arg4[8]), (arg5[8])); let mut x68: u32 = 0; fiat_p384_cmovznz_u32(&mut x68, x3, (arg4[9]), (arg5[9])); let mut x69: u32 = 0; fiat_p384_cmovznz_u32(&mut x69, x3, (arg4[10]), (arg5[10])); let mut x70: u32 = 0; fiat_p384_cmovznz_u32(&mut x70, x3, (arg4[11]), (arg5[11])); let mut x71: u32 = 0; let mut x72: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x71, &mut x72, 0x0, x59, x59); let mut x73: u32 = 0; let mut x74: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x73, &mut x74, x72, x60, x60); let mut x75: u32 = 0; let mut x76: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x75, &mut x76, x74, x61, x61); let mut x77: u32 = 0; let mut x78: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x77, &mut x78, x76, x62, x62); let mut x79: u32 = 0; let mut x80: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x79, &mut x80, x78, x63, x63); let mut x81: u32 = 0; let mut x82: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x81, &mut x82, x80, x64, x64); let mut x83: u32 = 0; let mut x84: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x83, &mut x84, x82, x65, x65); let mut x85: u32 = 0; let mut x86: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x85, &mut x86, x84, x66, x66); let mut x87: u32 = 0; let mut x88: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x87, &mut x88, x86, x67, x67); let mut x89: u32 = 0; let mut x90: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x89, &mut x90, x88, x68, x68); let mut x91: u32 = 0; let mut x92: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x91, &mut x92, x90, x69, x69); let mut x93: u32 = 0; let mut x94: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x93, &mut x94, x92, x70, x70); let mut x95: u32 = 0; let mut x96: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x95, &mut x96, 0x0, x71, 0xffffffff); let mut x97: u32 = 0; let mut x98: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x97, &mut x98, x96, x73, (0x0 as u32)); let mut x99: u32 = 0; let mut x100: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x99, &mut x100, x98, x75, (0x0 as u32)); let mut x101: u32 = 0; let mut x102: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x101, &mut x102, x100, x77, 0xffffffff); let mut x103: u32 = 0; let mut x104: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x103, &mut x104, x102, x79, 0xfffffffe); let mut x105: u32 = 0; let mut x106: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x105, &mut x106, x104, x81, 0xffffffff); let mut x107: u32 = 0; let mut x108: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x107, &mut x108, x106, x83, 0xffffffff); let mut x109: u32 = 0; let mut x110: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x109, &mut x110, x108, x85, 0xffffffff); let mut x111: u32 = 0; let mut x112: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x111, &mut x112, x110, x87, 0xffffffff); let mut x113: u32 = 0; let mut x114: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x113, &mut x114, x112, x89, 0xffffffff); let mut x115: u32 = 0; let mut x116: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x115, &mut x116, x114, x91, 0xffffffff); let mut x117: u32 = 0; let mut x118: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x117, &mut x118, x116, x93, 0xffffffff); let mut x119: u32 = 0; let mut x120: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x119, &mut x120, x118, (x94 as u32), (0x0 as u32)); let x121: u32 = (arg4[11]); let x122: u32 = (arg4[10]); let x123: u32 = (arg4[9]); let x124: u32 = (arg4[8]); let x125: u32 = (arg4[7]); let x126: u32 = (arg4[6]); let x127: u32 = (arg4[5]); let x128: u32 = (arg4[4]); let x129: u32 = (arg4[3]); let x130: u32 = (arg4[2]); let x131: u32 = (arg4[1]); let x132: u32 = (arg4[0]); let mut x133: u32 = 0; let mut x134: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x133, &mut x134, 0x0, (0x0 as u32), x132); let mut x135: u32 = 0; let mut x136: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x135, &mut x136, x134, (0x0 as u32), x131); let mut x137: u32 = 0; let mut x138: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x137, &mut x138, x136, (0x0 as u32), x130); let mut x139: u32 = 0; let mut x140: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x139, &mut x140, x138, (0x0 as u32), x129); let mut x141: u32 = 0; let mut x142: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x141, &mut x142, x140, (0x0 as u32), x128); let mut x143: u32 = 0; let mut x144: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x143, &mut x144, x142, (0x0 as u32), x127); let mut x145: u32 = 0; let mut x146: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x145, &mut x146, x144, (0x0 as u32), x126); let mut x147: u32 = 0; let mut x148: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x147, &mut x148, x146, (0x0 as u32), x125); let mut x149: u32 = 0; let mut x150: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x149, &mut x150, x148, (0x0 as u32), x124); let mut x151: u32 = 0; let mut x152: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x151, &mut x152, x150, (0x0 as u32), x123); let mut x153: u32 = 0; let mut x154: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x153, &mut x154, x152, (0x0 as u32), x122); let mut x155: u32 = 0; let mut x156: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x155, &mut x156, x154, (0x0 as u32), x121); let mut x157: u32 = 0; fiat_p384_cmovznz_u32(&mut x157, x156, (0x0 as u32), 0xffffffff); let mut x158: u32 = 0; let mut x159: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x158, &mut x159, 0x0, x133, x157); let mut x160: u32 = 0; let mut x161: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x160, &mut x161, x159, x135, (0x0 as u32)); let mut x162: u32 = 0; let mut x163: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x162, &mut x163, x161, x137, (0x0 as u32)); let mut x164: u32 = 0; let mut x165: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x164, &mut x165, x163, x139, x157); let mut x166: u32 = 0; let mut x167: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x166, &mut x167, x165, x141, (x157 & 0xfffffffe)); let mut x168: u32 = 0; let mut x169: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x168, &mut x169, x167, x143, x157); let mut x170: u32 = 0; let mut x171: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x170, &mut x171, x169, x145, x157); let mut x172: u32 = 0; let mut x173: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x172, &mut x173, x171, x147, x157); let mut x174: u32 = 0; let mut x175: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x174, &mut x175, x173, x149, x157); let mut x176: u32 = 0; let mut x177: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x176, &mut x177, x175, x151, x157); let mut x178: u32 = 0; let mut x179: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x178, &mut x179, x177, x153, x157); let mut x180: u32 = 0; let mut x181: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x180, &mut x181, x179, x155, x157); let mut x182: u32 = 0; fiat_p384_cmovznz_u32(&mut x182, x3, (arg5[0]), x158); let mut x183: u32 = 0; fiat_p384_cmovznz_u32(&mut x183, x3, (arg5[1]), x160); let mut x184: u32 = 0; fiat_p384_cmovznz_u32(&mut x184, x3, (arg5[2]), x162); let mut x185: u32 = 0; fiat_p384_cmovznz_u32(&mut x185, x3, (arg5[3]), x164); let mut x186: u32 = 0; fiat_p384_cmovznz_u32(&mut x186, x3, (arg5[4]), x166); let mut x187: u32 = 0; fiat_p384_cmovznz_u32(&mut x187, x3, (arg5[5]), x168); let mut x188: u32 = 0; fiat_p384_cmovznz_u32(&mut x188, x3, (arg5[6]), x170); let mut x189: u32 = 0; fiat_p384_cmovznz_u32(&mut x189, x3, (arg5[7]), x172); let mut x190: u32 = 0; fiat_p384_cmovznz_u32(&mut x190, x3, (arg5[8]), x174); let mut x191: u32 = 0; fiat_p384_cmovznz_u32(&mut x191, x3, (arg5[9]), x176); let mut x192: u32 = 0; fiat_p384_cmovznz_u32(&mut x192, x3, (arg5[10]), x178); let mut x193: u32 = 0; fiat_p384_cmovznz_u32(&mut x193, x3, (arg5[11]), x180); let x194: fiat_p384_u1 = ((x46 & (0x1 as u32)) as fiat_p384_u1); let mut x195: u32 = 0; fiat_p384_cmovznz_u32(&mut x195, x194, (0x0 as u32), x7); let mut x196: u32 = 0; fiat_p384_cmovznz_u32(&mut x196, x194, (0x0 as u32), x8); let mut x197: u32 = 0; fiat_p384_cmovznz_u32(&mut x197, x194, (0x0 as u32), x9); let mut x198: u32 = 0; fiat_p384_cmovznz_u32(&mut x198, x194, (0x0 as u32), x10); let mut x199: u32 = 0; fiat_p384_cmovznz_u32(&mut x199, x194, (0x0 as u32), x11); let mut x200: u32 = 0; fiat_p384_cmovznz_u32(&mut x200, x194, (0x0 as u32), x12); let mut x201: u32 = 0; fiat_p384_cmovznz_u32(&mut x201, x194, (0x0 as u32), x13); let mut x202: u32 = 0; fiat_p384_cmovznz_u32(&mut x202, x194, (0x0 as u32), x14); let mut x203: u32 = 0; fiat_p384_cmovznz_u32(&mut x203, x194, (0x0 as u32), x15); let mut x204: u32 = 0; fiat_p384_cmovznz_u32(&mut x204, x194, (0x0 as u32), x16); let mut x205: u32 = 0; fiat_p384_cmovznz_u32(&mut x205, x194, (0x0 as u32), x17); let mut x206: u32 = 0; fiat_p384_cmovznz_u32(&mut x206, x194, (0x0 as u32), x18); let mut x207: u32 = 0; fiat_p384_cmovznz_u32(&mut x207, x194, (0x0 as u32), x19); let mut x208: u32 = 0; let mut x209: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x208, &mut x209, 0x0, x46, x195); let mut x210: u32 = 0; let mut x211: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x210, &mut x211, x209, x47, x196); let mut x212: u32 = 0; let mut x213: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x212, &mut x213, x211, x48, x197); let mut x214: u32 = 0; let mut x215: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x214, &mut x215, x213, x49, x198); let mut x216: u32 = 0; let mut x217: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x216, &mut x217, x215, x50, x199); let mut x218: u32 = 0; let mut x219: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x218, &mut x219, x217, x51, x200); let mut x220: u32 = 0; let mut x221: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x220, &mut x221, x219, x52, x201); let mut x222: u32 = 0; let mut x223: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x222, &mut x223, x221, x53, x202); let mut x224: u32 = 0; let mut x225: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x224, &mut x225, x223, x54, x203); let mut x226: u32 = 0; let mut x227: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x226, &mut x227, x225, x55, x204); let mut x228: u32 = 0; let mut x229: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x228, &mut x229, x227, x56, x205); let mut x230: u32 = 0; let mut x231: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x230, &mut x231, x229, x57, x206); let mut x232: u32 = 0; let mut x233: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x232, &mut x233, x231, x58, x207); let mut x234: u32 = 0; fiat_p384_cmovznz_u32(&mut x234, x194, (0x0 as u32), x59); let mut x235: u32 = 0; fiat_p384_cmovznz_u32(&mut x235, x194, (0x0 as u32), x60); let mut x236: u32 = 0; fiat_p384_cmovznz_u32(&mut x236, x194, (0x0 as u32), x61); let mut x237: u32 = 0; fiat_p384_cmovznz_u32(&mut x237, x194, (0x0 as u32), x62); let mut x238: u32 = 0; fiat_p384_cmovznz_u32(&mut x238, x194, (0x0 as u32), x63); let mut x239: u32 = 0; fiat_p384_cmovznz_u32(&mut x239, x194, (0x0 as u32), x64); let mut x240: u32 = 0; fiat_p384_cmovznz_u32(&mut x240, x194, (0x0 as u32), x65); let mut x241: u32 = 0; fiat_p384_cmovznz_u32(&mut x241, x194, (0x0 as u32), x66); let mut x242: u32 = 0; fiat_p384_cmovznz_u32(&mut x242, x194, (0x0 as u32), x67); let mut x243: u32 = 0; fiat_p384_cmovznz_u32(&mut x243, x194, (0x0 as u32), x68); let mut x244: u32 = 0; fiat_p384_cmovznz_u32(&mut x244, x194, (0x0 as u32), x69); let mut x245: u32 = 0; fiat_p384_cmovznz_u32(&mut x245, x194, (0x0 as u32), x70); let mut x246: u32 = 0; let mut x247: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x246, &mut x247, 0x0, x182, x234); let mut x248: u32 = 0; let mut x249: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x248, &mut x249, x247, x183, x235); let mut x250: u32 = 0; let mut x251: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x250, &mut x251, x249, x184, x236); let mut x252: u32 = 0; let mut x253: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x252, &mut x253, x251, x185, x237); let mut x254: u32 = 0; let mut x255: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x254, &mut x255, x253, x186, x238); let mut x256: u32 = 0; let mut x257: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x256, &mut x257, x255, x187, x239); let mut x258: u32 = 0; let mut x259: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x258, &mut x259, x257, x188, x240); let mut x260: u32 = 0; let mut x261: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x260, &mut x261, x259, x189, x241); let mut x262: u32 = 0; let mut x263: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x262, &mut x263, x261, x190, x242); let mut x264: u32 = 0; let mut x265: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x264, &mut x265, x263, x191, x243); let mut x266: u32 = 0; let mut x267: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x266, &mut x267, x265, x192, x244); let mut x268: u32 = 0; let mut x269: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x268, &mut x269, x267, x193, x245); let mut x270: u32 = 0; let mut x271: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x270, &mut x271, 0x0, x246, 0xffffffff); let mut x272: u32 = 0; let mut x273: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x272, &mut x273, x271, x248, (0x0 as u32)); let mut x274: u32 = 0; let mut x275: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x274, &mut x275, x273, x250, (0x0 as u32)); let mut x276: u32 = 0; let mut x277: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x276, &mut x277, x275, x252, 0xffffffff); let mut x278: u32 = 0; let mut x279: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x278, &mut x279, x277, x254, 0xfffffffe); let mut x280: u32 = 0; let mut x281: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x280, &mut x281, x279, x256, 0xffffffff); let mut x282: u32 = 0; let mut x283: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x282, &mut x283, x281, x258, 0xffffffff); let mut x284: u32 = 0; let mut x285: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x284, &mut x285, x283, x260, 0xffffffff); let mut x286: u32 = 0; let mut x287: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x286, &mut x287, x285, x262, 0xffffffff); let mut x288: u32 = 0; let mut x289: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x288, &mut x289, x287, x264, 0xffffffff); let mut x290: u32 = 0; let mut x291: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x290, &mut x291, x289, x266, 0xffffffff); let mut x292: u32 = 0; let mut x293: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x292, &mut x293, x291, x268, 0xffffffff); let mut x294: u32 = 0; let mut x295: fiat_p384_u1 = 0; fiat_p384_subborrowx_u32(&mut x294, &mut x295, x293, (x269 as u32), (0x0 as u32)); let mut x296: u32 = 0; let mut x297: fiat_p384_u1 = 0; fiat_p384_addcarryx_u32(&mut x296, &mut x297, 0x0, x6, (0x1 as u32)); let x298: u32 = ((x208 >> 1) | ((x210 << 31) & 0xffffffff)); let x299: u32 = ((x210 >> 1) | ((x212 << 31) & 0xffffffff)); let x300: u32 = ((x212 >> 1) | ((x214 << 31) & 0xffffffff)); let x301: u32 = ((x214 >> 1) | ((x216 << 31) & 0xffffffff)); let x302: u32 = ((x216 >> 1) | ((x218 << 31) & 0xffffffff)); let x303: u32 = ((x218 >> 1) | ((x220 << 31) & 0xffffffff)); let x304: u32 = ((x220 >> 1) | ((x222 << 31) & 0xffffffff)); let x305: u32 = ((x222 >> 1) | ((x224 << 31) & 0xffffffff)); let x306: u32 = ((x224 >> 1) | ((x226 << 31) & 0xffffffff)); let x307: u32 = ((x226 >> 1) | ((x228 << 31) & 0xffffffff)); let x308: u32 = ((x228 >> 1) | ((x230 << 31) & 0xffffffff)); let x309: u32 = ((x230 >> 1) | ((x232 << 31) & 0xffffffff)); let x310: u32 = ((x232 & 0x80000000) | (x232 >> 1)); let mut x311: u32 = 0; fiat_p384_cmovznz_u32(&mut x311, x120, x95, x71); let mut x312: u32 = 0; fiat_p384_cmovznz_u32(&mut x312, x120, x97, x73); let mut x313: u32 = 0; fiat_p384_cmovznz_u32(&mut x313, x120, x99, x75); let mut x314: u32 = 0; fiat_p384_cmovznz_u32(&mut x314, x120, x101, x77); let mut x315: u32 = 0; fiat_p384_cmovznz_u32(&mut x315, x120, x103, x79); let mut x316: u32 = 0; fiat_p384_cmovznz_u32(&mut x316, x120, x105, x81); let mut x317: u32 = 0; fiat_p384_cmovznz_u32(&mut x317, x120, x107, x83); let mut x318: u32 = 0; fiat_p384_cmovznz_u32(&mut x318, x120, x109, x85); let mut x319: u32 = 0; fiat_p384_cmovznz_u32(&mut x319, x120, x111, x87); let mut x320: u32 = 0; fiat_p384_cmovznz_u32(&mut x320, x120, x113, x89); let mut x321: u32 = 0; fiat_p384_cmovznz_u32(&mut x321, x120, x115, x91); let mut x322: u32 = 0; fiat_p384_cmovznz_u32(&mut x322, x120, x117, x93); let mut x323: u32 = 0; fiat_p384_cmovznz_u32(&mut x323, x295, x270, x246); let mut x324: u32 = 0; fiat_p384_cmovznz_u32(&mut x324, x295, x272, x248); let mut x325: u32 = 0; fiat_p384_cmovznz_u32(&mut x325, x295, x274, x250); let mut x326: u32 = 0; fiat_p384_cmovznz_u32(&mut x326, x295, x276, x252); let mut x327: u32 = 0; fiat_p384_cmovznz_u32(&mut x327, x295, x278, x254); let mut x328: u32 = 0; fiat_p384_cmovznz_u32(&mut x328, x295, x280, x256); let mut x329: u32 = 0; fiat_p384_cmovznz_u32(&mut x329, x295, x282, x258); let mut x330: u32 = 0; fiat_p384_cmovznz_u32(&mut x330, x295, x284, x260); let mut x331: u32 = 0; fiat_p384_cmovznz_u32(&mut x331, x295, x286, x262); let mut x332: u32 = 0; fiat_p384_cmovznz_u32(&mut x332, x295, x288, x264); let mut x333: u32 = 0; fiat_p384_cmovznz_u32(&mut x333, x295, x290, x266); let mut x334: u32 = 0; fiat_p384_cmovznz_u32(&mut x334, x295, x292, x268); *out1 = x296; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out2[8] = x15; out2[9] = x16; out2[10] = x17; out2[11] = x18; out2[12] = x19; out3[0] = x298; out3[1] = x299; out3[2] = x300; out3[3] = x301; out3[4] = x302; out3[5] = x303; out3[6] = x304; out3[7] = x305; out3[8] = x306; out3[9] = x307; out3[10] = x308; out3[11] = x309; out3[12] = x310; out4[0] = x311; out4[1] = x312; out4[2] = x313; out4[3] = x314; out4[4] = x315; out4[5] = x316; out4[6] = x317; out4[7] = x318; out4[8] = x319; out4[9] = x320; out4[10] = x321; out4[11] = x322; out5[0] = x323; out5[1] = x324; out5[2] = x325; out5[3] = x326; out5[4] = x327; out5[5] = x328; out5[6] = x329; out5[7] = x330; out5[8] = x331; out5[9] = x332; out5[10] = x333; out5[11] = x334; } /// The function fiat_p384_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 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff], [0x0 ~> 0xffffffff]] #[inline] pub fn fiat_p384_divstep_precomp(out1: &mut [u32; 12]) -> () { out1[0] = 0xfff18fff; out1[1] = 0xfff69400; out1[2] = 0xffffd3ff; out1[3] = 0x2b7fe; out1[4] = 0xfffe97ff; out1[5] = 0xfffedbff; out1[6] = 0x2fff; out1[7] = 0x28400; out1[8] = 0x50400; out1[9] = 0x60400; out1[10] = 0x38000; out1[11] = 0xfffc4800; }
41.609774
830
0.662003
e8fdaddaeb89cd5a3e654f196c3dd9007030707f
65,841
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! The Rust compiler. //! //! # Note //! //! This API is completely unstable and subject to change. #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://doc.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/nightly/")] #![feature(box_syntax)] #![cfg_attr(unix, feature(libc))] #![feature(nll)] #![feature(quote)] #![feature(rustc_diagnostic_macros)] #![feature(slice_sort_by_cached_key)] #![feature(set_stdio)] #![feature(rustc_stack_internals)] #![feature(no_debug)] #![recursion_limit="256"] extern crate arena; pub extern crate getopts; extern crate graphviz; extern crate env_logger; #[cfg(unix)] extern crate libc; extern crate rustc_rayon as rayon; extern crate rustc; extern crate rustc_allocator; extern crate rustc_target; extern crate rustc_borrowck; extern crate rustc_data_structures; extern crate rustc_errors as errors; extern crate rustc_passes; extern crate rustc_lint; extern crate rustc_plugin; extern crate rustc_privacy; extern crate rustc_incremental; extern crate rustc_metadata; extern crate rustc_mir; extern crate rustc_resolve; extern crate rustc_save_analysis; extern crate rustc_traits; extern crate rustc_codegen_utils; extern crate rustc_typeck; extern crate scoped_tls; extern crate serialize; extern crate smallvec; #[macro_use] extern crate log; extern crate syntax; extern crate syntax_ext; extern crate syntax_pos; // Note that the linkage here should be all that we need, on Linux we're not // prefixing the symbols here so this should naturally override our default // allocator. On OSX it should override via the zone allocator. We shouldn't // enable this by default on other platforms, so other platforms aren't handled // here yet. #[cfg(feature = "jemalloc-sys")] extern crate jemalloc_sys; use driver::CompileController; use pretty::{PpMode, UserIdentifiedItem}; use rustc_resolve as resolve; use rustc_save_analysis as save; use rustc_save_analysis::DumpHandler; use rustc_data_structures::sync::{self, Lrc}; use rustc_data_structures::OnDrop; use rustc::session::{self, config, Session, build_session, CompileResult}; use rustc::session::CompileIncomplete; use rustc::session::config::{Input, PrintRequest, ErrorOutputType}; use rustc::session::config::nightly_options; use rustc::session::filesearch; use rustc::session::{early_error, early_warn}; use rustc::lint::Lint; use rustc::lint; use rustc_metadata::locator; use rustc_metadata::cstore::CStore; use rustc_metadata::dynamic_lib::DynamicLibrary; use rustc::util::common::{time, ErrorReported}; use rustc_codegen_utils::codegen_backend::CodegenBackend; use serialize::json::ToJson; use std::any::Any; use std::borrow::Cow; use std::cmp::max; use std::default::Default; use std::env::consts::{DLL_PREFIX, DLL_SUFFIX}; use std::env; use std::error::Error; use std::ffi::OsString; use std::fmt::{self, Display}; use std::io::{self, Read, Write}; use std::mem; use std::panic; use std::path::{PathBuf, Path}; use std::process::{self, Command, Stdio}; use std::str; use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use std::sync::{Once, ONCE_INIT}; use std::thread; use syntax::ast; use syntax::source_map::{SourceMap, FileLoader, RealFileLoader}; use syntax::feature_gate::{GatedCfg, UnstableFeatures}; use syntax::parse::{self, PResult}; use syntax_pos::{DUMMY_SP, MultiSpan, FileName}; #[cfg(test)] mod test; pub mod profile; pub mod driver; pub mod pretty; mod derive_registrar; pub mod target_features { use syntax::ast; use syntax::symbol::Symbol; use rustc::session::Session; use rustc_codegen_utils::codegen_backend::CodegenBackend; /// Add `target_feature = "..."` cfgs for a variety of platform /// specific features (SSE, NEON etc.). /// /// This is performed by checking whether a whitelisted set of /// features is available on the target machine, by querying LLVM. pub fn add_configuration(cfg: &mut ast::CrateConfig, sess: &Session, codegen_backend: &dyn CodegenBackend) { let tf = Symbol::intern("target_feature"); cfg.extend(codegen_backend.target_features(sess).into_iter().map(|feat| (tf, Some(feat)))); if sess.crt_static_feature() { cfg.insert((tf, Some(Symbol::intern("crt-static")))); } } } /// Exit status code used for successful compilation and help output. pub const EXIT_SUCCESS: isize = 0; /// Exit status code used for compilation failures and invalid flags. pub const EXIT_FAILURE: isize = 1; const BUG_REPORT_URL: &str = "https://github.com/rust-lang/rust/blob/master/CONTRIBUTING.\ md#bug-reports"; const ICE_REPORT_COMPILER_FLAGS: &[&str] = &["Z", "C", "crate-type"]; const ICE_REPORT_COMPILER_FLAGS_EXCLUDE: &[&str] = &["metadata", "extra-filename"]; const ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE: &[&str] = &["incremental"]; pub fn abort_on_err<T>(result: Result<T, CompileIncomplete>, sess: &Session) -> T { match result { Err(CompileIncomplete::Errored(ErrorReported)) => { sess.abort_if_errors(); panic!("error reported but abort_if_errors didn't abort???"); } Err(CompileIncomplete::Stopped) => { sess.fatal("compilation terminated"); } Ok(x) => x, } } pub fn run<F>(run_compiler: F) -> isize where F: FnOnce() -> (CompileResult, Option<Session>) + Send + 'static { let result = monitor(move || { syntax::with_globals(|| { let (result, session) = run_compiler(); if let Err(CompileIncomplete::Errored(_)) = result { match session { Some(sess) => { sess.abort_if_errors(); panic!("error reported but abort_if_errors didn't abort???"); } None => { let emitter = errors::emitter::EmitterWriter::stderr( errors::ColorConfig::Auto, None, true, false ); let handler = errors::Handler::with_emitter(true, false, Box::new(emitter)); handler.emit(&MultiSpan::new(), "aborting due to previous error(s)", errors::Level::Fatal); panic::resume_unwind(Box::new(errors::FatalErrorMarker)); } } } }); }); match result { Ok(()) => EXIT_SUCCESS, Err(_) => EXIT_FAILURE, } } fn load_backend_from_dylib(path: &Path) -> fn() -> Box<dyn CodegenBackend> { // Note that we're specifically using `open_global_now` here rather than // `open`, namely we want the behavior on Unix of RTLD_GLOBAL and RTLD_NOW, // where NOW means "bind everything right now" because we don't want // surprises later on and RTLD_GLOBAL allows the symbols to be made // available for future dynamic libraries opened. This is currently used by // loading LLVM and then making its symbols available for other dynamic // libraries. let lib = DynamicLibrary::open_global_now(path).unwrap_or_else(|err| { let err = format!("couldn't load codegen backend {:?}: {:?}", path, err); early_error(ErrorOutputType::default(), &err); }); unsafe { match lib.symbol("__rustc_codegen_backend") { Ok(f) => { mem::forget(lib); mem::transmute::<*mut u8, _>(f) } Err(e) => { let err = format!("couldn't load codegen backend as it \ doesn't export the `__rustc_codegen_backend` \ symbol: {:?}", e); early_error(ErrorOutputType::default(), &err); } } } } pub fn get_codegen_backend(sess: &Session) -> Box<dyn CodegenBackend> { static INIT: Once = ONCE_INIT; #[allow(deprecated)] #[no_debug] static mut LOAD: fn() -> Box<dyn CodegenBackend> = || unreachable!(); INIT.call_once(|| { let codegen_name = sess.opts.debugging_opts.codegen_backend.as_ref() .unwrap_or(&sess.target.target.options.codegen_backend); let backend = match &codegen_name[..] { "metadata_only" => { rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::new } filename if filename.contains(".") => { load_backend_from_dylib(filename.as_ref()) } codegen_name => get_codegen_sysroot(codegen_name), }; unsafe { LOAD = backend; } }); let backend = unsafe { LOAD() }; backend.init(sess); backend } fn get_codegen_sysroot(backend_name: &str) -> fn() -> Box<dyn CodegenBackend> { // For now we only allow this function to be called once as it'll dlopen a // few things, which seems to work best if we only do that once. In // general this assertion never trips due to the once guard in `get_codegen_backend`, // but there's a few manual calls to this function in this file we protect // against. static LOADED: AtomicBool = ATOMIC_BOOL_INIT; assert!(!LOADED.fetch_or(true, Ordering::SeqCst), "cannot load the default codegen backend twice"); // When we're compiling this library with `--test` it'll run as a binary but // not actually exercise much functionality. As a result most of the logic // here is defunkt (it assumes we're a dynamic library in a sysroot) so // let's just return a dummy creation function which won't be used in // general anyway. if cfg!(test) { return rustc_codegen_utils::codegen_backend::MetadataOnlyCodegenBackend::new } let target = session::config::host_triple(); let mut sysroot_candidates = vec![filesearch::get_or_default_sysroot()]; let path = current_dll_path() .and_then(|s| s.canonicalize().ok()); if let Some(dll) = path { // use `parent` twice to chop off the file name and then also the // directory containing the dll which should be either `lib` or `bin`. if let Some(path) = dll.parent().and_then(|p| p.parent()) { // The original `path` pointed at the `rustc_driver` crate's dll. // Now that dll should only be in one of two locations. The first is // in the compiler's libdir, for example `$sysroot/lib/*.dll`. The // other is the target's libdir, for example // `$sysroot/lib/rustlib/$target/lib/*.dll`. // // We don't know which, so let's assume that if our `path` above // ends in `$target` we *could* be in the target libdir, and always // assume that we may be in the main libdir. sysroot_candidates.push(path.to_owned()); if path.ends_with(target) { sysroot_candidates.extend(path.parent() // chop off `$target` .and_then(|p| p.parent()) // chop off `rustlib` .and_then(|p| p.parent()) // chop off `lib` .map(|s| s.to_owned())); } } } let sysroot = sysroot_candidates.iter() .map(|sysroot| { let libdir = filesearch::relative_target_lib_path(&sysroot, &target); sysroot.join(libdir).with_file_name( option_env!("CFG_CODEGEN_BACKENDS_DIR").unwrap_or("codegen-backends")) }) .filter(|f| { info!("codegen backend candidate: {}", f.display()); f.exists() }) .next(); let sysroot = sysroot.unwrap_or_else(|| { let candidates = sysroot_candidates.iter() .map(|p| p.display().to_string()) .collect::<Vec<_>>() .join("\n* "); let err = format!("failed to find a `codegen-backends` folder \ in the sysroot candidates:\n* {}", candidates); early_error(ErrorOutputType::default(), &err); }); info!("probing {} for a codegen backend", sysroot.display()); let d = sysroot.read_dir().unwrap_or_else(|e| { let err = format!("failed to load default codegen backend, couldn't \ read `{}`: {}", sysroot.display(), e); early_error(ErrorOutputType::default(), &err); }); let mut file: Option<PathBuf> = None; let expected_name = format!("rustc_codegen_llvm-{}", backend_name); for entry in d.filter_map(|e| e.ok()) { let path = entry.path(); let filename = match path.file_name().and_then(|s| s.to_str()) { Some(s) => s, None => continue, }; if !(filename.starts_with(DLL_PREFIX) && filename.ends_with(DLL_SUFFIX)) { continue } let name = &filename[DLL_PREFIX.len() .. filename.len() - DLL_SUFFIX.len()]; if name != expected_name { continue } if let Some(ref prev) = file { let err = format!("duplicate codegen backends found\n\ first: {}\n\ second: {}\n\ ", prev.display(), path.display()); early_error(ErrorOutputType::default(), &err); } file = Some(path.clone()); } match file { Some(ref s) => return load_backend_from_dylib(s), None => { let err = format!("failed to load default codegen backend for `{}`, \ no appropriate codegen dylib found in `{}`", backend_name, sysroot.display()); early_error(ErrorOutputType::default(), &err); } } #[cfg(unix)] fn current_dll_path() -> Option<PathBuf> { use std::ffi::{OsStr, CStr}; use std::os::unix::prelude::*; unsafe { let addr = current_dll_path as usize as *mut _; let mut info = mem::zeroed(); if libc::dladdr(addr, &mut info) == 0 { info!("dladdr failed"); return None } if info.dli_fname.is_null() { info!("dladdr returned null pointer"); return None } let bytes = CStr::from_ptr(info.dli_fname).to_bytes(); let os = OsStr::from_bytes(bytes); Some(PathBuf::from(os)) } } #[cfg(windows)] fn current_dll_path() -> Option<PathBuf> { use std::ffi::OsString; use std::os::windows::prelude::*; extern "system" { fn GetModuleHandleExW(dwFlags: u32, lpModuleName: usize, phModule: *mut usize) -> i32; fn GetModuleFileNameW(hModule: usize, lpFilename: *mut u16, nSize: u32) -> u32; } const GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS: u32 = 0x00000004; unsafe { let mut module = 0; let r = GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, current_dll_path as usize, &mut module); if r == 0 { info!("GetModuleHandleExW failed: {}", io::Error::last_os_error()); return None } let mut space = Vec::with_capacity(1024); let r = GetModuleFileNameW(module, space.as_mut_ptr(), space.capacity() as u32); if r == 0 { info!("GetModuleFileNameW failed: {}", io::Error::last_os_error()); return None } let r = r as usize; if r >= space.capacity() { info!("our buffer was too small? {}", io::Error::last_os_error()); return None } space.set_len(r); let os = OsString::from_wide(&space); Some(PathBuf::from(os)) } } } // Parse args and run the compiler. This is the primary entry point for rustc. // See comments on CompilerCalls below for details about the callbacks argument. // The FileLoader provides a way to load files from sources other than the file system. pub fn run_compiler<'a>(args: &[String], callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>, file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>, emitter_dest: Option<Box<dyn Write + Send>>) -> (CompileResult, Option<Session>) { let matches = match handle_options(args) { Some(matches) => matches, None => return (Ok(()), None), }; let (sopts, cfg) = config::build_session_options_and_crate_config(&matches); driver::spawn_thread_pool(sopts, |sopts| { run_compiler_with_pool(matches, sopts, cfg, callbacks, file_loader, emitter_dest) }) } fn run_compiler_with_pool<'a>( matches: getopts::Matches, sopts: config::Options, cfg: ast::CrateConfig, mut callbacks: Box<dyn CompilerCalls<'a> + sync::Send + 'a>, file_loader: Option<Box<dyn FileLoader + Send + Sync + 'static>>, emitter_dest: Option<Box<dyn Write + Send>> ) -> (CompileResult, Option<Session>) { macro_rules! do_or_return {($expr: expr, $sess: expr) => { match $expr { Compilation::Stop => return (Ok(()), $sess), Compilation::Continue => {} } }} let descriptions = diagnostics_registry(); do_or_return!(callbacks.early_callback(&matches, &sopts, &cfg, &descriptions, sopts.error_format), None); let (odir, ofile) = make_output(&matches); let (input, input_file_path, input_err) = match make_input(&matches.free) { Some((input, input_file_path, input_err)) => { let (input, input_file_path) = callbacks.some_input(input, input_file_path); (input, input_file_path, input_err) }, None => match callbacks.no_input(&matches, &sopts, &cfg, &odir, &ofile, &descriptions) { Some((input, input_file_path)) => (input, input_file_path, None), None => return (Ok(()), None), }, }; let loader = file_loader.unwrap_or(box RealFileLoader); let source_map = Lrc::new(SourceMap::with_file_loader(loader, sopts.file_path_mapping())); let mut sess = session::build_session_with_source_map( sopts, input_file_path.clone(), descriptions, source_map, emitter_dest, ); if let Some(err) = input_err { // Immediately stop compilation if there was an issue reading // the input (for example if the input stream is not UTF-8). sess.err(&err.to_string()); return (Err(CompileIncomplete::Stopped), Some(sess)); } let codegen_backend = get_codegen_backend(&sess); rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); let mut cfg = config::build_configuration(&sess, cfg); target_features::add_configuration(&mut cfg, &sess, &*codegen_backend); sess.parse_sess.config = cfg; let result = { let plugins = sess.opts.debugging_opts.extra_plugins.clone(); let cstore = CStore::new(codegen_backend.metadata_loader()); do_or_return!(callbacks.late_callback(&*codegen_backend, &matches, &sess, &cstore, &input, &odir, &ofile), Some(sess)); let _sess_abort_error = OnDrop(|| sess.diagnostic().print_error_count()); let control = callbacks.build_controller(&sess, &matches); driver::compile_input(codegen_backend, &sess, &cstore, &input_file_path, &input, &odir, &ofile, Some(plugins), &control) }; (result, Some(sess)) } #[cfg(unix)] pub fn set_sigpipe_handler() { unsafe { // Set the SIGPIPE signal handler, so that an EPIPE // will cause rustc to terminate, as expected. assert_ne!(libc::signal(libc::SIGPIPE, libc::SIG_DFL), libc::SIG_ERR); } } #[cfg(windows)] pub fn set_sigpipe_handler() {} // Extract output directory and file from matches. fn make_output(matches: &getopts::Matches) -> (Option<PathBuf>, Option<PathBuf>) { let odir = matches.opt_str("out-dir").map(|o| PathBuf::from(&o)); let ofile = matches.opt_str("o").map(|o| PathBuf::from(&o)); (odir, ofile) } // Extract input (string or file and optional path) from matches. fn make_input(free_matches: &[String]) -> Option<(Input, Option<PathBuf>, Option<io::Error>)> { if free_matches.len() == 1 { let ifile = &free_matches[0]; if ifile == "-" { let mut src = String::new(); let err = if io::stdin().read_to_string(&mut src).is_err() { Some(io::Error::new(io::ErrorKind::InvalidData, "couldn't read from stdin, as it did not contain valid UTF-8")) } else { None }; Some((Input::Str { name: FileName::Anon, input: src }, None, err)) } else { Some((Input::File(PathBuf::from(ifile)), Some(PathBuf::from(ifile)), None)) } } else { None } } fn parse_pretty(sess: &Session, matches: &getopts::Matches) -> Option<(PpMode, Option<UserIdentifiedItem>)> { let pretty = if sess.opts.debugging_opts.unstable_options { matches.opt_default("pretty", "normal").map(|a| { // stable pretty-print variants only pretty::parse_pretty(sess, &a, false) }) } else { None }; if pretty.is_none() { sess.opts.debugging_opts.unpretty.as_ref().map(|a| { // extended with unstable pretty-print variants pretty::parse_pretty(sess, &a, true) }) } else { pretty } } // Whether to stop or continue compilation. #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum Compilation { Stop, Continue, } impl Compilation { pub fn and_then<F: FnOnce() -> Compilation>(self, next: F) -> Compilation { match self { Compilation::Stop => Compilation::Stop, Compilation::Continue => next(), } } } /// A trait for customising the compilation process. Offers a number of hooks for /// executing custom code or customising input. pub trait CompilerCalls<'a> { /// Hook for a callback early in the process of handling arguments. This will /// be called straight after options have been parsed but before anything /// else (e.g., selecting input and output). fn early_callback(&mut self, _: &getopts::Matches, _: &config::Options, _: &ast::CrateConfig, _: &errors::registry::Registry, _: ErrorOutputType) -> Compilation { Compilation::Continue } /// Hook for a callback late in the process of handling arguments. This will /// be called just before actual compilation starts (and before build_controller /// is called), after all arguments etc. have been completely handled. fn late_callback(&mut self, _: &dyn CodegenBackend, _: &getopts::Matches, _: &Session, _: &CStore, _: &Input, _: &Option<PathBuf>, _: &Option<PathBuf>) -> Compilation { Compilation::Continue } /// Called after we extract the input from the arguments. Gives the implementer /// an opportunity to change the inputs or to add some custom input handling. /// The default behaviour is to simply pass through the inputs. fn some_input(&mut self, input: Input, input_path: Option<PathBuf>) -> (Input, Option<PathBuf>) { (input, input_path) } /// Called after we extract the input from the arguments if there is no valid /// input. Gives the implementer an opportunity to supply alternate input (by /// returning a Some value) or to add custom behaviour for this error such as /// emitting error messages. Returning None will cause compilation to stop /// at this point. fn no_input(&mut self, _: &getopts::Matches, _: &config::Options, _: &ast::CrateConfig, _: &Option<PathBuf>, _: &Option<PathBuf>, _: &errors::registry::Registry) -> Option<(Input, Option<PathBuf>)> { None } // Create a CompilController struct for controlling the behaviour of // compilation. fn build_controller( self: Box<Self>, _: &Session, _: &getopts::Matches ) -> CompileController<'a>; } /// CompilerCalls instance for a regular rustc build. #[derive(Copy, Clone)] pub struct RustcDefaultCalls; // FIXME remove these and use winapi 0.3 instead // Duplicates: bootstrap/compile.rs, librustc_errors/emitter.rs #[cfg(unix)] fn stdout_isatty() -> bool { unsafe { libc::isatty(libc::STDOUT_FILENO) != 0 } } #[cfg(windows)] fn stdout_isatty() -> bool { type DWORD = u32; type BOOL = i32; type HANDLE = *mut u8; type LPDWORD = *mut u32; const STD_OUTPUT_HANDLE: DWORD = -11i32 as DWORD; extern "system" { fn GetStdHandle(which: DWORD) -> HANDLE; fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: LPDWORD) -> BOOL; } unsafe { let handle = GetStdHandle(STD_OUTPUT_HANDLE); let mut out = 0; GetConsoleMode(handle, &mut out) != 0 } } fn handle_explain(code: &str, descriptions: &errors::registry::Registry, output: ErrorOutputType) { let normalised = if code.starts_with("E") { code.to_string() } else { format!("E{0:0>4}", code) }; match descriptions.find_description(&normalised) { Some(ref description) => { let mut is_in_code_block = false; let mut text = String::new(); // Slice off the leading newline and print. for line in description[1..].lines() { let indent_level = line.find(|c: char| !c.is_whitespace()) .unwrap_or_else(|| line.len()); let dedented_line = &line[indent_level..]; if dedented_line.starts_with("```") { is_in_code_block = !is_in_code_block; text.push_str(&line[..(indent_level+3)]); } else if is_in_code_block && dedented_line.starts_with("# ") { continue; } else { text.push_str(line); } text.push('\n'); } if stdout_isatty() { show_content_with_pager(&text); } else { print!("{}", text); } } None => { early_error(output, &format!("no extended information for {}", code)); } } } fn show_content_with_pager(content: &String) { let pager_name = env::var_os("PAGER").unwrap_or_else(|| if cfg!(windows) { OsString::from("more.com") } else { OsString::from("less") }); let mut fallback_to_println = false; match Command::new(pager_name).stdin(Stdio::piped()).spawn() { Ok(mut pager) => { if let Some(pipe) = pager.stdin.as_mut() { if pipe.write_all(content.as_bytes()).is_err() { fallback_to_println = true; } } if pager.wait().is_err() { fallback_to_println = true; } } Err(_) => { fallback_to_println = true; } } // If pager fails for whatever reason, we should still print the content // to standard output if fallback_to_println { print!("{}", content); } } impl<'a> CompilerCalls<'a> for RustcDefaultCalls { fn early_callback(&mut self, matches: &getopts::Matches, _: &config::Options, _: &ast::CrateConfig, descriptions: &errors::registry::Registry, output: ErrorOutputType) -> Compilation { if let Some(ref code) = matches.opt_str("explain") { handle_explain(code, descriptions, output); return Compilation::Stop; } Compilation::Continue } fn no_input(&mut self, matches: &getopts::Matches, sopts: &config::Options, cfg: &ast::CrateConfig, odir: &Option<PathBuf>, ofile: &Option<PathBuf>, descriptions: &errors::registry::Registry) -> Option<(Input, Option<PathBuf>)> { match matches.free.len() { 0 => { let mut sess = build_session(sopts.clone(), None, descriptions.clone()); if sopts.describe_lints { let mut ls = lint::LintStore::new(); rustc_lint::register_builtins(&mut ls, Some(&sess)); describe_lints(&sess, &ls, false); return None; } rustc_lint::register_builtins(&mut sess.lint_store.borrow_mut(), Some(&sess)); let mut cfg = config::build_configuration(&sess, cfg.clone()); let codegen_backend = get_codegen_backend(&sess); target_features::add_configuration(&mut cfg, &sess, &*codegen_backend); sess.parse_sess.config = cfg; let should_stop = RustcDefaultCalls::print_crate_info( &*codegen_backend, &sess, None, odir, ofile ); if should_stop == Compilation::Stop { return None; } early_error(sopts.error_format, "no input filename given"); } 1 => panic!("make_input should have provided valid inputs"), _ => early_error(sopts.error_format, "multiple input filenames provided"), } } fn late_callback(&mut self, codegen_backend: &dyn CodegenBackend, matches: &getopts::Matches, sess: &Session, cstore: &CStore, input: &Input, odir: &Option<PathBuf>, ofile: &Option<PathBuf>) -> Compilation { RustcDefaultCalls::print_crate_info(codegen_backend, sess, Some(input), odir, ofile) .and_then(|| RustcDefaultCalls::list_metadata(sess, cstore, matches, input)) } fn build_controller(self: Box<Self>, sess: &Session, matches: &getopts::Matches) -> CompileController<'a> { let mut control = CompileController::basic(); control.keep_ast = sess.opts.debugging_opts.keep_ast; control.continue_parse_after_error = sess.opts.debugging_opts.continue_parse_after_error; if let Some((ppm, opt_uii)) = parse_pretty(sess, matches) { if ppm.needs_ast_map(&opt_uii) { control.after_hir_lowering.stop = Compilation::Stop; control.after_parse.callback = box move |state| { state.krate = Some(pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm)); }; control.after_hir_lowering.callback = box move |state| { pretty::print_after_hir_lowering(state.session, state.cstore.unwrap(), state.hir_map.unwrap(), state.analysis.unwrap(), state.resolutions.unwrap(), state.input, &state.expanded_crate.take().unwrap(), state.crate_name.unwrap(), ppm, state.arenas.unwrap(), state.output_filenames.unwrap(), opt_uii.clone(), state.out_file); }; } else { control.after_parse.stop = Compilation::Stop; control.after_parse.callback = box move |state| { let krate = pretty::fold_crate(state.session, state.krate.take().unwrap(), ppm); pretty::print_after_parsing(state.session, state.input, &krate, ppm, state.out_file); }; } return control; } if sess.opts.debugging_opts.parse_only || sess.opts.debugging_opts.show_span.is_some() || sess.opts.debugging_opts.ast_json_noexpand { control.after_parse.stop = Compilation::Stop; } if sess.opts.debugging_opts.no_analysis || sess.opts.debugging_opts.ast_json { control.after_hir_lowering.stop = Compilation::Stop; } if sess.opts.debugging_opts.save_analysis { enable_save_analysis(&mut control); } if sess.print_fuel_crate.is_some() { let old_callback = control.compilation_done.callback; control.compilation_done.callback = box move |state| { old_callback(state); let sess = state.session; println!("Fuel used by {}: {}", sess.print_fuel_crate.as_ref().unwrap(), sess.print_fuel.get()); } } control } } pub fn enable_save_analysis(control: &mut CompileController) { control.keep_ast = true; control.after_analysis.callback = box |state| { time(state.session, "save analysis", || { save::process_crate(state.tcx.unwrap(), state.expanded_crate.unwrap(), state.analysis.unwrap(), state.crate_name.unwrap(), state.input, None, DumpHandler::new(state.out_dir, state.crate_name.unwrap())) }); }; control.after_analysis.run_callback_on_error = true; control.make_glob_map = resolve::MakeGlobMap::Yes; } impl RustcDefaultCalls { pub fn list_metadata(sess: &Session, cstore: &CStore, matches: &getopts::Matches, input: &Input) -> Compilation { let r = matches.opt_strs("Z"); if r.iter().any(|s| *s == "ls") { match input { &Input::File(ref ifile) => { let path = &(*ifile); let mut v = Vec::new(); locator::list_file_metadata(&sess.target.target, path, &*cstore.metadata_loader, &mut v) .unwrap(); println!("{}", String::from_utf8(v).unwrap()); } &Input::Str { .. } => { early_error(ErrorOutputType::default(), "cannot list metadata for stdin"); } } return Compilation::Stop; } Compilation::Continue } fn print_crate_info(codegen_backend: &dyn CodegenBackend, sess: &Session, input: Option<&Input>, odir: &Option<PathBuf>, ofile: &Option<PathBuf>) -> Compilation { use rustc::session::config::PrintRequest::*; // PrintRequest::NativeStaticLibs is special - printed during linking // (empty iterator returns true) if sess.opts.prints.iter().all(|&p| p == PrintRequest::NativeStaticLibs) { return Compilation::Continue; } let attrs = match input { None => None, Some(input) => { let result = parse_crate_attrs(sess, input); match result { Ok(attrs) => Some(attrs), Err(mut parse_error) => { parse_error.emit(); return Compilation::Stop; } } } }; for req in &sess.opts.prints { match *req { TargetList => { let mut targets = rustc_target::spec::get_targets().collect::<Vec<String>>(); targets.sort(); println!("{}", targets.join("\n")); }, Sysroot => println!("{}", sess.sysroot().display()), TargetSpec => println!("{}", sess.target.target.to_json().pretty()), FileNames | CrateName => { let input = input.unwrap_or_else(|| early_error(ErrorOutputType::default(), "no input file provided")); let attrs = attrs.as_ref().unwrap(); let t_outputs = driver::build_output_filenames(input, odir, ofile, attrs, sess); let id = rustc_codegen_utils::link::find_crate_name(Some(sess), attrs, input); if *req == PrintRequest::CrateName { println!("{}", id); continue; } let crate_types = driver::collect_crate_types(sess, attrs); for &style in &crate_types { let fname = rustc_codegen_utils::link::filename_for_input( sess, style, &id, &t_outputs ); println!("{}", fname.file_name().unwrap().to_string_lossy()); } } Cfg => { let allow_unstable_cfg = UnstableFeatures::from_environment() .is_nightly_build(); let mut cfgs = sess.parse_sess.config.iter().filter_map(|&(name, ref value)| { let gated_cfg = GatedCfg::gate(&ast::MetaItem { ident: ast::Path::from_ident(ast::Ident::with_empty_ctxt(name)), node: ast::MetaItemKind::Word, span: DUMMY_SP, }); // Note that crt-static is a specially recognized cfg // directive that's printed out here as part of // rust-lang/rust#37406, but in general the // `target_feature` cfg is gated under // rust-lang/rust#29717. For now this is just // specifically allowing the crt-static cfg and that's // it, this is intended to get into Cargo and then go // through to build scripts. let value = value.as_ref().map(|s| s.as_str()); let value = value.as_ref().map(|s| s.as_ref()); if name != "target_feature" || value != Some("crt-static") { if !allow_unstable_cfg && gated_cfg.is_some() { return None } } if let Some(value) = value { Some(format!("{}=\"{}\"", name, value)) } else { Some(name.to_string()) } }).collect::<Vec<String>>(); cfgs.sort(); for cfg in cfgs { println!("{}", cfg); } } RelocationModels | CodeModels | TlsModels | TargetCPUs | TargetFeatures => { codegen_backend.print(*req, sess); } // Any output here interferes with Cargo's parsing of other printed output PrintRequest::NativeStaticLibs => {} } } return Compilation::Stop; } } /// Returns a version string such as "0.12.0-dev". fn release_str() -> Option<&'static str> { option_env!("CFG_RELEASE") } /// Returns the full SHA1 hash of HEAD of the Git repo from which rustc was built. fn commit_hash_str() -> Option<&'static str> { option_env!("CFG_VER_HASH") } /// Returns the "commit date" of HEAD of the Git repo from which rustc was built as a static string. fn commit_date_str() -> Option<&'static str> { option_env!("CFG_VER_DATE") } /// Prints version information pub fn version(binary: &str, matches: &getopts::Matches) { let verbose = matches.opt_present("verbose"); println!("{} {}", binary, option_env!("CFG_VERSION").unwrap_or("unknown version")); if verbose { fn unw(x: Option<&str>) -> &str { x.unwrap_or("unknown") } println!("binary: {}", binary); println!("commit-hash: {}", unw(commit_hash_str())); println!("commit-date: {}", unw(commit_date_str())); println!("host: {}", config::host_triple()); println!("release: {}", unw(release_str())); get_codegen_sysroot("llvm")().print_version(); } } fn usage(verbose: bool, include_unstable_options: bool) { let groups = if verbose { config::rustc_optgroups() } else { config::rustc_short_optgroups() }; let mut options = getopts::Options::new(); for option in groups.iter().filter(|x| include_unstable_options || x.is_stable()) { (option.apply)(&mut options); } let message = "Usage: rustc [OPTIONS] INPUT"; let nightly_help = if nightly_options::is_nightly_build() { "\n -Z help Print internal options for debugging rustc" } else { "" }; let verbose_help = if verbose { "" } else { "\n --help -v Print the full set of options rustc accepts" }; println!("{}\nAdditional help: -C help Print codegen options -W help \ Print 'lint' options and default settings{}{}\n", options.usage(message), nightly_help, verbose_help); } fn print_wall_help() { println!(" The flag `-Wall` does not exist in `rustc`. Most useful lints are enabled by default. Use `rustc -W help` to see all available lints. It's more common to put warning settings in the crate root using `#![warn(LINT_NAME)]` instead of using the command line flag directly. "); } fn describe_lints(sess: &Session, lint_store: &lint::LintStore, loaded_plugins: bool) { println!(" Available lint options: -W <foo> Warn about <foo> -A <foo> \ Allow <foo> -D <foo> Deny <foo> -F <foo> Forbid <foo> \ (deny <foo> and all attempts to override) "); fn sort_lints(sess: &Session, lints: Vec<(&'static Lint, bool)>) -> Vec<&'static Lint> { let mut lints: Vec<_> = lints.into_iter().map(|(x, _)| x).collect(); // The sort doesn't case-fold but it's doubtful we care. lints.sort_by_cached_key(|x: &&Lint| (x.default_level(sess), x.name)); lints } fn sort_lint_groups(lints: Vec<(&'static str, Vec<lint::LintId>, bool)>) -> Vec<(&'static str, Vec<lint::LintId>)> { let mut lints: Vec<_> = lints.into_iter().map(|(x, y, _)| (x, y)).collect(); lints.sort_by_key(|l| l.0); lints } let (plugin, builtin): (Vec<_>, _) = lint_store.get_lints() .iter() .cloned() .partition(|&(_, p)| p); let plugin = sort_lints(sess, plugin); let builtin = sort_lints(sess, builtin); let (plugin_groups, builtin_groups): (Vec<_>, _) = lint_store.get_lint_groups() .iter() .cloned() .partition(|&(.., p)| p); let plugin_groups = sort_lint_groups(plugin_groups); let builtin_groups = sort_lint_groups(builtin_groups); let max_name_len = plugin.iter() .chain(&builtin) .map(|&s| s.name.chars().count()) .max() .unwrap_or(0); let padded = |x: &str| { let mut s = " ".repeat(max_name_len - x.chars().count()); s.push_str(x); s }; println!("Lint checks provided by rustc:\n"); println!(" {} {:7.7} {}", padded("name"), "default", "meaning"); println!(" {} {:7.7} {}", padded("----"), "-------", "-------"); let print_lints = |lints: Vec<&Lint>| { for lint in lints { let name = lint.name_lower().replace("_", "-"); println!(" {} {:7.7} {}", padded(&name), lint.default_level.as_str(), lint.desc); } println!("\n"); }; print_lints(builtin); let max_name_len = max("warnings".len(), plugin_groups.iter() .chain(&builtin_groups) .map(|&(s, _)| s.chars().count()) .max() .unwrap_or(0)); let padded = |x: &str| { let mut s = " ".repeat(max_name_len - x.chars().count()); s.push_str(x); s }; println!("Lint groups provided by rustc:\n"); println!(" {} {}", padded("name"), "sub-lints"); println!(" {} {}", padded("----"), "---------"); println!(" {} {}", padded("warnings"), "all lints that are set to issue warnings"); let print_lint_groups = |lints: Vec<(&'static str, Vec<lint::LintId>)>| { for (name, to) in lints { let name = name.to_lowercase().replace("_", "-"); let desc = to.into_iter() .map(|x| x.to_string().replace("_", "-")) .collect::<Vec<String>>() .join(", "); println!(" {} {}", padded(&name), desc); } println!("\n"); }; print_lint_groups(builtin_groups); match (loaded_plugins, plugin.len(), plugin_groups.len()) { (false, 0, _) | (false, _, 0) => { println!("Compiler plugins can provide additional lints and lint groups. To see a \ listing of these, re-run `rustc -W help` with a crate filename."); } (false, ..) => panic!("didn't load lint plugins but got them anyway!"), (true, 0, 0) => println!("This crate does not load any lint plugins or lint groups."), (true, l, g) => { if l > 0 { println!("Lint checks provided by plugins loaded by this crate:\n"); print_lints(plugin); } if g > 0 { println!("Lint groups provided by plugins loaded by this crate:\n"); print_lint_groups(plugin_groups); } } } } fn describe_debug_flags() { println!("\nAvailable debug options:\n"); print_flag_list("-Z", config::DB_OPTIONS); } fn describe_codegen_flags() { println!("\nAvailable codegen options:\n"); print_flag_list("-C", config::CG_OPTIONS); } fn print_flag_list<T>(cmdline_opt: &str, flag_list: &[(&'static str, T, Option<&'static str>, &'static str)]) { let max_len = flag_list.iter() .map(|&(name, _, opt_type_desc, _)| { let extra_len = match opt_type_desc { Some(..) => 4, None => 0, }; name.chars().count() + extra_len }) .max() .unwrap_or(0); for &(name, _, opt_type_desc, desc) in flag_list { let (width, extra) = match opt_type_desc { Some(..) => (max_len - 4, "=val"), None => (max_len, ""), }; println!(" {} {:>width$}{} -- {}", cmdline_opt, name.replace("_", "-"), extra, desc, width = width); } } /// Process command line options. Emits messages as appropriate. If compilation /// should continue, returns a getopts::Matches object parsed from args, /// otherwise returns None. /// /// The compiler's handling of options is a little complicated as it ties into /// our stability story, and it's even *more* complicated by historical /// accidents. The current intention of each compiler option is to have one of /// three modes: /// /// 1. An option is stable and can be used everywhere. /// 2. An option is unstable, but was historically allowed on the stable /// channel. /// 3. An option is unstable, and can only be used on nightly. /// /// Like unstable library and language features, however, unstable options have /// always required a form of "opt in" to indicate that you're using them. This /// provides the easy ability to scan a code base to check to see if anything /// unstable is being used. Currently, this "opt in" is the `-Z` "zed" flag. /// /// All options behind `-Z` are considered unstable by default. Other top-level /// options can also be considered unstable, and they were unlocked through the /// `-Z unstable-options` flag. Note that `-Z` remains to be the root of /// instability in both cases, though. /// /// So with all that in mind, the comments below have some more detail about the /// contortions done here to get things to work out correctly. pub fn handle_options(args: &[String]) -> Option<getopts::Matches> { // Throw away the first argument, the name of the binary let args = &args[1..]; if args.is_empty() { // user did not write `-v` nor `-Z unstable-options`, so do not // include that extra information. usage(false, false); return None; } // Parse with *all* options defined in the compiler, we don't worry about // option stability here we just want to parse as much as possible. let mut options = getopts::Options::new(); for option in config::rustc_optgroups() { (option.apply)(&mut options); } let matches = options.parse(args).unwrap_or_else(|f| early_error(ErrorOutputType::default(), &f.to_string())); // For all options we just parsed, we check a few aspects: // // * If the option is stable, we're all good // * If the option wasn't passed, we're all good // * If `-Z unstable-options` wasn't passed (and we're not a -Z option // ourselves), then we require the `-Z unstable-options` flag to unlock // this option that was passed. // * If we're a nightly compiler, then unstable options are now unlocked, so // we're good to go. // * Otherwise, if we're a truly unstable option then we generate an error // (unstable option being used on stable) // * If we're a historically stable-but-should-be-unstable option then we // emit a warning that we're going to turn this into an error soon. nightly_options::check_nightly_options(&matches, &config::rustc_optgroups()); if matches.opt_present("h") || matches.opt_present("help") { // Only show unstable options in --help if we *really* accept unstable // options, which catches the case where we got `-Z unstable-options` on // the stable channel of Rust which was accidentally allowed // historically. usage(matches.opt_present("verbose"), nightly_options::is_unstable_enabled(&matches)); return None; } // Handle the special case of -Wall. let wall = matches.opt_strs("W"); if wall.iter().any(|x| *x == "all") { print_wall_help(); return None; } // Don't handle -W help here, because we might first load plugins. let r = matches.opt_strs("Z"); if r.iter().any(|x| *x == "help") { describe_debug_flags(); return None; } let cg_flags = matches.opt_strs("C"); if cg_flags.iter().any(|x| *x == "help") { describe_codegen_flags(); return None; } if cg_flags.iter().any(|x| *x == "no-stack-check") { early_warn(ErrorOutputType::default(), "the --no-stack-check flag is deprecated and does nothing"); } if cg_flags.iter().any(|x| *x == "passes=list") { get_codegen_sysroot("llvm")().print_passes(); return None; } if matches.opt_present("version") { version("rustc", &matches); return None; } Some(matches) } fn parse_crate_attrs<'a>(sess: &'a Session, input: &Input) -> PResult<'a, Vec<ast::Attribute>> { match *input { Input::File(ref ifile) => { parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess) } Input::Str { ref name, ref input } => { parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.parse_sess) } } } /// Runs `f` in a suitable thread for running `rustc`; returns a `Result` with either the return /// value of `f` or -- if a panic occurs -- the panic value. /// /// This version applies the given name to the thread. This is used by rustdoc to ensure consistent /// doctest output across platforms and executions. pub fn in_named_rustc_thread<F, R>(name: String, f: F) -> Result<R, Box<dyn Any + Send>> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { // Temporarily have stack size set to 16MB to deal with nom-using crates failing const STACK_SIZE: usize = 16 * 1024 * 1024; // 16MB #[cfg(all(unix, not(target_os = "haiku")))] let spawn_thread = unsafe { // Fetch the current resource limits let mut rlim = libc::rlimit { rlim_cur: 0, rlim_max: 0, }; if libc::getrlimit(libc::RLIMIT_STACK, &mut rlim) != 0 { let err = io::Error::last_os_error(); error!("in_rustc_thread: error calling getrlimit: {}", err); true } else if rlim.rlim_max < STACK_SIZE as libc::rlim_t { true } else if rlim.rlim_cur < STACK_SIZE as libc::rlim_t { std::rt::deinit_stack_guard(); rlim.rlim_cur = STACK_SIZE as libc::rlim_t; if libc::setrlimit(libc::RLIMIT_STACK, &mut rlim) != 0 { let err = io::Error::last_os_error(); error!("in_rustc_thread: error calling setrlimit: {}", err); std::rt::update_stack_guard(); true } else { std::rt::update_stack_guard(); false } } else { false } }; // We set the stack size at link time. See src/rustc/rustc.rs. #[cfg(windows)] let spawn_thread = false; #[cfg(target_os = "haiku")] let spawn_thread = unsafe { // Haiku does not have setrlimit implemented for the stack size. // By default it does have the 16 MB stack limit, but we check this in // case the minimum STACK_SIZE changes or Haiku's defaults change. let mut rlim = libc::rlimit { rlim_cur: 0, rlim_max: 0, }; if libc::getrlimit(libc::RLIMIT_STACK, &mut rlim) != 0 { let err = io::Error::last_os_error(); error!("in_rustc_thread: error calling getrlimit: {}", err); true } else if rlim.rlim_cur >= STACK_SIZE { false } else { true } }; #[cfg(not(any(windows, unix)))] let spawn_thread = true; // The or condition is added from backward compatibility. if spawn_thread || env::var_os("RUST_MIN_STACK").is_some() { let mut cfg = thread::Builder::new().name(name); // FIXME: Hacks on hacks. If the env is trying to override the stack size // then *don't* set it explicitly. if env::var_os("RUST_MIN_STACK").is_none() { cfg = cfg.stack_size(STACK_SIZE); } let thread = cfg.spawn(f); thread.unwrap().join() } else { let f = panic::AssertUnwindSafe(f); panic::catch_unwind(f) } } /// Runs `f` in a suitable thread for running `rustc`; returns a /// `Result` with either the return value of `f` or -- if a panic /// occurs -- the panic value. pub fn in_rustc_thread<F, R>(f: F) -> Result<R, Box<dyn Any + Send>> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { in_named_rustc_thread("rustc".to_string(), f) } /// Get a list of extra command-line flags provided by the user, as strings. /// /// This function is used during ICEs to show more information useful for /// debugging, since some ICEs only happens with non-default compiler flags /// (and the users don't always report them). fn extra_compiler_flags() -> Option<(Vec<String>, bool)> { let args = env::args_os().map(|arg| arg.to_string_lossy().to_string()).collect::<Vec<_>>(); // Avoid printing help because of empty args. This can suggest the compiler // itself is not the program root (consider RLS). if args.len() < 2 { return None; } let matches = if let Some(matches) = handle_options(&args) { matches } else { return None; }; let mut result = Vec::new(); let mut excluded_cargo_defaults = false; for flag in ICE_REPORT_COMPILER_FLAGS { let prefix = if flag.len() == 1 { "-" } else { "--" }; for content in &matches.opt_strs(flag) { // Split always returns the first element let name = if let Some(first) = content.split('=').next() { first } else { &content }; let content = if ICE_REPORT_COMPILER_FLAGS_STRIP_VALUE.contains(&name) { name } else { content }; if !ICE_REPORT_COMPILER_FLAGS_EXCLUDE.contains(&name) { result.push(format!("{}{} {}", prefix, flag, content)); } else { excluded_cargo_defaults = true; } } } if !result.is_empty() { Some((result, excluded_cargo_defaults)) } else { None } } #[derive(Debug)] pub struct CompilationFailure; impl Error for CompilationFailure {} impl Display for CompilationFailure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "compilation had errors") } } /// Run a procedure which will detect panics in the compiler and print nicer /// error messages rather than just failing the test. /// /// The diagnostic emitter yielded to the procedure should be used for reporting /// errors of the compiler. pub fn monitor<F: FnOnce() + Send + 'static>(f: F) -> Result<(), CompilationFailure> { in_rustc_thread(move || { f() }).map_err(|value| { if value.is::<errors::FatalErrorMarker>() { CompilationFailure } else { // Thread panicked without emitting a fatal diagnostic eprintln!(""); let emitter = Box::new(errors::emitter::EmitterWriter::stderr(errors::ColorConfig::Auto, None, false, false)); let handler = errors::Handler::with_emitter(true, false, emitter); // a .span_bug or .bug call has already printed what // it wants to print. if !value.is::<errors::ExplicitBug>() { handler.emit(&MultiSpan::new(), "unexpected panic", errors::Level::Bug); } let mut xs: Vec<Cow<'static, str>> = vec![ "the compiler unexpectedly panicked. this is a bug.".into(), format!("we would appreciate a bug report: {}", BUG_REPORT_URL).into(), format!("rustc {} running on {}", option_env!("CFG_VERSION").unwrap_or("unknown_version"), config::host_triple()).into(), ]; if let Some((flags, excluded_cargo_defaults)) = extra_compiler_flags() { xs.push(format!("compiler flags: {}", flags.join(" ")).into()); if excluded_cargo_defaults { xs.push("some of the compiler flags provided by cargo are hidden".into()); } } for note in &xs { handler.emit(&MultiSpan::new(), note, errors::Level::Note); } panic::resume_unwind(Box::new(errors::FatalErrorMarker)); } }) } pub fn diagnostics_registry() -> errors::registry::Registry { use errors::registry::Registry; let mut all_errors = Vec::new(); all_errors.extend_from_slice(&rustc::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_typeck::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_resolve::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_privacy::DIAGNOSTICS); // FIXME: need to figure out a way to get these back in here // all_errors.extend_from_slice(get_codegen_backend(sess).diagnostics()); all_errors.extend_from_slice(&rustc_codegen_utils::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_metadata::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_passes::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_plugin::DIAGNOSTICS); all_errors.extend_from_slice(&rustc_mir::DIAGNOSTICS); all_errors.extend_from_slice(&syntax::DIAGNOSTICS); Registry::new(&all_errors) } /// This allows tools to enable rust logging without having to magically match rustc's /// log crate version pub fn init_rustc_env_logger() { env_logger::init(); } pub fn main() { init_rustc_env_logger(); let result = run(|| { let args = env::args_os().enumerate() .map(|(i, arg)| arg.into_string().unwrap_or_else(|arg| { early_error(ErrorOutputType::default(), &format!("Argument {} is not valid Unicode: {:?}", i, arg)) })) .collect::<Vec<_>>(); run_compiler(&args, Box::new(RustcDefaultCalls), None, None) }); process::exit(result as i32); }
38.014434
100
0.537203
4af89d2148dfc5c0684ccac1abf87af3f120573c
227,258
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /* # check.rs Within the check phase of type check, we check each item one at a time (bodies of function expressions are checked as part of the containing function). Inference is used to supply types wherever they are unknown. By far the most complex case is checking the body of a function. This can be broken down into several distinct phases: - gather: creates type variables to represent the type of each local variable and pattern binding. - main: the main pass does the lion's share of the work: it determines the types of all expressions, resolves methods, checks for most invalid conditions, and so forth. In some cases, where a type is unknown, it may create a type or region variable and use that as the type of an expression. In the process of checking, various constraints will be placed on these type variables through the subtyping relationships requested through the `demand` module. The `infer` module is in charge of resolving those constraints. - regionck: after main is complete, the regionck pass goes over all types looking for regions and making sure that they did not escape into places they are not in scope. This may also influence the final assignments of the various region variables if there is some flexibility. - vtable: find and records the impls to use for each trait bound that appears on a type parameter. - writeback: writes the final types within a function body, replacing type variables with their final inferred types. These final types are written into the `tcx.node_types` table, which should *never* contain any reference to a type variable. ## Intermediate types While type checking a function, the intermediate types for the expressions, blocks, and so forth contained within the function are stored in `fcx.node_types` and `fcx.node_substs`. These types may contain unresolved type variables. After type checking is complete, the functions in the writeback module are used to take the types from this table, resolve them, and then write them into their permanent home in the type context `tcx`. This means that during inferencing you should use `fcx.write_ty()` and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of nodes within the function. The types of top-level items, which never contain unbound type variables, are stored directly into the `tcx` tables. n.b.: A type variable is not the same thing as a type parameter. A type variable is rather an "instance" of a type parameter: that is, given a generic function `fn foo<T>(t: T)`: while checking the function `foo`, the type `ty_param(0)` refers to the type `T`, which is treated in abstract. When `foo()` is called, however, `T` will be substituted for a fresh type variable `N`. This variable will eventually be resolved to some concrete type (which might itself be type parameter). */ pub use self::Expectation::*; use self::autoderef::Autoderef; use self::callee::DeferredCallResolution; use self::coercion::{CoerceMany, DynamicCoerceMany}; pub use self::compare_method::{compare_impl_method, compare_const_impl}; use self::method::MethodCallee; use self::TupleArgumentsFlag::*; use astconv::AstConv; use hir::GenericArg; use hir::def::Def; use hir::def_id::{CrateNum, DefId, LOCAL_CRATE}; use std::slice; use namespace::Namespace; use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin}; use rustc::infer::anon_types::AnonTypeDecl; use rustc::infer::type_variable::{TypeVariableOrigin}; use rustc::middle::region; use rustc::mir::interpret::{GlobalId}; use rustc::ty::subst::{UnpackedKind, Subst, Substs}; use rustc::traits::{self, ObligationCause, ObligationCauseCode, TraitEngine}; use rustc::ty::{self, Ty, TyCtxt, GenericParamDefKind, Visibility, ToPredicate, RegionKind}; use rustc::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability}; use rustc::ty::fold::TypeFoldable; use rustc::ty::query::Providers; use rustc::ty::util::{Representability, IntTypeExt, Discr}; use errors::{DiagnosticBuilder, DiagnosticId}; use require_c_abi_if_variadic; use session::{CompileIncomplete, config, Session}; use TypeAndSubsts; use lint; use util::common::{ErrorReported, indenter}; use util::nodemap::{DefIdMap, DefIdSet, FxHashMap, NodeMap}; use std::cell::{Cell, RefCell, Ref, RefMut}; use rustc_data_structures::sync::Lrc; use std::collections::hash_map::Entry; use std::cmp; use std::fmt::Display; use std::iter; use std::mem::replace; use std::ops::{self, Deref}; use rustc_target::spec::abi::Abi; use syntax::ast; use syntax::attr; use syntax::codemap::original_sp; use syntax::feature_gate::{GateIssue, emit_feature_err}; use syntax::ptr::P; use syntax::symbol::{Symbol, LocalInternedString, keywords}; use syntax::util::lev_distance::find_best_match_for_name; use syntax_pos::{self, BytePos, Span, MultiSpan}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; use rustc::hir::itemlikevisit::ItemLikeVisitor; use rustc::hir::map::Node; use rustc::hir::{self, PatKind, ItemKind}; use rustc::middle::lang_items; mod autoderef; pub mod dropck; pub mod _match; pub mod writeback; mod regionck; pub mod coercion; pub mod demand; pub mod method; mod upvar; mod wfcheck; mod cast; mod closure; mod callee; mod compare_method; mod generator_interior; mod intrinsic; mod op; /// A wrapper for InferCtxt's `in_progress_tables` field. #[derive(Copy, Clone)] struct MaybeInProgressTables<'a, 'tcx: 'a> { maybe_tables: Option<&'a RefCell<ty::TypeckTables<'tcx>>>, } impl<'a, 'tcx> MaybeInProgressTables<'a, 'tcx> { fn borrow(self) -> Ref<'a, ty::TypeckTables<'tcx>> { match self.maybe_tables { Some(tables) => tables.borrow(), None => { bug!("MaybeInProgressTables: inh/fcx.tables.borrow() with no tables") } } } fn borrow_mut(self) -> RefMut<'a, ty::TypeckTables<'tcx>> { match self.maybe_tables { Some(tables) => tables.borrow_mut(), None => { bug!("MaybeInProgressTables: inh/fcx.tables.borrow_mut() with no tables") } } } } /// closures defined within the function. For example: /// /// fn foo() { /// bar(move|| { ... }) /// } /// /// Here, the function `foo()` and the closure passed to /// `bar()` will each have their own `FnCtxt`, but they will /// share the inherited fields. pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { infcx: InferCtxt<'a, 'gcx, 'tcx>, tables: MaybeInProgressTables<'a, 'tcx>, locals: RefCell<NodeMap<Ty<'tcx>>>, fulfillment_cx: RefCell<Box<dyn TraitEngine<'tcx>>>, // When we process a call like `c()` where `c` is a closure type, // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or // `FnOnce` closure. In that case, we defer full resolution of the // call until upvar inference can kick in and make the // decision. We keep these deferred resolutions grouped by the // def-id of the closure, so that once we decide, we can easily go // back and process them. deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolution<'gcx, 'tcx>>>>, deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>, deferred_generator_interiors: RefCell<Vec<(hir::BodyId, Ty<'tcx>)>>, // Anonymized types found in explicit return types and their // associated fresh inference variable. Writeback resolves these // variables to get the concrete type, which can be used to // deanonymize TyAnon, after typeck is done with all functions. anon_types: RefCell<DefIdMap<AnonTypeDecl<'tcx>>>, /// Each type parameter has an implicit region bound that /// indicates it must outlive at least the function body (the user /// may specify stronger requirements). This field indicates the /// region of the callee. If it is `None`, then the parameter /// environment is for an item or something where the "callee" is /// not clear. implicit_region_bound: Option<ty::Region<'tcx>>, body_id: Option<hir::BodyId>, } impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> { type Target = InferCtxt<'a, 'gcx, 'tcx>; fn deref(&self) -> &Self::Target { &self.infcx } } /// When type-checking an expression, we propagate downward /// whatever type hint we are able in the form of an `Expectation`. #[derive(Copy, Clone, Debug)] pub enum Expectation<'tcx> { /// We know nothing about what type this expression should have. NoExpectation, /// This expression is an `if` condition, it must resolve to `bool`. ExpectIfCondition, /// This expression should have the type given (or some subtype) ExpectHasType(Ty<'tcx>), /// This expression will be cast to the `Ty` ExpectCastableToType(Ty<'tcx>), /// This rvalue expression will be wrapped in `&` or `Box` and coerced /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`. ExpectRvalueLikeUnsized(Ty<'tcx>), } impl<'a, 'gcx, 'tcx> Expectation<'tcx> { // Disregard "castable to" expectations because they // can lead us astray. Consider for example `if cond // {22} else {c} as u8` -- if we propagate the // "castable to u8" constraint to 22, it will pick the // type 22u8, which is overly constrained (c might not // be a u8). In effect, the problem is that the // "castable to" expectation is not the tightest thing // we can say, so we want to drop it in this case. // The tightest thing we can say is "must unify with // else branch". Note that in the case of a "has type" // constraint, this limitation does not hold. // If the expected type is just a type variable, then don't use // an expected type. Otherwise, we might write parts of the type // when checking the 'then' block which are incompatible with the // 'else' branch. fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> { match *self { ExpectHasType(ety) => { let ety = fcx.shallow_resolve(ety); if !ety.is_ty_var() { ExpectHasType(ety) } else { NoExpectation } } ExpectRvalueLikeUnsized(ety) => { ExpectRvalueLikeUnsized(ety) } _ => NoExpectation } } /// Provide an expectation for an rvalue expression given an *optional* /// hint, which is not required for type safety (the resulting type might /// be checked higher up, as is the case with `&expr` and `box expr`), but /// is useful in determining the concrete type. /// /// The primary use case is where the expected type is a fat pointer, /// like `&[isize]`. For example, consider the following statement: /// /// let x: &[isize] = &[1, 2, 3]; /// /// In this case, the expected type for the `&[1, 2, 3]` expression is /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the /// expectation `ExpectHasType([isize])`, that would be too strong -- /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`. /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced /// to the type `&[isize]`. Therefore, we propagate this more limited hint, /// which still is useful, because it informs integer literals and the like. /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169 /// for examples of where this comes up,. fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> { match fcx.tcx.struct_tail(ty).sty { ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => { ExpectRvalueLikeUnsized(ty) } _ => ExpectHasType(ty) } } // Resolves `expected` by a single level if it is a variable. If // there is no expected type or resolution is not possible (e.g., // no constraints yet present), just returns `None`. fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> { match self { NoExpectation => NoExpectation, ExpectIfCondition => ExpectIfCondition, ExpectCastableToType(t) => { ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t)) } ExpectHasType(t) => { ExpectHasType(fcx.resolve_type_vars_if_possible(&t)) } ExpectRvalueLikeUnsized(t) => { ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t)) } } } fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> { match self.resolve(fcx) { NoExpectation => None, ExpectIfCondition => Some(fcx.tcx.types.bool), ExpectCastableToType(ty) | ExpectHasType(ty) | ExpectRvalueLikeUnsized(ty) => Some(ty), } } /// It sometimes happens that we want to turn an expectation into /// a **hard constraint** (i.e., something that must be satisfied /// for the program to type-check). `only_has_type` will return /// such a constraint, if it exists. fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> { match self.resolve(fcx) { ExpectHasType(ty) => Some(ty), ExpectIfCondition => Some(fcx.tcx.types.bool), NoExpectation | ExpectCastableToType(_) | ExpectRvalueLikeUnsized(_) => None, } } /// Like `only_has_type`, but instead of returning `None` if no /// hard constraint exists, creates a fresh type variable. fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> { self.only_has_type(fcx) .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span))) } } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Needs { MutPlace, None } impl Needs { fn maybe_mut_place(m: hir::Mutability) -> Self { match m { hir::MutMutable => Needs::MutPlace, hir::MutImmutable => Needs::None, } } } #[derive(Copy, Clone)] pub struct UnsafetyState { pub def: ast::NodeId, pub unsafety: hir::Unsafety, pub unsafe_push_count: u32, from_fn: bool } impl UnsafetyState { pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState { UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true } } pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState { match self.unsafety { // If this unsafe, then if the outer function was already marked as // unsafe we shouldn't attribute the unsafe'ness to the block. This // way the block can be warned about instead of ignoring this // extraneous block (functions are never warned about). hir::Unsafety::Unsafe if self.from_fn => *self, unsafety => { let (unsafety, def, count) = match blk.rules { hir::PushUnsafeBlock(..) => (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()), hir::PopUnsafeBlock(..) => (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()), hir::UnsafeBlock(..) => (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count), hir::DefaultBlock => (unsafety, self.def, self.unsafe_push_count), }; UnsafetyState{ def, unsafety, unsafe_push_count: count, from_fn: false } } } } } #[derive(Debug, Copy, Clone)] pub enum PlaceOp { Deref, Index } /// Tracks whether executing a node may exit normally (versus /// return/break/panic, which "diverge", leaving dead code in their /// wake). Tracked semi-automatically (through type variables marked /// as diverging), with some manual adjustments for control-flow /// primitives (approximating a CFG). #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub enum Diverges { /// Potentially unknown, some cases converge, /// others require a CFG to determine them. Maybe, /// Definitely known to diverge and therefore /// not reach the next sibling or its parent. Always, /// Same as `Always` but with a reachability /// warning already emitted WarnedAlways } // Convenience impls for combinig `Diverges`. impl ops::BitAnd for Diverges { type Output = Self; fn bitand(self, other: Self) -> Self { cmp::min(self, other) } } impl ops::BitOr for Diverges { type Output = Self; fn bitor(self, other: Self) -> Self { cmp::max(self, other) } } impl ops::BitAndAssign for Diverges { fn bitand_assign(&mut self, other: Self) { *self = *self & other; } } impl ops::BitOrAssign for Diverges { fn bitor_assign(&mut self, other: Self) { *self = *self | other; } } impl Diverges { fn always(self) -> bool { self >= Diverges::Always } } pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> { may_break: bool, // this is `null` for loops where break with a value is illegal, // such as `while`, `for`, and `while let` coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>, } pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> { stack: Vec<BreakableCtxt<'gcx, 'tcx>>, by_id: NodeMap<usize>, } impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> { fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> { let ix = *self.by_id.get(&target_id).unwrap_or_else(|| { bug!("could not find enclosing breakable with id {}", target_id); }); &mut self.stack[ix] } } pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { body_id: ast::NodeId, /// The parameter environment used for proving trait obligations /// in this function. This can change when we descend into /// closures (as they bring new things into scope), hence it is /// not part of `Inherited` (as of the time of this writing, /// closures do not yet change the environment, but they will /// eventually). param_env: ty::ParamEnv<'tcx>, // Number of errors that had been reported when we started // checking this function. On exit, if we find that *more* errors // have been reported, we will skip regionck and other work that // expects the types within the function to be consistent. err_count_on_creation: usize, ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>, yield_ty: Option<Ty<'tcx>>, ps: RefCell<UnsafetyState>, /// Whether the last checked node generates a divergence (e.g., /// `return` will set this to Always). In general, when entering /// an expression or other node in the tree, the initial value /// indicates whether prior parts of the containing expression may /// have diverged. It is then typically set to `Maybe` (and the /// old value remembered) for processing the subparts of the /// current expression. As each subpart is processed, they may set /// the flag to `Always` etc. Finally, at the end, we take the /// result and "union" it with the original value, so that when we /// return the flag indicates if any subpart of the the parent /// expression (up to and including this part) has diverged. So, /// if you read it after evaluating a subexpression `X`, the value /// you get indicates whether any subexpression that was /// evaluating up to and including `X` diverged. /// /// We currently use this flag only for diagnostic purposes: /// /// - To warn about unreachable code: if, after processing a /// sub-expression but before we have applied the effects of the /// current node, we see that the flag is set to `Always`, we /// can issue a warning. This corresponds to something like /// `foo(return)`; we warn on the `foo()` expression. (We then /// update the flag to `WarnedAlways` to suppress duplicate /// reports.) Similarly, if we traverse to a fresh statement (or /// tail expression) from a `Always` setting, we will issue a /// warning. This corresponds to something like `{return; /// foo();}` or `{return; 22}`, where we would warn on the /// `foo()` or `22`. /// /// An expression represents dead-code if, after checking it, /// the diverges flag is set to something other than `Maybe`. diverges: Cell<Diverges>, /// Whether any child nodes have any type errors. has_errors: Cell<bool>, enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>, inh: &'a Inherited<'a, 'gcx, 'tcx>, } impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> { type Target = Inherited<'a, 'gcx, 'tcx>; fn deref(&self) -> &Self::Target { &self.inh } } /// Helper type of a temporary returned by Inherited::build(...). /// Necessary because we can't write the following bound: /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>). pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>, def_id: DefId, } impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> { pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId) -> InheritedBuilder<'a, 'gcx, 'tcx> { let hir_id_root = if def_id.is_local() { let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); let hir_id = tcx.hir.definitions().node_to_hir_id(node_id); DefId::local(hir_id.owner) } else { def_id }; InheritedBuilder { infcx: tcx.infer_ctxt().with_fresh_in_progress_tables(hir_id_root), def_id, } } } impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> { fn enter<F, R>(&'tcx mut self, f: F) -> R where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R { let def_id = self.def_id; self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id))) } } impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> { fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self { let tcx = infcx.tcx; let item_id = tcx.hir.as_local_node_id(def_id); let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id)); let implicit_region_bound = body_id.map(|body_id| { let body = tcx.hir.body(body_id); tcx.mk_region(ty::ReScope(region::Scope::CallSite(body.value.hir_id.local_id))) }); Inherited { tables: MaybeInProgressTables { maybe_tables: infcx.in_progress_tables, }, infcx, fulfillment_cx: RefCell::new(TraitEngine::new(tcx)), locals: RefCell::new(NodeMap()), deferred_call_resolutions: RefCell::new(DefIdMap()), deferred_cast_checks: RefCell::new(Vec::new()), deferred_generator_interiors: RefCell::new(Vec::new()), anon_types: RefCell::new(DefIdMap()), implicit_region_bound, body_id, } } fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) { debug!("register_predicate({:?})", obligation); if obligation.has_escaping_regions() { span_bug!(obligation.cause.span, "escaping regions in predicate {:?}", obligation); } self.fulfillment_cx .borrow_mut() .register_predicate_obligation(self, obligation); } fn register_predicates<I>(&self, obligations: I) where I: IntoIterator<Item = traits::PredicateObligation<'tcx>> { for obligation in obligations { self.register_predicate(obligation); } } fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T { self.register_predicates(infer_ok.obligations); infer_ok.value } fn normalize_associated_types_in<T>(&self, span: Span, body_id: ast::NodeId, param_env: ty::ParamEnv<'tcx>, value: &T) -> T where T : TypeFoldable<'tcx> { let ok = self.partially_normalize_associated_types_in(span, body_id, param_env, value); self.register_infer_ok_obligations(ok) } } struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> } impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> { fn visit_item(&mut self, i: &'tcx hir::Item) { check_item_type(self.tcx, i); } fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { } fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { } } pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { tcx.sess.track_errors(|| { let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx); tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor()); }) } pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), ErrorReported> { tcx.sess.track_errors(|| { tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx }); }) } pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Result<(), CompileIncomplete> { tcx.typeck_item_bodies(LOCAL_CRATE) } fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> Result<(), CompileIncomplete> { debug_assert!(crate_num == LOCAL_CRATE); Ok(tcx.sess.track_errors(|| { tcx.par_body_owners(|body_owner_def_id| { ty::query::queries::typeck_tables_of::ensure(tcx, body_owner_def_id); }); })?) } fn check_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) { wfcheck::check_item_well_formed(tcx, def_id); } fn check_trait_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) { wfcheck::check_trait_item(tcx, def_id); } fn check_impl_item_well_formed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) { wfcheck::check_impl_item(tcx, def_id); } pub fn provide(providers: &mut Providers) { method::provide(providers); *providers = Providers { typeck_item_bodies, typeck_tables_of, has_typeck_tables, adt_destructor, used_trait_imports, check_item_well_formed, check_trait_item_well_formed, check_impl_item_well_formed, ..*providers }; } fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Option<ty::Destructor> { tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl) } /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))` /// with information about it's body-id and fn-decl (if any). Otherwise, /// returns `None`. /// /// If this function returns "some", then `typeck_tables(def_id)` will /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or /// may not succeed. In some cases where this function returns `None` /// (notably closures), `typeck_tables(def_id)` would wind up /// redirecting to the owning function. fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: ast::NodeId) -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)> { match tcx.hir.get(id) { hir::map::NodeItem(item) => { match item.node { hir::ItemKind::Const(_, body) | hir::ItemKind::Static(_, _, body) => Some((body, None)), hir::ItemKind::Fn(ref decl, .., body) => Some((body, Some(decl))), _ => None, } } hir::map::NodeTraitItem(item) => { match item.node { hir::TraitItemKind::Const(_, Some(body)) => Some((body, None)), hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => Some((body, Some(&sig.decl))), _ => None, } } hir::map::NodeImplItem(item) => { match item.node { hir::ImplItemKind::Const(_, body) => Some((body, None)), hir::ImplItemKind::Method(ref sig, body) => Some((body, Some(&sig.decl))), _ => None, } } hir::map::NodeAnonConst(constant) => Some((constant.body, None)), _ => None, } } fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { return tcx.has_typeck_tables(outer_def_id); } let id = tcx.hir.as_local_node_id(def_id).unwrap(); primary_body_of(tcx, id).is_some() } fn used_trait_imports<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Lrc<DefIdSet> { tcx.typeck_tables_of(def_id).used_trait_imports.clone() } fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> &'tcx ty::TypeckTables<'tcx> { // Closures' tables come from their outermost function, // as they are part of the same "inference environment". let outer_def_id = tcx.closure_base_def_id(def_id); if outer_def_id != def_id { return tcx.typeck_tables_of(outer_def_id); } let id = tcx.hir.as_local_node_id(def_id).unwrap(); let span = tcx.hir.span(id); // Figure out what primary body this item has. let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| { span_bug!(span, "can't type-check body of {:?}", def_id); }); let body = tcx.hir.body(body_id); let tables = Inherited::build(tcx, def_id).enter(|inh| { let param_env = tcx.param_env(def_id); let fcx = if let Some(decl) = fn_decl { let fn_sig = tcx.fn_sig(def_id); check_abi(tcx, span, fn_sig.abi()); // Compute the fty from point of view of inside fn. let fn_sig = tcx.liberate_late_bound_regions(def_id, &fn_sig); let fn_sig = inh.normalize_associated_types_in(body.value.span, body_id.node_id, param_env, &fn_sig); let fcx = check_fn(&inh, param_env, fn_sig, decl, id, body, None).0; fcx } else { let fcx = FnCtxt::new(&inh, param_env, body.value.id); let expected_type = tcx.type_of(def_id); let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type); fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized); // Gather locals in statics (because of block expressions). // This is technically unnecessary because locals in static items are forbidden, // but prevents type checking from blowing up before const checking can properly // emit an error. GatherLocalsVisitor { fcx: &fcx }.visit_body(body); fcx.check_expr_coercable_to_type(&body.value, expected_type); fcx }; // All type checking constraints were added, try to fallback unsolved variables. fcx.select_obligations_where_possible(false); let mut fallback_has_occurred = false; for ty in &fcx.unsolved_variables() { fallback_has_occurred |= fcx.fallback_if_possible(ty); } fcx.select_obligations_where_possible(fallback_has_occurred); // Even though coercion casts provide type hints, we check casts after fallback for // backwards compatibility. This makes fallback a stronger type hint than a cast coercion. fcx.check_casts(); // Closure and generater analysis may run after fallback // because they don't constrain other type variables. fcx.closure_analyze(body); assert!(fcx.deferred_call_resolutions.borrow().is_empty()); fcx.resolve_generator_interiors(def_id); fcx.select_all_obligations_or_error(); if fn_decl.is_some() { fcx.regionck_fn(id, body); } else { fcx.regionck_expr(body); } fcx.resolve_type_vars_in_body(body) }); // Consistency check our TypeckTables instance can hold all ItemLocalIds // it will need to hold. assert_eq!(tables.local_id_root, Some(DefId::local(tcx.hir.definitions().node_to_hir_id(id).owner))); tables } fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) { if !tcx.sess.target.target.is_abi_supported(abi) { struct_span_err!(tcx.sess, span, E0570, "The ABI `{}` is not supported for the current target", abi).emit() } } struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> { fcx: &'a FnCtxt<'a, 'gcx, 'tcx> } impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> { fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> { match ty_opt { None => { // infer the variable's type let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span)); self.fcx.locals.borrow_mut().insert(nid, var_ty); var_ty } Some(typ) => { // take type that the user specified self.fcx.locals.borrow_mut().insert(nid, typ); typ } } } } impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> { fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> { NestedVisitorMap::None } // Add explicitly-declared locals. fn visit_local(&mut self, local: &'gcx hir::Local) { let o_ty = match local.ty { Some(ref ty) => { let o_ty = self.fcx.to_ty(&ty); let c_ty = self.fcx.inh.infcx.canonicalize_response(&o_ty); debug!("visit_local: ty.hir_id={:?} o_ty={:?} c_ty={:?}", ty.hir_id, o_ty, c_ty); self.fcx.tables.borrow_mut().user_provided_tys_mut().insert(ty.hir_id, c_ty); Some(o_ty) }, None => None, }; self.assign(local.span, local.id, o_ty); debug!("Local variable {:?} is assigned type {}", local.pat, self.fcx.ty_to_string( self.fcx.locals.borrow().get(&local.id).unwrap().clone())); intravisit::walk_local(self, local); } // Add pattern bindings. fn visit_pat(&mut self, p: &'gcx hir::Pat) { if let PatKind::Binding(_, _, ident, _) = p.node { let var_ty = self.assign(p.span, p.id, None); self.fcx.require_type_is_sized(var_ty, p.span, traits::VariableType(p.id)); debug!("Pattern binding {} is assigned to {} with type {:?}", ident, self.fcx.ty_to_string( self.fcx.locals.borrow().get(&p.id).unwrap().clone()), var_ty); } intravisit::walk_pat(self, p); } // Don't descend into the bodies of nested closures fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl, _: hir::BodyId, _: Span, _: ast::NodeId) { } } /// When `check_fn` is invoked on a generator (i.e., a body that /// includes yield), it returns back some information about the yield /// points. struct GeneratorTypes<'tcx> { /// Type of value that is yielded. yield_ty: ty::Ty<'tcx>, /// Types that are captured (see `GeneratorInterior` for more). interior: ty::Ty<'tcx>, /// Indicates if the generator is movable or static (immovable) movability: hir::GeneratorMovability, } /// 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) fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>, param_env: ty::ParamEnv<'tcx>, fn_sig: ty::FnSig<'tcx>, decl: &'gcx hir::FnDecl, fn_id: ast::NodeId, body: &'gcx hir::Body, can_be_generator: Option<hir::GeneratorMovability>) -> (FnCtxt<'a, 'gcx, 'tcx>, Option<GeneratorTypes<'tcx>>) { let mut fn_sig = fn_sig.clone(); debug!("check_fn(sig={:?}, fn_id={}, param_env={:?})", fn_sig, fn_id, param_env); // 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.id); *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id); let declared_ret_ty = fn_sig.output(); fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); let revealed_ret_ty = fcx.instantiate_anon_types_from_return_value(fn_id, &declared_ret_ty); fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(revealed_ret_ty))); fn_sig = fcx.tcx.mk_fn_sig( fn_sig.inputs().iter().cloned(), revealed_ret_ty, fn_sig.variadic, fn_sig.unsafety, fn_sig.abi ); let span = body.value.span; if body.is_generator && can_be_generator.is_some() { let yield_ty = fcx.next_ty_var(TypeVariableOrigin::TypeInference(span)); fcx.require_type_is_sized(yield_ty, span, traits::SizedYieldType); fcx.yield_ty = Some(yield_ty); } GatherLocalsVisitor { fcx: &fcx, }.visit_body(body); // Add formal parameters. for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) { // Check the pattern. fcx.check_pat_walk(&arg.pat, arg_ty, ty::BindingMode::BindByValue(hir::Mutability::MutImmutable), true); // 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 arg.pat.simple_ident().is_none() { fcx.require_type_is_sized(arg_ty, decl.output.span(), traits::MiscObligation); } fcx.write_ty(arg.hir_id, arg_ty); } let fn_hir_id = fcx.tcx.hir.node_to_hir_id(fn_id); inherited.tables.borrow_mut().liberated_fn_sigs_mut().insert(fn_hir_id, fn_sig); fcx.check_return_expr(&body.value); // 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 can_be_generator.is_some() && body.is_generator { let interior = fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)); fcx.deferred_generator_interiors.borrow_mut().push((body.id(), interior)); Some(GeneratorTypes { yield_ty: fcx.yield_ty.unwrap(), 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. // // However, the behavior around `!` is sort of complex. In the // event that the `actual_return_ty` comes back as `!`, that // indicates that the fn either does not return or "returns" only // values of type `!`. In this case, if there is an expected // return type that is *not* `!`, that should be ok. But if the // return type is being inferred, we want to "fallback" to `!`: // // let x = move || panic!(); // // To allow for that, I am creating a type variable with diverging // fallback. This was deemed ever so slightly better than unifying // the return value with `!` because it allows for the caller to // make more assumptions about the return type (e.g., they could do // // let y: Option<u32> = Some(x()); // // which would then cause this return type to become `u32`, not // `!`). let coercion = fcx.ret_coercion.take().unwrap().into_inner(); let mut actual_return_ty = coercion.complete(&fcx); if actual_return_ty.is_never() { actual_return_ty = fcx.next_diverging_ty_var( TypeVariableOrigin::DivergingFn(span)); } fcx.demand_suptype(span, revealed_ret_ty, actual_return_ty); // Check that the main return type implements the termination trait. if let Some(term_id) = fcx.tcx.lang_items().termination() { if let Some((id, _, entry_type)) = *fcx.tcx.sess.entry_fn.borrow() { if id == fn_id { match entry_type { config::EntryMain => { let substs = fcx.tcx.mk_substs_trait(declared_ret_ty, &[]); let trait_ref = ty::TraitRef::new(term_id, substs); let return_ty_span = decl.output.span(); let cause = traits::ObligationCause::new( return_ty_span, fn_id, ObligationCauseCode::MainFunctionType); inherited.register_predicate( traits::Obligation::new( cause, param_env, trait_ref.to_predicate())); }, config::EntryStart => {}, } } } } // Check that a function marked as `#[panic_implementation]` has signature `fn(&PanicInfo) -> !` if let Some(panic_impl_did) = fcx.tcx.lang_items().panic_impl() { if panic_impl_did == fcx.tcx.hir.local_def_id(fn_id) { if let Some(panic_info_did) = fcx.tcx.lang_items().panic_info() { if declared_ret_ty.sty != ty::TyNever { fcx.tcx.sess.span_err( decl.output.span(), "return type should be `!`", ); } let inputs = fn_sig.inputs(); let span = fcx.tcx.hir.span(fn_id); if inputs.len() == 1 { let arg_is_panic_info = match inputs[0].sty { ty::TyRef(region, ty, mutbl) => match ty.sty { ty::TyAdt(ref adt, _) => { adt.did == panic_info_did && mutbl == hir::Mutability::MutImmutable && *region != RegionKind::ReStatic }, _ => false, }, _ => false, }; if !arg_is_panic_info { fcx.tcx.sess.span_err( decl.inputs[0].span, "argument should be `&PanicInfo`", ); } if let Node::NodeItem(item) = fcx.tcx.hir.get(fn_id) { if let ItemKind::Fn(_, _, ref generics, _) = item.node { if !generics.params.is_empty() { fcx.tcx.sess.span_err( span, "`#[panic_implementation]` function should have no type \ parameters", ); } } } } else { fcx.tcx.sess.span_err(span, "function should have one argument"); } } else { fcx.tcx.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) = fcx.tcx.lang_items().oom() { if alloc_error_handler_did == fcx.tcx.hir.local_def_id(fn_id) { if let Some(alloc_layout_did) = fcx.tcx.lang_items().alloc_layout() { if declared_ret_ty.sty != ty::TyNever { fcx.tcx.sess.span_err( decl.output.span(), "return type should be `!`", ); } let inputs = fn_sig.inputs(); let span = fcx.tcx.hir.span(fn_id); if inputs.len() == 1 { let arg_is_alloc_layout = match inputs[0].sty { ty::TyAdt(ref adt, _) => { adt.did == alloc_layout_did }, _ => false, }; if !arg_is_alloc_layout { fcx.tcx.sess.span_err( decl.inputs[0].span, "argument should be `Layout`", ); } if let Node::NodeItem(item) = fcx.tcx.hir.get(fn_id) { if let ItemKind::Fn(_, _, ref generics, _) = item.node { if !generics.params.is_empty() { fcx.tcx.sess.span_err( span, "`#[alloc_error_handler]` function should have no type \ parameters", ); } } } } else { fcx.tcx.sess.span_err(span, "function should have one argument"); } } else { fcx.tcx.sess.err("language item required, but not found: `alloc_layout`"); } } } (fcx, gen_ty) } fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: ast::NodeId, span: Span) { let def_id = tcx.hir.local_def_id(id); 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_id); check_packed(tcx, span, def_id); } fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, id: ast::NodeId, span: Span) { let def_id = tcx.hir.local_def_id(id); let def = tcx.adt_def(def_id); def.destructor(tcx); // force the destructor to be evaluated check_representable(tcx, span, def_id); check_packed(tcx, span, def_id); } pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) { debug!("check_item_type(it.id={}, it.name={})", it.id, tcx.item_path_str(tcx.hir.local_def_id(it.id))); let _indenter = indenter(); match it.node { // Consts can play a role in type-checking, so they are included here. hir::ItemKind::Static(..) => { let def_id = tcx.hir.local_def_id(it.id); tcx.typeck_tables_of(def_id); maybe_check_static_with_link_section(tcx, def_id, it.span); } hir::ItemKind::Const(..) => { tcx.typeck_tables_of(tcx.hir.local_def_id(it.id)); } hir::ItemKind::Enum(ref enum_definition, _) => { check_enum(tcx, it.span, &enum_definition.variants, it.id); } hir::ItemKind::Fn(..) => {} // entirely within check_item_body hir::ItemKind::Impl(.., ref impl_item_refs) => { debug!("ItemKind::Impl {} with id {}", it.name, it.id); let impl_def_id = tcx.hir.local_def_id(it.id); if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) { check_impl_items_against_trait(tcx, it.span, impl_def_id, impl_trait_ref, impl_item_refs); let trait_def_id = impl_trait_ref.def_id; check_on_unimplemented(tcx, trait_def_id, it); } } hir::ItemKind::Trait(..) => { let def_id = tcx.hir.local_def_id(it.id); check_on_unimplemented(tcx, def_id, it); } hir::ItemKind::Struct(..) => { check_struct(tcx, it.id, it.span); } hir::ItemKind::Union(..) => { check_union(tcx, it.id, it.span); } hir::ItemKind::Existential(..) | hir::ItemKind::Ty(..) => { let def_id = tcx.hir.local_def_id(it.id); let pty_ty = tcx.type_of(def_id); let generics = tcx.generics_of(def_id); check_bounds_are_used(tcx, &generics, pty_ty); } hir::ItemKind::ForeignMod(ref m) => { check_abi(tcx, it.span, m.abi); if m.abi == Abi::RustIntrinsic { for item in &m.items { intrinsic::check_intrinsic_type(tcx, item); } } else if m.abi == Abi::PlatformIntrinsic { for item in &m.items { intrinsic::check_platform_intrinsic_type(tcx, item); } } else { for item in &m.items { let generics = tcx.generics_of(tcx.hir.local_def_id(item.id)); if generics.params.len() - generics.own_counts().lifetimes != 0 { let mut err = struct_span_err!(tcx.sess, item.span, E0044, "foreign items may not have type parameters"); err.span_label(item.span, "can't have type parameters"); // FIXME: once we start storing spans for type arguments, turn this into a // suggestion. err.help("use specialization instead of type parameters by replacing them \ with concrete types like `u32`"); err.emit(); } if let hir::ForeignItemKind::Fn(ref fn_decl, _, _) = item.node { require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span); } } } } _ => {/* nothing to do */ } } } fn maybe_check_static_with_link_section(tcx: TyCtxt, id: DefId, span: Span) { // Only restricted on wasm32 target for now if !tcx.sess.opts.target_triple.triple().starts_with("wasm32") { return } // If `#[link_section]` is missing, then nothing to verify let attrs = tcx.codegen_fn_attrs(id); if attrs.link_section.is_none() { return } // For the wasm32 target statics with #[link_section] are placed into custom // sections of the final output file, but this isn't link custom sections of // other executable formats. Namely we can only embed a list of bytes, // nothing with pointers to anything else or relocations. If any relocation // show up, reject them here. let instance = ty::Instance::mono(tcx, id); let cid = GlobalId { instance, promoted: None }; let param_env = ty::ParamEnv::reveal_all(); if let Ok(static_) = tcx.const_eval(param_env.and(cid)) { let alloc = tcx.const_value_to_allocation(static_); if alloc.relocations.len() != 0 { let msg = "statics with a custom `#[link_section]` must be a \ simple list of bytes on the wasm target with no \ extra levels of indirection such as references"; tcx.sess.span_err(span, msg); } } } fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def_id: DefId, item: &hir::Item) { let item_def_id = tcx.hir.local_def_id(item.id); // an error would be reported if this fails. let _ = traits::OnUnimplementedDirective::of_item(tcx, trait_def_id, item_def_id); } fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_item: &hir::ImplItem, parent_impl: DefId) { let mut err = struct_span_err!( tcx.sess, impl_item.span, E0520, "`{}` specializes an item from a parent `impl`, but \ that item is not marked `default`", impl_item.ident); err.span_label(impl_item.span, format!("cannot specialize default item `{}`", impl_item.ident)); match tcx.span_of_impl(parent_impl) { Ok(span) => { err.span_label(span, "parent `impl` is here"); err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`", impl_item.ident)); } Err(cname) => { err.note(&format!("parent implementation is in crate `{}`", cname)); } } err.emit(); } fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def: &ty::TraitDef, trait_item: &ty::AssociatedItem, impl_id: DefId, impl_item: &hir::ImplItem) { let ancestors = trait_def.ancestors(tcx, impl_id); let kind = match impl_item.node { hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const, hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method, hir::ImplItemKind::Existential(..) => ty::AssociatedKind::Existential, hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type }; let parent = ancestors.defs(tcx, trait_item.ident, kind, trait_def.def_id).skip(1).next() .map(|node_item| node_item.map(|parent| parent.defaultness)); if let Some(parent) = parent { if tcx.impl_item_is_final(&parent) { report_forbidden_specialization(tcx, impl_item, parent.node.def_id()); } } } fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, impl_span: Span, impl_id: DefId, impl_trait_ref: ty::TraitRef<'tcx>, impl_item_refs: &[hir::ImplItemRef]) { let impl_span = tcx.sess.codemap().def_span(impl_span); // 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; } // Locate trait definition and items let trait_def = tcx.trait_def(impl_trait_ref.def_id); let mut overridden_associated_type = None; let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id)); // Check existing impl methods to see if they are both present in trait // and compatible with trait signature for impl_item in impl_items() { let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id)); let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id) .find(|ac| Namespace::from(&impl_item.node) == Namespace::from(ac.kind) && tcx.hygienic_eq(ty_impl_item.ident, ac.ident, impl_trait_ref.def_id)) .or_else(|| { // Not compatible, but needed for the error message tcx.associated_items(impl_trait_ref.def_id) .find(|ac| tcx.hygienic_eq(ty_impl_item.ident, ac.ident, impl_trait_ref.def_id)) }); // Check that impl definition matches trait definition if let Some(ty_trait_item) = ty_trait_item { match impl_item.node { hir::ImplItemKind::Const(..) => { // Find associated const definition. if ty_trait_item.kind == ty::AssociatedKind::Const { compare_const_impl(tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref); } else { let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323, "item `{}` is an associated const, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref); err.span_label(impl_item.span, "does not match trait"); // We can only get the spans from local trait definition // Same for E0324 and E0325 if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) { err.span_label(trait_span, "item in trait"); } err.emit() } } hir::ImplItemKind::Method(..) => { let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id); if ty_trait_item.kind == ty::AssociatedKind::Method { compare_impl_method(tcx, &ty_impl_item, impl_item.span, &ty_trait_item, impl_trait_ref, trait_span); } else { let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324, "item `{}` is an associated method, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref); err.span_label(impl_item.span, "does not match trait"); if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) { err.span_label(trait_span, "item in trait"); } err.emit() } } hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(_) => { if ty_trait_item.kind == ty::AssociatedKind::Type { if ty_trait_item.defaultness.has_value() { overridden_associated_type = Some(impl_item); } } else { let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325, "item `{}` is an associated type, \ which doesn't match its trait `{}`", ty_impl_item.ident, impl_trait_ref); err.span_label(impl_item.span, "does not match trait"); if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) { err.span_label(trait_span, "item in trait"); } err.emit() } } } check_specialization_validity(tcx, trait_def, &ty_trait_item, impl_id, impl_item); } } // Check for missing items from trait let mut missing_items = Vec::new(); let mut invalidated_items = Vec::new(); let associated_type_overridden = overridden_associated_type.is_some(); for trait_item in tcx.associated_items(impl_trait_ref.def_id) { let is_implemented = trait_def.ancestors(tcx, impl_id) .defs(tcx, trait_item.ident, trait_item.kind, impl_trait_ref.def_id) .next() .map(|node_item| !node_item.node.is_from_trait()) .unwrap_or(false); if !is_implemented && !tcx.impl_is_default(impl_id) { if !trait_item.defaultness.has_value() { missing_items.push(trait_item); } else if associated_type_overridden { invalidated_items.push(trait_item.ident); } } } if !missing_items.is_empty() { let mut err = struct_span_err!(tcx.sess, impl_span, E0046, "not all trait items implemented, missing: `{}`", missing_items.iter() .map(|trait_item| trait_item.ident.to_string()) .collect::<Vec<_>>().join("`, `")); err.span_label(impl_span, format!("missing `{}` in implementation", missing_items.iter() .map(|trait_item| trait_item.ident.to_string()) .collect::<Vec<_>>().join("`, `"))); for trait_item in missing_items { if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) { err.span_label(span, format!("`{}` from trait", trait_item.ident)); } else { err.note_trait_signature(trait_item.ident.to_string(), trait_item.signature(&tcx)); } } err.emit(); } if !invalidated_items.is_empty() { let invalidator = overridden_associated_type.unwrap(); span_err!(tcx.sess, invalidator.span, E0399, "the following trait items need to be reimplemented \ as `{}` was overridden: `{}`", invalidator.ident, invalidated_items.iter() .map(|name| name.to_string()) .collect::<Vec<_>>().join("`, `")) } } /// 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. fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, item_def_id: DefId) -> 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 rty.is_representable(tcx, sp) { Representability::SelfRecursive(spans) => { let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id); for span in spans { err.span_label(span, "recursive without indirection"); } err.emit(); return false } Representability::Representable | Representability::ContainsRecursive => (), } return true } pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) { let t = tcx.type_of(def_id); match t.sty { ty::TyAdt(def, substs) if def.is_struct() => { let fields = &def.non_enum_variant().fields; if fields.is_empty() { span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty"); 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; } match e.sty { ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ } _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ } _ => { span_err!(tcx.sess, sp, E0077, "SIMD vector element type should be machine type"); return; } } } _ => () } } fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) { let repr = tcx.adt_def(def_id).repr; if repr.packed() { for attr in tcx.get_attrs(def_id).iter() { for r in attr::find_repr_attrs(tcx.sess.diagnostic(), attr) { if let attr::ReprPacked(pack) = r { if pack != repr.pack { struct_span_err!(tcx.sess, sp, E0634, "type has conflicting packed representation hints").emit(); } } } } if repr.align > 0 { struct_span_err!(tcx.sess, sp, E0587, "type has conflicting packed and align representation hints").emit(); } else if check_packed_inner(tcx, def_id, &mut Vec::new()) { struct_span_err!(tcx.sess, sp, E0588, "packed type cannot transitively contain a `[repr(align)]` type").emit(); } } } fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId, stack: &mut Vec<DefId>) -> bool { let t = tcx.type_of(def_id); if stack.contains(&def_id) { debug!("check_packed_inner: {:?} is recursive", t); return false; } match t.sty { ty::TyAdt(def, substs) if def.is_struct() || def.is_union() => { if tcx.adt_def(def.did).repr.align > 0 { return true; } // push struct def_id before checking fields stack.push(def_id); for field in &def.non_enum_variant().fields { let f = field.ty(tcx, substs); match f.sty { ty::TyAdt(def, _) => { if check_packed_inner(tcx, def.did, stack) { return true; } } _ => () } } // only need to pop if not early out stack.pop(); } _ => () } false } fn check_transparent<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) { let adt = tcx.adt_def(def_id); if !adt.repr.transparent() { return; } // For each field, figure out if it's known to be a ZST and align(1) let field_infos: Vec<_> = adt.non_enum_variant().fields.iter().map(|field| { let ty = field.ty(tcx, Substs::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(|layout| layout.is_zst()).unwrap_or(false); let align1 = layout.map(|layout| layout.align.abi() == 1).unwrap_or(false); (span, zst, align1) }).collect(); let non_zst_fields = field_infos.iter().filter(|(_span, zst, _align1)| !*zst); let non_zst_count = non_zst_fields.clone().count(); if non_zst_count != 1 { let field_spans: Vec<_> = non_zst_fields.map(|(span, _zst, _align1)| *span).collect(); struct_span_err!(tcx.sess, sp, E0690, "transparent struct needs exactly one non-zero-sized field, but has {}", non_zst_count) .span_note(field_spans, "non-zero-sized field") .emit(); } for &(span, zst, align1) in &field_infos { if zst && !align1 { span_err!(tcx.sess, span, E0691, "zero-sized field in transparent struct has alignment larger than 1"); } } } #[allow(trivial_numeric_casts)] pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, vs: &'tcx [hir::Variant], id: ast::NodeId) { let def_id = tcx.hir.local_def_id(id); 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); if let Some(attr) = attr::find_by_name(&attributes, "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 { emit_feature_err(&tcx.sess.parse_sess, "repr128", sp, GateIssue::Language, "repr with 128-bit type is unstable"); } } for v in vs { if let Some(ref e) = v.node.disr_expr { tcx.typeck_tables_of(tcx.hir.local_def_id(e.id)); } } let mut disr_vals: Vec<Discr<'tcx>> = Vec::new(); for (discr, v) in def.discriminants(tcx).zip(vs) { // Check for duplicate discriminant values if let Some(i) = disr_vals.iter().position(|&x| x.val == discr.val) { let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap(); let variant_i = tcx.hir.expect_variant(variant_i_node_id); let i_span = match variant_i.node.disr_expr { Some(ref expr) => tcx.hir.span(expr.id), None => tcx.hir.span(variant_i_node_id) }; let span = match v.node.disr_expr { Some(ref expr) => tcx.hir.span(expr.id), None => v.span }; struct_span_err!(tcx.sess, span, E0081, "discriminant value `{}` already exists", disr_vals[i]) .span_label(i_span, format!("first use of `{}`", disr_vals[i])) .span_label(span , format!("enum already has `{}`", disr_vals[i])) .emit(); } disr_vals.push(discr); } check_representable(tcx, sp, def_id); } impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> { fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx } fn get_type_parameter_bounds(&self, _: Span, def_id: DefId) -> ty::GenericPredicates<'tcx> { let tcx = self.tcx; let node_id = tcx.hir.as_local_node_id(def_id).unwrap(); let item_id = tcx.hir.ty_param_owner(node_id); let item_def_id = tcx.hir.local_def_id(item_id); let generics = tcx.generics_of(item_def_id); let index = generics.param_def_id_to_index[&def_id]; ty::GenericPredicates { parent: None, predicates: self.param_env.caller_bounds.iter().filter(|predicate| { match **predicate { ty::Predicate::Trait(ref data) => { data.skip_binder().self_ty().is_param(index) } _ => false } }).cloned().collect() } } fn re_infer(&self, span: Span, def: Option<&ty::GenericParamDef>) -> Option<ty::Region<'tcx>> { let v = match def { Some(def) => infer::EarlyBoundRegion(span, def.name), None => infer::MiscVariable(span) }; Some(self.next_region_var(v)) } fn ty_infer(&self, span: Span) -> Ty<'tcx> { self.next_ty_var(TypeVariableOrigin::TypeInference(span)) } fn ty_infer_for_def(&self, ty_param_def: &ty::GenericParamDef, span: Span) -> Ty<'tcx> { if let UnpackedKind::Type(ty) = self.var_for_def(span, ty_param_def).unpack() { return ty; } unreachable!() } fn projected_ty_from_poly_trait_ref(&self, span: Span, item_def_id: DefId, poly_trait_ref: ty::PolyTraitRef<'tcx>) -> Ty<'tcx> { let (trait_ref, _) = self.replace_late_bound_regions_with_fresh_var( span, infer::LateBoundRegionConversionTime::AssocTypeProjection(item_def_id), &poly_trait_ref); self.tcx().mk_projection(item_def_id, trait_ref.substs) } fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> { if ty.has_escaping_regions() { ty // FIXME: normalization and escaping regions } else { self.normalize_associated_types_in(span, &ty) } } fn set_tainted_by_errors(&self) { self.infcx.set_tainted_by_errors() } fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, _span: Span) { self.write_ty(hir_id, ty) } } /// Controls whether the arguments are tupled. This is used for the call /// operator. /// /// Tupling means that all call-side arguments are packed into a tuple and /// passed as a single parameter. For example, if tupling is enabled, this /// function: /// /// fn f(x: (isize, isize)) /// /// Can be called as: /// /// f(1, 2); /// /// Instead of: /// /// f((1, 2)); #[derive(Clone, Eq, PartialEq)] enum TupleArgumentsFlag { DontTupleArguments, TupleArguments, } impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>, param_env: ty::ParamEnv<'tcx>, body_id: ast::NodeId) -> FnCtxt<'a, 'gcx, 'tcx> { FnCtxt { body_id, param_env, err_count_on_creation: inh.tcx.sess.err_count(), ret_coercion: None, yield_ty: None, ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal, ast::CRATE_NODE_ID)), diverges: Cell::new(Diverges::Maybe), has_errors: Cell::new(false), enclosing_breakables: RefCell::new(EnclosingBreakables { stack: Vec::new(), by_id: NodeMap(), }), inh, } } pub fn sess(&self) -> &Session { &self.tcx.sess } pub fn err_count_since_creation(&self) -> usize { self.tcx.sess.err_count() - self.err_count_on_creation } /// Produce warning on the given node, if the current point in the /// function is unreachable, and there hasn't been another warning. fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) { if self.diverges.get() == Diverges::Always { self.diverges.set(Diverges::WarnedAlways); debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind); self.tcx().lint_node( lint::builtin::UNREACHABLE_CODE, id, span, &format!("unreachable {}", kind)); } } pub fn cause(&self, span: Span, code: ObligationCauseCode<'tcx>) -> ObligationCause<'tcx> { ObligationCause::new(span, self.body_id, code) } pub fn misc(&self, span: Span) -> ObligationCause<'tcx> { self.cause(span, ObligationCauseCode::MiscObligation) } /// Resolves type variables in `ty` if possible. Unlike the infcx /// version (resolve_type_vars_if_possible), this version will /// also select obligations if it seems useful, in an effort /// to get more type information. fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> { debug!("resolve_type_vars_with_obligations(ty={:?})", ty); // No TyInfer()? Nothing needs doing. if !ty.has_infer_types() { debug!("resolve_type_vars_with_obligations: ty={:?}", ty); return ty; } // If `ty` is a type variable, see whether we already know what it is. ty = self.resolve_type_vars_if_possible(&ty); if !ty.has_infer_types() { debug!("resolve_type_vars_with_obligations: ty={:?}", ty); return ty; } // If not, try resolving pending obligations as much as // possible. This can help substantially when there are // indirect dependencies that don't seem worth tracking // precisely. self.select_obligations_where_possible(false); ty = self.resolve_type_vars_if_possible(&ty); debug!("resolve_type_vars_with_obligations: ty={:?}", ty); ty } fn record_deferred_call_resolution(&self, closure_def_id: DefId, r: DeferredCallResolution<'gcx, 'tcx>) { let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r); } fn remove_deferred_call_resolutions(&self, closure_def_id: DefId) -> Vec<DeferredCallResolution<'gcx, 'tcx>> { let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); deferred_call_resolutions.remove(&closure_def_id).unwrap_or(vec![]) } pub fn tag(&self) -> String { let self_ptr: *const FnCtxt = self; format!("{:?}", self_ptr) } pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> { match self.locals.borrow().get(&nid) { Some(&t) => t, None => { span_bug!(span, "no type for local variable {}", self.tcx.hir.node_to_string(nid)); } } } #[inline] pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) { debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_type_vars_if_possible(&ty), self.tag()); self.tables.borrow_mut().node_types_mut().insert(id, ty); if ty.references_error() { self.has_errors.set(true); self.set_tainted_by_errors(); } } pub fn write_field_index(&self, node_id: ast::NodeId, index: usize) { let hir_id = self.tcx.hir.node_to_hir_id(node_id); self.tables.borrow_mut().field_indices_mut().insert(hir_id, index); } // The NodeId and the ItemLocalId must identify the same item. We just pass // both of them for consistency checking. pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { self.tables .borrow_mut() .type_dependent_defs_mut() .insert(hir_id, Def::Method(method.def_id)); self.write_substs(hir_id, method.substs); } pub fn write_substs(&self, node_id: hir::HirId, substs: &'tcx Substs<'tcx>) { if !substs.is_noop() { debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); self.tables.borrow_mut().node_substs_mut().insert(node_id, substs); } } pub fn apply_adjustments(&self, expr: &hir::Expr, adj: Vec<Adjustment<'tcx>>) { debug!("apply_adjustments(expr={:?}, adj={:?})", expr, adj); if adj.is_empty() { return; } match self.tables.borrow_mut().adjustments_mut().entry(expr.hir_id) { Entry::Vacant(entry) => { entry.insert(adj); }, Entry::Occupied(mut entry) => { debug!(" - composing on top of {:?}", entry.get()); match (&entry.get()[..], &adj[..]) { // Applying any adjustment on top of a NeverToAny // is a valid NeverToAny adjustment, because it can't // be reached. (&[Adjustment { kind: Adjust::NeverToAny, .. }], _) => return, (&[ Adjustment { kind: Adjust::Deref(_), .. }, Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(..)), .. }, ], &[ Adjustment { kind: Adjust::Deref(_), .. }, .. // Any following adjustments are allowed. ]) => { // A reborrow has no effect before a dereference. } // FIXME: currently we never try to compose autoderefs // and ReifyFnPointer/UnsafeFnPointer, but we could. _ => bug!("while adjusting {:?}, can't compose {:?} and {:?}", expr, entry.get(), adj) }; *entry.get_mut() = adj; } } } /// Basically whenever we are converting from a type scheme into /// the fn body space, we always want to normalize associated /// types as well. This function combines the two. fn instantiate_type_scheme<T>(&self, span: Span, substs: &Substs<'tcx>, value: &T) -> T where T : TypeFoldable<'tcx> { let value = value.subst(self.tcx, substs); let result = self.normalize_associated_types_in(span, &value); debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}", value, substs, result); result } /// As `instantiate_type_scheme`, but for the bounds found in a /// generic type scheme. fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>) -> ty::InstantiatedPredicates<'tcx> { let bounds = self.tcx.predicates_of(def_id); let result = bounds.instantiate(self.tcx, substs); let result = self.normalize_associated_types_in(span, &result); debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}", bounds, substs, result); result } /// Replace the anonymized types from the return value of the /// function with type variables and records the `AnonTypeMap` for /// later use during writeback. See /// `InferCtxt::instantiate_anon_types` for more details. fn instantiate_anon_types_from_return_value<T: TypeFoldable<'tcx>>( &self, fn_id: ast::NodeId, value: &T, ) -> T { let fn_def_id = self.tcx.hir.local_def_id(fn_id); debug!( "instantiate_anon_types_from_return_value(fn_def_id={:?}, value={:?})", fn_def_id, value ); let (value, anon_type_map) = self.register_infer_ok_obligations( self.instantiate_anon_types( fn_def_id, self.body_id, self.param_env, value, ) ); let mut anon_types = self.anon_types.borrow_mut(); for (ty, decl) in anon_type_map { let old_value = anon_types.insert(ty, decl); assert!(old_value.is_none(), "instantiated twice: {:?}/{:?}", ty, decl); } value } fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T where T : TypeFoldable<'tcx> { self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value) } fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T) -> InferOk<'tcx, T> where T : TypeFoldable<'tcx> { self.inh.partially_normalize_associated_types_in(span, self.body_id, self.param_env, value) } pub fn require_type_meets(&self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>, def_id: DefId) { self.register_bound( ty, def_id, traits::ObligationCause::new(span, self.body_id, code)); } pub fn require_type_is_sized(&self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>) { let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem); self.require_type_meets(ty, span, code, lang_item); } pub fn register_bound(&self, ty: Ty<'tcx>, def_id: DefId, cause: traits::ObligationCause<'tcx>) { self.fulfillment_cx.borrow_mut() .register_bound(self, self.param_env, ty, def_id, cause); } pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> { let t = AstConv::ast_ty_to_ty(self, ast_t); self.register_wf_obligation(t, ast_t.span, traits::MiscObligation); t } pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { match self.tables.borrow().node_types().get(id) { Some(&t) => t, None if self.is_tainted_by_errors() => self.tcx.types.err, None => { let node_id = self.tcx.hir.hir_to_node_id(id); bug!("no type for node {}: {} in fcx {}", node_id, self.tcx.hir.node_to_string(node_id), self.tag()); } } } /// Registers an obligation for checking later, during regionck, that the type `ty` must /// outlive the region `r`. pub fn register_wf_obligation(&self, ty: Ty<'tcx>, span: Span, code: traits::ObligationCauseCode<'tcx>) { // WF obligations never themselves fail, so no real need to give a detailed cause: let cause = traits::ObligationCause::new(span, self.body_id, code); self.register_predicate(traits::Obligation::new(cause, self.param_env, ty::Predicate::WellFormed(ty))); } /// Registers obligations that all types appearing in `substs` are well-formed. pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr) { for ty in substs.types() { self.register_wf_obligation(ty, expr.span, traits::MiscObligation); } } /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each /// type/region parameter was instantiated (`substs`), creates and registers suitable /// trait/region obligations. /// /// For example, if there is a function: /// /// ``` /// fn foo<'a,T:'a>(...) /// ``` /// /// and a reference: /// /// ``` /// let f = foo; /// ``` /// /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a` /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally. pub fn add_obligations_for_parameters(&self, cause: traits::ObligationCause<'tcx>, predicates: &ty::InstantiatedPredicates<'tcx>) { assert!(!predicates.has_escaping_regions()); debug!("add_obligations_for_parameters(predicates={:?})", predicates); for obligation in traits::predicates_for_generics(cause, self.param_env, predicates) { self.register_predicate(obligation); } } // FIXME(arielb1): use this instead of field.ty everywhere // Only for fields! Returns <none> for methods> // Indifferent to privacy flags pub fn field_ty(&self, span: Span, field: &'tcx ty::FieldDef, substs: &Substs<'tcx>) -> Ty<'tcx> { self.normalize_associated_types_in(span, &field.ty(self.tcx, substs)) } fn check_casts(&self) { let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); for cast in deferred_cast_checks.drain(..) { cast.check(self); } } fn resolve_generator_interiors(&self, def_id: DefId) { let mut generators = self.deferred_generator_interiors.borrow_mut(); for (body_id, interior) in generators.drain(..) { self.select_obligations_where_possible(false); generator_interior::resolve_interior(self, def_id, body_id, interior); } } // Tries to apply a fallback to `ty` if it is an unsolved variable. // Non-numerics get replaced with ! or () (depending on whether // feature(never_type) is enabled, unconstrained ints with i32, // unconstrained floats with f64. // Fallback becomes very dubious if we have encountered type-checking errors. // In that case, fallback to TyError. // The return value indicates whether fallback has occured. fn fallback_if_possible(&self, ty: Ty<'tcx>) -> bool { use rustc::ty::error::UnconstrainedNumeric::Neither; use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat}; assert!(ty.is_ty_infer()); let fallback = match self.type_is_unconstrained_numeric(ty) { _ if self.is_tainted_by_errors() => self.tcx().types.err, UnconstrainedInt => self.tcx.types.i32, UnconstrainedFloat => self.tcx.types.f64, Neither if self.type_var_diverges(ty) => self.tcx.mk_diverging_default(), Neither => return false, }; debug!("default_type_parameters: defaulting `{:?}` to `{:?}`", ty, fallback); self.demand_eqtype(syntax_pos::DUMMY_SP, ty, fallback); true } fn select_all_obligations_or_error(&self) { debug!("select_all_obligations_or_error"); if let Err(errors) = self.fulfillment_cx.borrow_mut().select_all_or_error(&self) { self.report_fulfillment_errors(&errors, self.inh.body_id, false); } } /// Select as many obligations as we can at present. fn select_obligations_where_possible(&self, fallback_has_occurred: bool) { match self.fulfillment_cx.borrow_mut().select_where_possible(self) { Ok(()) => { } Err(errors) => { self.report_fulfillment_errors(&errors, self.inh.body_id, fallback_has_occurred); }, } } fn is_place_expr(&self, expr: &hir::Expr) -> bool { match expr.node { hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) => { match path.def { Def::Local(..) | Def::Upvar(..) | Def::Static(..) | Def::Err => true, _ => false, } } hir::ExprKind::Type(ref e, _) => { self.is_place_expr(e) } hir::ExprKind::Unary(hir::UnDeref, _) | hir::ExprKind::Field(..) | hir::ExprKind::Index(..) => { true } // Partially qualified paths in expressions can only legally // refer to associated items which are always rvalues. hir::ExprKind::Path(hir::QPath::TypeRelative(..)) | hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::Struct(..) | hir::ExprKind::Tup(..) | hir::ExprKind::If(..) | hir::ExprKind::Match(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Block(..) | hir::ExprKind::Repeat(..) | hir::ExprKind::Array(..) | hir::ExprKind::Break(..) | hir::ExprKind::Continue(..) | hir::ExprKind::Ret(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Assign(..) | hir::ExprKind::InlineAsm(..) | hir::ExprKind::AssignOp(..) | hir::ExprKind::Lit(_) | hir::ExprKind::Unary(..) | hir::ExprKind::Box(..) | hir::ExprKind::AddrOf(..) | hir::ExprKind::Binary(..) | hir::ExprKind::Yield(..) | hir::ExprKind::Cast(..) => { false } } } /// For the overloaded place expressions (`*x`, `x[3]`), the trait /// returns a type of `&T`, but the actual type we assign to the /// *expression* is `T`. So this function just peels off the return /// type by one layer to yield `T`. fn make_overloaded_place_return_type(&self, method: MethodCallee<'tcx>) -> ty::TypeAndMut<'tcx> { // extract method return type, which will be &T; let ret_ty = method.sig.output(); // method returns &T, but the type as visible to user is T, so deref ret_ty.builtin_deref(true).unwrap() } fn lookup_indexing(&self, expr: &hir::Expr, base_expr: &'gcx hir::Expr, base_ty: Ty<'tcx>, idx_ty: Ty<'tcx>, needs: Needs) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { // FIXME(#18741) -- this is almost but not quite the same as the // autoderef that normal method probing does. They could likely be // consolidated. let mut autoderef = self.autoderef(base_expr.span, base_ty); let mut result = None; while result.is_none() && autoderef.next().is_some() { result = self.try_index_step(expr, base_expr, &autoderef, needs, idx_ty); } autoderef.finalize(); result } /// To type-check `base_expr[index_expr]`, we progressively autoderef /// (and otherwise adjust) `base_expr`, looking for a type which either /// supports builtin indexing or overloaded indexing. /// This loop implements one step in that search; the autoderef loop /// is implemented by `lookup_indexing`. fn try_index_step(&self, expr: &hir::Expr, base_expr: &hir::Expr, autoderef: &Autoderef<'a, 'gcx, 'tcx>, needs: Needs, index_ty: Ty<'tcx>) -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { let adjusted_ty = autoderef.unambiguous_final_ty(); debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \ index_ty={:?})", expr, base_expr, adjusted_ty, index_ty); for &unsize in &[false, true] { let mut self_ty = adjusted_ty; if unsize { // We only unsize arrays here. if let ty::TyArray(element_ty, _) = adjusted_ty.sty { self_ty = self.tcx.mk_slice(element_ty); } else { continue; } } // If some lookup succeeds, write callee into table and extract index/element // type from the method signature. // If some lookup succeeded, install method in table let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_expr.span)); let method = self.try_overloaded_place_op( expr.span, self_ty, &[input_ty], needs, PlaceOp::Index); let result = method.map(|ok| { debug!("try_index_step: success, using overloaded indexing"); let method = self.register_infer_ok_obligations(ok); let mut adjustments = autoderef.adjust_steps(needs); if let ty::TyRef(region, _, r_mutbl) = method.sig.inputs()[0].sty { let mutbl = match r_mutbl { hir::MutImmutable => AutoBorrowMutability::Immutable, hir::MutMutable => AutoBorrowMutability::Mutable { // Indexing can be desugared to a method call, // so maybe we could use two-phase here. // See the documentation of AllowTwoPhase for why that's // not the case today. allow_two_phase_borrow: AllowTwoPhase::No, } }; adjustments.push(Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)), target: self.tcx.mk_ref(region, ty::TypeAndMut { mutbl: r_mutbl, ty: adjusted_ty }) }); } if unsize { adjustments.push(Adjustment { kind: Adjust::Unsize, target: method.sig.inputs()[0] }); } self.apply_adjustments(base_expr, adjustments); self.write_method_call(expr.hir_id, method); (input_ty, self.make_overloaded_place_return_type(method).ty) }); if result.is_some() { return result; } } None } fn resolve_place_op(&self, op: PlaceOp, is_mut: bool) -> (Option<DefId>, ast::Ident) { let (tr, name) = match (op, is_mut) { (PlaceOp::Deref, false) => (self.tcx.lang_items().deref_trait(), "deref"), (PlaceOp::Deref, true) => (self.tcx.lang_items().deref_mut_trait(), "deref_mut"), (PlaceOp::Index, false) => (self.tcx.lang_items().index_trait(), "index"), (PlaceOp::Index, true) => (self.tcx.lang_items().index_mut_trait(), "index_mut"), }; (tr, ast::Ident::from_str(name)) } fn try_overloaded_place_op(&self, span: Span, base_ty: Ty<'tcx>, arg_tys: &[Ty<'tcx>], needs: Needs, op: PlaceOp) -> Option<InferOk<'tcx, MethodCallee<'tcx>>> { debug!("try_overloaded_place_op({:?},{:?},{:?},{:?})", span, base_ty, needs, op); // Try Mut first, if needed. let (mut_tr, mut_op) = self.resolve_place_op(op, true); let method = match (needs, mut_tr) { (Needs::MutPlace, Some(trait_did)) => { self.lookup_method_in_trait(span, mut_op, trait_did, base_ty, Some(arg_tys)) } _ => None, }; // Otherwise, fall back to the immutable version. let (imm_tr, imm_op) = self.resolve_place_op(op, false); let method = match (method, imm_tr) { (None, Some(trait_did)) => { self.lookup_method_in_trait(span, imm_op, trait_did, base_ty, Some(arg_tys)) } (method, _) => method, }; method } fn check_method_argument_types(&self, sp: Span, expr_sp: Span, method: Result<MethodCallee<'tcx>, ()>, args_no_rcvr: &'gcx [hir::Expr], tuple_arguments: TupleArgumentsFlag, expected: Expectation<'tcx>) -> Ty<'tcx> { let has_error = match method { Ok(method) => { method.substs.references_error() || method.sig.references_error() } Err(_) => true }; if has_error { let err_inputs = self.err_args(args_no_rcvr.len()); let err_inputs = match tuple_arguments { DontTupleArguments => err_inputs, TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..])], }; self.check_argument_types(sp, expr_sp, &err_inputs[..], &[], args_no_rcvr, false, tuple_arguments, None); return self.tcx.types.err; } let method = method.unwrap(); // HACK(eddyb) ignore self in the definition (see above). let expected_arg_tys = self.expected_inputs_for_expected_output( sp, expected, method.sig.output(), &method.sig.inputs()[1..] ); self.check_argument_types(sp, expr_sp, &method.sig.inputs()[1..], &expected_arg_tys[..], args_no_rcvr, method.sig.variadic, tuple_arguments, self.tcx.hir.span_if_local(method.def_id)); method.sig.output() } /// Generic function that factors out common logic from function calls, /// method calls and overloaded operators. fn check_argument_types(&self, sp: Span, expr_sp: Span, fn_inputs: &[Ty<'tcx>], mut expected_arg_tys: &[Ty<'tcx>], args: &'gcx [hir::Expr], variadic: bool, tuple_arguments: TupleArgumentsFlag, def_span: Option<Span>) { let tcx = self.tcx; // Grab the argument types, supplying fresh type variables // if the wrong number of arguments were supplied let supplied_arg_count = if tuple_arguments == DontTupleArguments { args.len() } else { 1 }; // All the input types from the fn signature must outlive the call // so as to validate implied bounds. for &fn_input_ty in fn_inputs { self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation); } let expected_arg_count = fn_inputs.len(); let param_count_error = |expected_count: usize, arg_count: usize, error_code: &str, variadic: bool, sugg_unit: bool| { let mut err = tcx.sess.struct_span_err_with_code(sp, &format!("this function takes {}{} parameter{} but {} parameter{} supplied", if variadic {"at least "} else {""}, expected_count, if expected_count == 1 {""} else {"s"}, arg_count, if arg_count == 1 {" was"} else {"s were"}), DiagnosticId::Error(error_code.to_owned())); if let Some(def_s) = def_span.map(|sp| tcx.sess.codemap().def_span(sp)) { err.span_label(def_s, "defined here"); } if sugg_unit { let sugg_span = tcx.sess.codemap().end_point(expr_sp); // remove closing `)` from the span let sugg_span = sugg_span.shrink_to_lo(); err.span_suggestion( sugg_span, "expected the unit value `()`; create it with empty parentheses", String::from("()")); } else { err.span_label(sp, format!("expected {}{} parameter{}", if variadic {"at least "} else {""}, expected_count, if expected_count == 1 {""} else {"s"})); } err.emit(); }; let formal_tys = if tuple_arguments == TupleArguments { let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]); match tuple_type.sty { ty::TyTuple(arg_types) if arg_types.len() != args.len() => { param_count_error(arg_types.len(), args.len(), "E0057", false, false); expected_arg_tys = &[]; self.err_args(args.len()) } ty::TyTuple(arg_types) => { expected_arg_tys = match expected_arg_tys.get(0) { Some(&ty) => match ty.sty { ty::TyTuple(ref tys) => &tys, _ => &[] }, None => &[] }; arg_types.to_vec() } _ => { span_err!(tcx.sess, sp, E0059, "cannot use call notation; the first type parameter \ for the function trait is neither a tuple nor unit"); expected_arg_tys = &[]; self.err_args(args.len()) } } } else if expected_arg_count == supplied_arg_count { fn_inputs.to_vec() } else if variadic { if supplied_arg_count >= expected_arg_count { fn_inputs.to_vec() } else { param_count_error(expected_arg_count, supplied_arg_count, "E0060", true, false); expected_arg_tys = &[]; self.err_args(supplied_arg_count) } } else { // is the missing argument of type `()`? let sugg_unit = if expected_arg_tys.len() == 1 && supplied_arg_count == 0 { self.resolve_type_vars_if_possible(&expected_arg_tys[0]).is_nil() } else if fn_inputs.len() == 1 && supplied_arg_count == 0 { self.resolve_type_vars_if_possible(&fn_inputs[0]).is_nil() } else { false }; param_count_error(expected_arg_count, supplied_arg_count, "E0061", false, sugg_unit); expected_arg_tys = &[]; self.err_args(supplied_arg_count) }; // If there is no expectation, expect formal_tys. let expected_arg_tys = if !expected_arg_tys.is_empty() { expected_arg_tys } else { &formal_tys }; debug!("check_argument_types: formal_tys={:?}", formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>()); // Check the arguments. // We do this in a pretty awful way: first we typecheck any arguments // that are not closures, then we typecheck the closures. This is so // that we have more information about the types of arguments when we // typecheck the functions. This isn't really the right way to do this. for &check_closures in &[false, true] { debug!("check_closures={}", check_closures); // More awful hacks: before we check argument types, try to do // an "opportunistic" vtable resolution of any trait bounds on // the call. This helps coercions. if check_closures { self.select_obligations_where_possible(false); } // For variadic functions, we don't have a declared type for all of // the arguments hence we only do our usual type checking with // the arguments who's types we do know. let t = if variadic { expected_arg_count } else if tuple_arguments == TupleArguments { args.len() } else { supplied_arg_count }; for (i, arg) in args.iter().take(t).enumerate() { // Warn only for the first loop (the "no closures" one). // Closure arguments themselves can't be diverging, but // a previous argument can, e.g. `foo(panic!(), || {})`. if !check_closures { self.warn_if_unreachable(arg.id, arg.span, "expression"); } let is_closure = match arg.node { hir::ExprKind::Closure(..) => true, _ => false }; if is_closure != check_closures { continue; } debug!("checking the argument"); let formal_ty = formal_tys[i]; // The special-cased logic below has three functions: // 1. Provide as good of an expected type as possible. let expected = Expectation::rvalue_hint(self, expected_arg_tys[i]); let checked_ty = self.check_expr_with_expectation(&arg, expected); // 2. Coerce to the most detailed type that could be coerced // to, which is `expected_ty` if `rvalue_hint` returns an // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise. let coerce_ty = expected.only_has_type(self).unwrap_or(formal_ty); // We're processing function arguments so we definitely want to use // two-phase borrows. self.demand_coerce(&arg, checked_ty, coerce_ty, AllowTwoPhase::Yes); // 3. Relate the expected type and the formal one, // if the expected type was used for the coercion. self.demand_suptype(arg.span, formal_ty, coerce_ty); } } // We also need to make sure we at least write the ty of the other // arguments which we skipped above. if variadic { fn variadic_error<'tcx>(s: &Session, span: Span, t: Ty<'tcx>, cast_ty: &str) { use structured_errors::{VariadicError, StructuredDiagnostic}; VariadicError::new(s, span, t, cast_ty).diagnostic().emit(); } for arg in args.iter().skip(expected_arg_count) { let arg_ty = self.check_expr(&arg); // There are a few types which get autopromoted when passed via varargs // in C but we just error out instead and require explicit casts. let arg_ty = self.structurally_resolved_type(arg.span, arg_ty); match arg_ty.sty { ty::TyFloat(ast::FloatTy::F32) => { variadic_error(tcx.sess, arg.span, arg_ty, "c_double"); } ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => { variadic_error(tcx.sess, arg.span, arg_ty, "c_int"); } ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => { variadic_error(tcx.sess, arg.span, arg_ty, "c_uint"); } ty::TyFnDef(..) => { let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx)); let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty); variadic_error(tcx.sess, arg.span, arg_ty, &format!("{}", ptr_ty)); } _ => {} } } } } fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> { (0..len).map(|_| self.tcx.types.err).collect() } // AST fragment checking fn check_lit(&self, lit: &ast::Lit, expected: Expectation<'tcx>) -> Ty<'tcx> { let tcx = self.tcx; match lit.node { ast::LitKind::Str(..) => tcx.mk_static_str(), ast::LitKind::ByteStr(ref v) => { tcx.mk_imm_ref(tcx.types.re_static, tcx.mk_array(tcx.types.u8, v.len() as u64)) } ast::LitKind::Byte(_) => tcx.types.u8, ast::LitKind::Char(_) => tcx.types.char, ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t), ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t), ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => { let opt_ty = expected.to_option(self).and_then(|ty| { match ty.sty { ty::TyInt(_) | ty::TyUint(_) => Some(ty), ty::TyChar => Some(tcx.types.u8), ty::TyRawPtr(..) => Some(tcx.types.usize), ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize), _ => None } }); opt_ty.unwrap_or_else( || tcx.mk_int_var(self.next_int_var_id())) } ast::LitKind::Float(_, t) => tcx.mk_mach_float(t), ast::LitKind::FloatUnsuffixed(_) => { let opt_ty = expected.to_option(self).and_then(|ty| { match ty.sty { ty::TyFloat(_) => Some(ty), _ => None } }); opt_ty.unwrap_or_else( || tcx.mk_float_var(self.next_float_var_id())) } ast::LitKind::Bool(_) => tcx.types.bool } } fn check_expr_eq_type(&self, expr: &'gcx hir::Expr, expected: Ty<'tcx>) { let ty = self.check_expr_with_hint(expr, expected); self.demand_eqtype(expr.span, expected, ty); } pub fn check_expr_has_type_or_error(&self, expr: &'gcx hir::Expr, expected: Ty<'tcx>) -> Ty<'tcx> { self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected)) } fn check_expr_meets_expectation_or_error(&self, expr: &'gcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> { let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool); let mut ty = self.check_expr_with_expectation(expr, expected); // While we don't allow *arbitrary* coercions here, we *do* allow // coercions from ! to `expected`. if ty.is_never() { assert!(!self.tables.borrow().adjustments().contains_key(expr.hir_id), "expression with never type wound up being adjusted"); let adj_ty = self.next_diverging_ty_var( TypeVariableOrigin::AdjustmentType(expr.span)); self.apply_adjustments(expr, vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }]); ty = adj_ty; } if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) { // Add help to type error if this is an `if` condition with an assignment match (expected, &expr.node) { (ExpectIfCondition, &hir::ExprKind::Assign(ref lhs, ref rhs)) => { let msg = "try comparing for equality"; if let (Ok(left), Ok(right)) = ( self.tcx.sess.codemap().span_to_snippet(lhs.span), self.tcx.sess.codemap().span_to_snippet(rhs.span)) { err.span_suggestion(expr.span, msg, format!("{} == {}", left, right)); } else { err.help(msg); } } _ => (), } err.emit(); } ty } fn check_expr_coercable_to_type(&self, expr: &'gcx hir::Expr, expected: Ty<'tcx>) -> Ty<'tcx> { let ty = self.check_expr_with_hint(expr, expected); // checks don't need two phase self.demand_coerce(expr, ty, expected, AllowTwoPhase::No) } fn check_expr_with_hint(&self, expr: &'gcx hir::Expr, expected: Ty<'tcx>) -> Ty<'tcx> { self.check_expr_with_expectation(expr, ExpectHasType(expected)) } fn check_expr_with_expectation(&self, expr: &'gcx hir::Expr, expected: Expectation<'tcx>) -> Ty<'tcx> { self.check_expr_with_expectation_and_needs(expr, expected, Needs::None) } fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> { self.check_expr_with_expectation(expr, NoExpectation) } fn check_expr_with_needs(&self, expr: &'gcx hir::Expr, needs: Needs) -> Ty<'tcx> { self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs) } // determine the `self` type, using fresh variables for all variables // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>` // would return ($0, $1) where $0 and $1 are freshly instantiated type // variables. pub fn impl_self_ty(&self, span: Span, // (potential) receiver for this impl did: DefId) -> TypeAndSubsts<'tcx> { let ity = self.tcx.type_of(did); debug!("impl_self_ty: ity={:?}", ity); let substs = self.fresh_substs_for_item(span, did); let substd_ty = self.instantiate_type_scheme(span, &substs, &ity); TypeAndSubsts { substs: substs, ty: substd_ty } } /// Unifies the output type with the expected type early, for more coercions /// and forward type information on the input expressions. fn expected_inputs_for_expected_output(&self, call_span: Span, expected_ret: Expectation<'tcx>, formal_ret: Ty<'tcx>, formal_args: &[Ty<'tcx>]) -> Vec<Ty<'tcx>> { let formal_ret = self.resolve_type_vars_with_obligations(formal_ret); let ret_ty = match expected_ret.only_has_type(self) { Some(ret) => ret, None => return Vec::new() }; let expect_args = self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || { // Attempt to apply a subtyping relationship between the formal // return type (likely containing type variables if the function // is polymorphic) and the expected return type. // No argument expectations are produced if unification fails. let origin = self.misc(call_span); let ures = self.at(&origin, self.param_env).sup(ret_ty, &formal_ret); // FIXME(#27336) can't use ? here, Try::from_error doesn't default // to identity so the resulting type is not constrained. match ures { Ok(ok) => { // Process any obligations locally as much as // we can. We don't care if some things turn // out unconstrained or ambiguous, as we're // just trying to get hints here. self.save_and_restore_in_snapshot_flag(|_| { let mut fulfill = TraitEngine::new(self.tcx); for obligation in ok.obligations { fulfill.register_predicate_obligation(self, obligation); } fulfill.select_where_possible(self) }).map_err(|_| ())?; } Err(_) => return Err(()), } // Record all the argument types, with the substitutions // produced from the above subtyping unification. Ok(formal_args.iter().map(|ty| { self.resolve_type_vars_if_possible(ty) }).collect()) }).unwrap_or(Vec::new()); debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})", formal_args, formal_ret, expect_args, expected_ret); expect_args } // Checks a method call. fn check_method_call(&self, expr: &'gcx hir::Expr, segment: &hir::PathSegment, span: Span, args: &'gcx [hir::Expr], expected: Expectation<'tcx>, needs: Needs) -> Ty<'tcx> { let rcvr = &args[0]; let rcvr_t = self.check_expr_with_needs(&rcvr, needs); // no need to check for bot/err -- callee does that let rcvr_t = self.structurally_resolved_type(args[0].span, rcvr_t); let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr) { Ok(method) => { self.write_method_call(expr.hir_id, method); Ok(method) } Err(error) => { if segment.ident.name != keywords::Invalid.name() { self.report_method_error(span, rcvr_t, segment.ident, Some(rcvr), error, Some(args)); } Err(()) } }; // Call the generic checker. self.check_method_argument_types(span, expr.span, method, &args[1..], DontTupleArguments, expected) } fn check_return_expr(&self, return_expr: &'gcx hir::Expr) { let ret_coercion = self.ret_coercion .as_ref() .unwrap_or_else(|| span_bug!(return_expr.span, "check_return_expr called outside fn body")); let ret_ty = ret_coercion.borrow().expected_ty(); let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty.clone()); ret_coercion.borrow_mut() .coerce(self, &self.cause(return_expr.span, ObligationCauseCode::ReturnType(return_expr.id)), return_expr, return_expr_ty); } // A generic function for checking the then and else in an if // or if-else. fn check_then_else(&self, cond_expr: &'gcx hir::Expr, then_expr: &'gcx hir::Expr, opt_else_expr: Option<&'gcx hir::Expr>, sp: Span, expected: Expectation<'tcx>) -> Ty<'tcx> { let cond_ty = self.check_expr_meets_expectation_or_error(cond_expr, ExpectIfCondition); let cond_diverges = self.diverges.get(); self.diverges.set(Diverges::Maybe); let expected = expected.adjust_for_branches(self); let then_ty = self.check_expr_with_expectation(then_expr, expected); let then_diverges = self.diverges.get(); self.diverges.set(Diverges::Maybe); // We've already taken the expected type's preferences // into account when typing the `then` branch. To figure // out the initial shot at a LUB, we thus only consider // `expected` if it represents a *hard* constraint // (`only_has_type`); otherwise, we just go with a // fresh type variable. let coerce_to_ty = expected.coercion_target_type(self, sp); let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty); let if_cause = self.cause(sp, ObligationCauseCode::IfExpression); coerce.coerce(self, &if_cause, then_expr, then_ty); if let Some(else_expr) = opt_else_expr { let else_ty = self.check_expr_with_expectation(else_expr, expected); let else_diverges = self.diverges.get(); coerce.coerce(self, &if_cause, else_expr, else_ty); // We won't diverge unless both branches do (or the condition does). self.diverges.set(cond_diverges | then_diverges & else_diverges); } else { let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse); coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true); // If the condition is false we can't diverge. self.diverges.set(cond_diverges); } let result_ty = coerce.complete(self); if cond_ty.references_error() { self.tcx.types.err } else { result_ty } } // Check field access expressions fn check_field(&self, expr: &'gcx hir::Expr, needs: Needs, base: &'gcx hir::Expr, field: ast::Ident) -> Ty<'tcx> { let expr_t = self.check_expr_with_needs(base, needs); let expr_t = self.structurally_resolved_type(base.span, expr_t); let mut private_candidate = None; let mut autoderef = self.autoderef(expr.span, expr_t); while let Some((base_t, _)) = autoderef.next() { match base_t.sty { ty::TyAdt(base_def, substs) if !base_def.is_enum() => { debug!("struct named {:?}", base_t); let (ident, def_scope) = self.tcx.adjust_ident(field, base_def.did, self.body_id); let fields = &base_def.non_enum_variant().fields; if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) { let field = &fields[index]; let field_ty = self.field_ty(expr.span, field, substs); // Save the index of all fields regardless of their visibility in case // of error recovery. self.write_field_index(expr.id, index); if field.vis.is_accessible_from(def_scope, self.tcx) { let adjustments = autoderef.adjust_steps(needs); self.apply_adjustments(base, adjustments); autoderef.finalize(); self.tcx.check_stability(field.did, Some(expr.id), expr.span); return field_ty; } private_candidate = Some((base_def.did, field_ty)); } } ty::TyTuple(ref tys) => { let fstr = field.as_str(); if let Ok(index) = fstr.parse::<usize>() { if fstr == index.to_string() { if let Some(field_ty) = tys.get(index) { let adjustments = autoderef.adjust_steps(needs); self.apply_adjustments(base, adjustments); autoderef.finalize(); self.write_field_index(expr.id, index); return field_ty; } } } } _ => {} } } autoderef.unambiguous_final_ty(); if let Some((did, field_ty)) = private_candidate { let struct_path = self.tcx().item_path_str(did); let mut err = struct_span_err!(self.tcx().sess, expr.span, E0616, "field `{}` of struct `{}` is private", field, struct_path); // Also check if an accessible method exists, which is often what is meant. if self.method_exists(field, expr_t, expr.id, false) { err.note(&format!("a method `{}` also exists, perhaps you wish to call it", field)); } err.emit(); field_ty } else if field.name == keywords::Invalid.name() { self.tcx().types.err } else if self.method_exists(field, expr_t, expr.id, true) { type_error_struct!(self.tcx().sess, field.span, expr_t, E0615, "attempted to take value of method `{}` on type `{}`", field, expr_t) .help("maybe a `()` to call it is missing?") .emit(); self.tcx().types.err } else { if !expr_t.is_primitive_ty() { let mut err = self.no_such_field_err(field.span, field, expr_t); match expr_t.sty { ty::TyAdt(def, _) if !def.is_enum() => { if let Some(suggested_field_name) = Self::suggest_field_name(def.non_enum_variant(), &field.as_str(), vec![]) { err.span_label(field.span, format!("did you mean `{}`?", suggested_field_name)); } else { err.span_label(field.span, "unknown field"); let struct_variant_def = def.non_enum_variant(); let field_names = self.available_field_names(struct_variant_def); if !field_names.is_empty() { err.note(&format!("available fields are: {}", self.name_series_display(field_names))); } }; } ty::TyRawPtr(..) => { let base = self.tcx.hir.node_to_pretty_string(base.id); let msg = format!("`{}` is a native pointer; try dereferencing it", base); let suggestion = format!("(*{}).{}", base, field); err.span_suggestion(field.span, &msg, suggestion); } _ => {} } err } else { type_error_struct!(self.tcx().sess, field.span, expr_t, E0610, "`{}` is a primitive type and therefore doesn't have fields", expr_t) }.emit(); self.tcx().types.err } } // Return an hint about the closest match in field names fn suggest_field_name(variant: &'tcx ty::VariantDef, field: &str, skip: Vec<LocalInternedString>) -> Option<Symbol> { let names = variant.fields.iter().filter_map(|field| { // ignore already set fields and private fields from non-local crates if skip.iter().any(|x| *x == field.ident.as_str()) || (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) { None } else { Some(&field.ident.name) } }); find_best_match_for_name(names, field, None) } fn available_field_names(&self, variant: &'tcx ty::VariantDef) -> Vec<ast::Name> { let mut available = Vec::new(); for field in variant.fields.iter() { let def_scope = self.tcx.adjust_ident(field.ident, variant.did, self.body_id).1; if field.vis.is_accessible_from(def_scope, self.tcx) { available.push(field.ident.name); } } available } fn name_series_display(&self, names: Vec<ast::Name>) -> String { // dynamic limit, to never omit just one field let limit = if names.len() == 6 { 6 } else { 5 }; let mut display = names.iter().take(limit) .map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", "); if names.len() > limit { display = format!("{} ... and {} others", display, names.len() - limit); } display } fn no_such_field_err<T: Display>(&self, span: Span, field: T, expr_t: &ty::TyS) -> DiagnosticBuilder { type_error_struct!(self.tcx().sess, span, expr_t, E0609, "no field `{}` on type `{}`", field, expr_t) } fn report_unknown_field(&self, ty: Ty<'tcx>, variant: &'tcx ty::VariantDef, field: &hir::Field, skip_fields: &[hir::Field], kind_name: &str) { let mut err = self.type_error_struct_with_diag( field.ident.span, |actual| match ty.sty { ty::TyAdt(adt, ..) if adt.is_enum() => { struct_span_err!(self.tcx.sess, field.ident.span, E0559, "{} `{}::{}` has no field named `{}`", kind_name, actual, variant.name, field.ident) } _ => { struct_span_err!(self.tcx.sess, field.ident.span, E0560, "{} `{}` has no field named `{}`", kind_name, actual, field.ident) } }, ty); // prevent all specified fields from being suggested let skip_fields = skip_fields.iter().map(|ref x| x.ident.as_str()); if let Some(field_name) = Self::suggest_field_name(variant, &field.ident.as_str(), skip_fields.collect()) { err.span_label(field.ident.span, format!("field does not exist - did you mean `{}`?", field_name)); } else { match ty.sty { ty::TyAdt(adt, ..) => { if adt.is_enum() { err.span_label(field.ident.span, format!("`{}::{}` does not have this field", ty, variant.name)); } else { err.span_label(field.ident.span, format!("`{}` does not have this field", ty)); } let available_field_names = self.available_field_names(variant); if !available_field_names.is_empty() { err.note(&format!("available fields are: {}", self.name_series_display(available_field_names))); } } _ => bug!("non-ADT passed to report_unknown_field") } }; err.emit(); } fn check_expr_struct_fields(&self, adt_ty: Ty<'tcx>, expected: Expectation<'tcx>, expr_id: ast::NodeId, span: Span, variant: &'tcx ty::VariantDef, ast_fields: &'gcx [hir::Field], check_completeness: bool) -> bool { let tcx = self.tcx; let adt_ty_hint = self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]) .get(0).cloned().unwrap_or(adt_ty); // re-link the regions that EIfEO can erase. self.demand_eqtype(span, adt_ty_hint, adt_ty); let (substs, adt_kind, kind_name) = match &adt_ty.sty{ &ty::TyAdt(adt, substs) => { (substs, adt.adt_kind(), adt.variant_descr()) } _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields") }; let mut remaining_fields = FxHashMap(); for (i, field) in variant.fields.iter().enumerate() { remaining_fields.insert(field.ident.modern(), (i, field)); } let mut seen_fields = FxHashMap(); let mut error_happened = false; // Typecheck each field. for field in ast_fields { let ident = tcx.adjust_ident(field.ident, variant.did, self.body_id).0; let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) { seen_fields.insert(ident, field.span); self.write_field_index(field.id, i); // we don't look at stability attributes on // struct-like enums (yet...), but it's definitely not // a bug to have construct one. if adt_kind != ty::AdtKind::Enum { tcx.check_stability(v_field.did, Some(expr_id), field.span); } self.field_ty(field.span, v_field, substs) } else { error_happened = true; if let Some(prev_span) = seen_fields.get(&ident) { let mut err = struct_span_err!(self.tcx.sess, field.ident.span, E0062, "field `{}` specified more than once", ident); err.span_label(field.ident.span, "used more than once"); err.span_label(*prev_span, format!("first use of `{}`", ident)); err.emit(); } else { self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name); } tcx.types.err }; // Make sure to give a type to the field even if there's // an error, so we can continue typechecking self.check_expr_coercable_to_type(&field.expr, field_type); } // Make sure the programmer specified correct number of fields. if kind_name == "union" { if ast_fields.len() != 1 { tcx.sess.span_err(span, "union expressions should have exactly one field"); } } else if check_completeness && !error_happened && !remaining_fields.is_empty() { let len = remaining_fields.len(); let mut displayable_field_names = remaining_fields .keys() .map(|ident| ident.as_str()) .collect::<Vec<_>>(); displayable_field_names.sort(); let truncated_fields_error = if len <= 3 { "".to_string() } else { format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"}) }; let remaining_fields_names = displayable_field_names.iter().take(3) .map(|n| format!("`{}`", n)) .collect::<Vec<_>>() .join(", "); struct_span_err!(tcx.sess, span, E0063, "missing field{} {}{} in initializer of `{}`", if remaining_fields.len() == 1 { "" } else { "s" }, remaining_fields_names, truncated_fields_error, adt_ty) .span_label(span, format!("missing {}{}", remaining_fields_names, truncated_fields_error)) .emit(); } error_happened } fn check_struct_fields_on_error(&self, fields: &'gcx [hir::Field], base_expr: &'gcx Option<P<hir::Expr>>) { for field in fields { self.check_expr(&field.expr); } match *base_expr { Some(ref base) => { self.check_expr(&base); }, None => {} } } pub fn check_struct_path(&self, qpath: &hir::QPath, node_id: ast::NodeId) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> { let path_span = match *qpath { hir::QPath::Resolved(_, ref path) => path.span, hir::QPath::TypeRelative(ref qself, _) => qself.span }; let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id); let variant = match def { Def::Err => { self.set_tainted_by_errors(); return None; } Def::Variant(..) => { match ty.sty { ty::TyAdt(adt, substs) => { Some((adt.variant_of_def(def), adt.did, substs)) } _ => bug!("unexpected type: {:?}", ty.sty) } } Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) => { match ty.sty { ty::TyAdt(adt, substs) if !adt.is_enum() => { Some((adt.non_enum_variant(), adt.did, substs)) } _ => None, } } _ => bug!("unexpected definition: {:?}", def) }; if let Some((variant, did, substs)) = variant { // Check bounds on type arguments used in the path. let bounds = self.instantiate_bounds(path_span, did, substs); let cause = traits::ObligationCause::new(path_span, self.body_id, traits::ItemObligation(did)); self.add_obligations_for_parameters(cause, &bounds); Some((variant, ty)) } else { struct_span_err!(self.tcx.sess, path_span, E0071, "expected struct, variant or union type, found {}", ty.sort_string(self.tcx)) .span_label(path_span, "not a struct") .emit(); None } } fn check_expr_struct(&self, expr: &hir::Expr, expected: Expectation<'tcx>, qpath: &hir::QPath, fields: &'gcx [hir::Field], base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx> { // Find the relevant variant let (variant, struct_ty) = if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) { variant_ty } else { self.check_struct_fields_on_error(fields, base_expr); return self.tcx.types.err; }; let path_span = match *qpath { hir::QPath::Resolved(_, ref path) => path.span, hir::QPath::TypeRelative(ref qself, _) => qself.span }; // Prohibit struct expressions when non exhaustive flag is set. if let ty::TyAdt(adt, _) = struct_ty.sty { if !adt.did.is_local() && adt.is_non_exhaustive() { span_err!(self.tcx.sess, expr.span, E0639, "cannot create non-exhaustive {} using struct expression", adt.variant_descr()); } } let error_happened = self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields, base_expr.is_none()); if let &Some(ref base_expr) = base_expr { // If check_expr_struct_fields hit an error, do not attempt to populate // the fields with the base_expr. This could cause us to hit errors later // when certain fields are assumed to exist that in fact do not. if !error_happened { self.check_expr_has_type_or_error(base_expr, struct_ty); match struct_ty.sty { ty::TyAdt(adt, substs) if adt.is_struct() => { let fru_field_types = adt.non_enum_variant().fields.iter().map(|f| { self.normalize_associated_types_in(expr.span, &f.ty(self.tcx, substs)) }).collect(); self.tables .borrow_mut() .fru_field_types_mut() .insert(expr.hir_id, fru_field_types); } _ => { span_err!(self.tcx.sess, base_expr.span, E0436, "functional record update syntax requires a struct"); } } } } self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized); struct_ty } /// Invariant: /// If an expression has any sub-expressions that result in a type error, /// inspecting that expression's type with `ty.references_error()` will return /// true. Likewise, if an expression is known to diverge, inspecting its /// type with `ty::type_is_bot` will return true (n.b.: since Rust is /// strict, _|_ can appear in the type of an expression that does not, /// itself, diverge: for example, fn() -> _|_.) /// Note that inspecting a type's structure *directly* may expose the fact /// that there are actually multiple representations for `TyError`, so avoid /// that when err needs to be handled differently. fn check_expr_with_expectation_and_needs(&self, expr: &'gcx hir::Expr, expected: Expectation<'tcx>, needs: Needs) -> Ty<'tcx> { debug!(">> typechecking: expr={:?} expected={:?}", expr, expected); // Warn for expressions after diverging siblings. self.warn_if_unreachable(expr.id, expr.span, "expression"); // Hide the outer diverging and has_errors flags. let old_diverges = self.diverges.get(); let old_has_errors = self.has_errors.get(); self.diverges.set(Diverges::Maybe); self.has_errors.set(false); let ty = self.check_expr_kind(expr, expected, needs); // Warn for non-block expressions with diverging children. match expr.node { hir::ExprKind::Block(..) | hir::ExprKind::Loop(..) | hir::ExprKind::While(..) | hir::ExprKind::If(..) | hir::ExprKind::Match(..) => {} _ => self.warn_if_unreachable(expr.id, expr.span, "expression") } // Any expression that produces a value of type `!` must have diverged if ty.is_never() { self.diverges.set(self.diverges.get() | Diverges::Always); } // Record the type, which applies it effects. // We need to do this after the warning above, so that // we don't warn for the diverging expression itself. self.write_ty(expr.hir_id, ty); // Combine the diverging and has_error flags. self.diverges.set(self.diverges.get() | old_diverges); self.has_errors.set(self.has_errors.get() | old_has_errors); debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id)); debug!("... {:?}, expected is {:?}", ty, expected); ty } fn check_expr_kind(&self, expr: &'gcx hir::Expr, expected: Expectation<'tcx>, needs: Needs) -> Ty<'tcx> { let tcx = self.tcx; let id = expr.id; match expr.node { hir::ExprKind::Box(ref subexpr) => { let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| { match ty.sty { ty::TyAdt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()), _ => NoExpectation } }); let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner); tcx.mk_box(referent_ty) } hir::ExprKind::Lit(ref lit) => { self.check_lit(&lit, expected) } hir::ExprKind::Binary(op, ref lhs, ref rhs) => { self.check_binop(expr, op, lhs, rhs) } hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { self.check_binop_assign(expr, op, lhs, rhs) } hir::ExprKind::Unary(unop, ref oprnd) => { let expected_inner = match unop { hir::UnNot | hir::UnNeg => { expected } hir::UnDeref => { NoExpectation } }; let needs = match unop { hir::UnDeref => needs, _ => Needs::None }; let mut oprnd_t = self.check_expr_with_expectation_and_needs(&oprnd, expected_inner, needs); if !oprnd_t.references_error() { oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t); match unop { hir::UnDeref => { if let Some(mt) = oprnd_t.builtin_deref(true) { oprnd_t = mt.ty; } else if let Some(ok) = self.try_overloaded_deref( expr.span, oprnd_t, needs) { let method = self.register_infer_ok_obligations(ok); if let ty::TyRef(region, _, mutbl) = method.sig.inputs()[0].sty { let mutbl = match mutbl { hir::MutImmutable => AutoBorrowMutability::Immutable, hir::MutMutable => AutoBorrowMutability::Mutable { // (It shouldn't actually matter for unary ops whether // we enable two-phase borrows or not, since a unary // op has no additional operands.) allow_two_phase_borrow: AllowTwoPhase::No, } }; self.apply_adjustments(oprnd, vec![Adjustment { kind: Adjust::Borrow(AutoBorrow::Ref(region, mutbl)), target: method.sig.inputs()[0] }]); } oprnd_t = self.make_overloaded_place_return_type(method).ty; self.write_method_call(expr.hir_id, method); } else { type_error_struct!(tcx.sess, expr.span, oprnd_t, E0614, "type `{}` cannot be dereferenced", oprnd_t).emit(); oprnd_t = tcx.types.err; } } hir::UnNot => { let result = self.check_user_unop(expr, oprnd_t, unop); // If it's builtin, we can reuse the type, this helps inference. if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) { oprnd_t = result; } } hir::UnNeg => { let result = self.check_user_unop(expr, oprnd_t, unop); // If it's builtin, we can reuse the type, this helps inference. if !(oprnd_t.is_integral() || oprnd_t.is_fp()) { oprnd_t = result; } } } } oprnd_t } hir::ExprKind::AddrOf(mutbl, ref oprnd) => { let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| { match ty.sty { ty::TyRef(_, ty, _) | ty::TyRawPtr(ty::TypeAndMut { ty, .. }) => { if self.is_place_expr(&oprnd) { // Places may legitimately have unsized types. // For example, dereferences of a fat pointer and // the last field of a struct can be unsized. ExpectHasType(ty) } else { Expectation::rvalue_hint(self, ty) } } _ => NoExpectation } }); let needs = Needs::maybe_mut_place(mutbl); let ty = self.check_expr_with_expectation_and_needs(&oprnd, hint, needs); let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl }; if tm.ty.references_error() { tcx.types.err } else { // Note: at this point, we cannot say what the best lifetime // is to use for resulting pointer. We want to use the // shortest lifetime possible so as to avoid spurious borrowck // errors. Moreover, the longest lifetime will depend on the // precise details of the value whose address is being taken // (and how long it is valid), which we don't know yet until type // inference is complete. // // Therefore, here we simply generate a region variable. The // region inferencer will then select the ultimate value. // Finally, borrowck is charged with guaranteeing that the // value whose address was taken can actually be made to live // as long as it needs to live. let region = self.next_region_var(infer::AddrOfRegion(expr.span)); tcx.mk_ref(region, tm) } } hir::ExprKind::Path(ref qpath) => { let (def, opt_ty, segs) = self.resolve_ty_and_def_ufcs(qpath, expr.id, expr.span); let ty = if def != Def::Err { self.instantiate_value_path(segs, opt_ty, def, expr.span, id) } else { self.set_tainted_by_errors(); tcx.types.err }; // We always require that the type provided as the value for // a type parameter outlives the moment of instantiation. let substs = self.tables.borrow().node_substs(expr.hir_id); self.add_wf_bounds(substs, expr); ty } hir::ExprKind::InlineAsm(_, ref outputs, ref inputs) => { for output in outputs { self.check_expr(output); } for input in inputs { self.check_expr(input); } tcx.mk_nil() } hir::ExprKind::Break(destination, ref expr_opt) => { if let Ok(target_id) = destination.target_id { let (e_ty, cause); if let Some(ref e) = *expr_opt { // If this is a break with a value, we need to type-check // the expression. Get an expected type from the loop context. let opt_coerce_to = { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); enclosing_breakables.find_breakable(target_id) .coerce .as_ref() .map(|coerce| coerce.expected_ty()) }; // If the loop context is not a `loop { }`, then break with // a value is illegal, and `opt_coerce_to` will be `None`. // Just set expectation to error in that case. let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err); // Recurse without `enclosing_breakables` borrowed. e_ty = self.check_expr_with_hint(e, coerce_to); cause = self.misc(e.span); } else { // Otherwise, this is a break *without* a value. That's // always legal, and is equivalent to `break ()`. e_ty = tcx.mk_nil(); cause = self.misc(expr.span); } // Now that we have type-checked `expr_opt`, borrow // the `enclosing_loops` field and let's coerce the // type of `expr_opt` into what is expected. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let ctxt = enclosing_breakables.find_breakable(target_id); if let Some(ref mut coerce) = ctxt.coerce { if let Some(ref e) = *expr_opt { coerce.coerce(self, &cause, e, e_ty); } else { assert!(e_ty.is_nil()); coerce.coerce_forced_unit(self, &cause, &mut |_| (), true); } } else { // If `ctxt.coerce` is `None`, we can just ignore // the type of the expresison. This is because // either this was a break *without* a value, in // which case it is always a legal type (`()`), or // else an error would have been flagged by the // `loops` pass for using break with an expression // where you are not supposed to. assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0); } ctxt.may_break = true; // the type of a `break` is always `!`, since it diverges tcx.types.never } else { // Otherwise, we failed to find the enclosing loop; // this can only happen if the `break` was not // inside a loop at all, which is caught by the // loop-checking pass. if self.tcx.sess.err_count() == 0 { self.tcx.sess.delay_span_bug(expr.span, "break was outside loop, but no error was emitted"); } // We still need to assign a type to the inner expression to // prevent the ICE in #43162. if let Some(ref e) = *expr_opt { self.check_expr_with_hint(e, tcx.types.err); // ... except when we try to 'break rust;'. // ICE this expression in particular (see #43162). if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = e.node { if path.segments.len() == 1 && path.segments[0].ident.name == "rust" { fatally_break_rust(self.tcx.sess); } } } // There was an error, make typecheck fail tcx.types.err } } hir::ExprKind::Continue(destination) => { if let Ok(_) = destination.target_id { tcx.types.never } else { // There was an error, make typecheck fail tcx.types.err } } hir::ExprKind::Ret(ref expr_opt) => { if self.ret_coercion.is_none() { struct_span_err!(self.tcx.sess, expr.span, E0572, "return statement outside of function body").emit(); } else if let Some(ref e) = *expr_opt { self.check_return_expr(e); } else { let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut(); let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression); coercion.coerce_forced_unit(self, &cause, &mut |_| (), true); } tcx.types.never } hir::ExprKind::Assign(ref lhs, ref rhs) => { let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace); let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty); match expected { ExpectIfCondition => { self.tcx.sess.delay_span_bug(lhs.span, "invalid lhs expression in if;\ expected error elsehwere"); } _ => { // Only check this if not in an `if` condition, as the // mistyped comparison help is more appropriate. if !self.is_place_expr(&lhs) { struct_span_err!(self.tcx.sess, expr.span, E0070, "invalid left-hand side expression") .span_label(expr.span, "left-hand of expression not valid") .emit(); } } } self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized); if lhs_ty.references_error() || rhs_ty.references_error() { tcx.types.err } else { tcx.mk_nil() } } hir::ExprKind::If(ref cond, ref then_expr, ref opt_else_expr) => { self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e), expr.span, expected) } hir::ExprKind::While(ref cond, ref body, _) => { let ctxt = BreakableCtxt { // cannot use break with a value from a while loop coerce: None, may_break: false, // Will get updated if/when we find a `break`. }; let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || { self.check_expr_has_type_or_error(&cond, tcx.types.bool); let cond_diverging = self.diverges.get(); self.check_block_no_value(&body); // We may never reach the body so it diverging means nothing. self.diverges.set(cond_diverging); }); if ctxt.may_break { // No way to know whether it's diverging because // of a `break` or an outer `break` or `return`. self.diverges.set(Diverges::Maybe); } self.tcx.mk_nil() } hir::ExprKind::Loop(ref body, _, source) => { let coerce = match source { // you can only use break with a value from a normal `loop { }` hir::LoopSource::Loop => { let coerce_to = expected.coercion_target_type(self, body.span); Some(CoerceMany::new(coerce_to)) } hir::LoopSource::WhileLet | hir::LoopSource::ForLoop => { None } }; let ctxt = BreakableCtxt { coerce, may_break: false, // Will get updated if/when we find a `break`. }; let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || { self.check_block_no_value(&body); }); if ctxt.may_break { // No way to know whether it's diverging because // of a `break` or an outer `break` or `return`. self.diverges.set(Diverges::Maybe); } // If we permit break with a value, then result type is // the LUB of the breaks (possibly ! if none); else, it // is nil. This makes sense because infinite loops // (which would have type !) are only possible iff we // permit break with a value [1]. if ctxt.coerce.is_none() && !ctxt.may_break { // [1] self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break"); } ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil()) } hir::ExprKind::Match(ref discrim, ref arms, match_src) => { self.check_match(expr, &discrim, arms, expected, match_src) } hir::ExprKind::Closure(capture, ref decl, body_id, _, gen) => { self.check_expr_closure(expr, capture, &decl, body_id, gen, expected) } hir::ExprKind::Block(ref body, _) => { self.check_block_with_expected(&body, expected) } hir::ExprKind::Call(ref callee, ref args) => { self.check_call(expr, &callee, args, expected) } hir::ExprKind::MethodCall(ref segment, span, ref args) => { self.check_method_call(expr, segment, span, args, expected, needs) } hir::ExprKind::Cast(ref e, ref t) => { // Find the type of `e`. Supply hints based on the type we are casting to, // if appropriate. let t_cast = self.to_ty(t); let t_cast = self.resolve_type_vars_if_possible(&t_cast); let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast)); let t_cast = self.resolve_type_vars_if_possible(&t_cast); // Eagerly check for some obvious errors. if t_expr.references_error() || t_cast.references_error() { tcx.types.err } else { // Defer other checks until we're done type checking. let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut(); match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) { Ok(cast_check) => { deferred_cast_checks.push(cast_check); t_cast } Err(ErrorReported) => { tcx.types.err } } } } hir::ExprKind::Type(ref e, ref t) => { let ty = self.to_ty(&t); self.check_expr_eq_type(&e, ty); ty } hir::ExprKind::Array(ref args) => { let uty = expected.to_option(self).and_then(|uty| { match uty.sty { ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty), _ => None } }); let element_ty = if !args.is_empty() { let coerce_to = uty.unwrap_or_else( || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))); let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args); assert_eq!(self.diverges.get(), Diverges::Maybe); for e in args { let e_ty = self.check_expr_with_hint(e, coerce_to); let cause = self.misc(e.span); coerce.coerce(self, &cause, e, e_ty); } coerce.complete(self) } else { self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)) }; tcx.mk_array(element_ty, args.len() as u64) } hir::ExprKind::Repeat(ref element, ref count) => { let count_def_id = tcx.hir.local_def_id(count.id); let param_env = ty::ParamEnv::empty(); let substs = Substs::identity_for_item(tcx.global_tcx(), count_def_id); let instance = ty::Instance::resolve( tcx.global_tcx(), param_env, count_def_id, substs, ).unwrap(); let global_id = GlobalId { instance, promoted: None }; let count = tcx.const_eval(param_env.and(global_id)); if let Err(ref err) = count { err.report_as_error( tcx.at(tcx.def_span(count_def_id)), "could not evaluate repeat length", ); } let uty = match expected { ExpectHasType(uty) => { match uty.sty { ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty), _ => None } } _ => None }; let (element_ty, t) = match uty { Some(uty) => { self.check_expr_coercable_to_type(&element, uty); (uty, uty) } None => { let ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span)); let element_ty = self.check_expr_has_type_or_error(&element, ty); (element_ty, ty) } }; if let Ok(count) = count { let zero_or_one = count.assert_usize(tcx).map_or(false, |count| count <= 1); if !zero_or_one { // For [foo, ..n] where n > 1, `foo` must have // Copy type: let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem); self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item); } } if element_ty.references_error() { tcx.types.err } else if let Ok(count) = count { tcx.mk_ty(ty::TyArray(t, count)) } else { tcx.types.err } } hir::ExprKind::Tup(ref elts) => { let flds = expected.only_has_type(self).and_then(|ty| { let ty = self.resolve_type_vars_with_obligations(ty); match ty.sty { ty::TyTuple(ref flds) => Some(&flds[..]), _ => None } }); let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| { let t = match flds { Some(ref fs) if i < fs.len() => { let ety = fs[i]; self.check_expr_coercable_to_type(&e, ety); ety } _ => { self.check_expr_with_expectation(&e, NoExpectation) } }; t }); let tuple = tcx.mk_tup(elt_ts_iter); if tuple.references_error() { tcx.types.err } else { self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized); tuple } } hir::ExprKind::Struct(ref qpath, ref fields, ref base_expr) => { self.check_expr_struct(expr, expected, qpath, fields, base_expr) } hir::ExprKind::Field(ref base, field) => { self.check_field(expr, needs, &base, field) } hir::ExprKind::Index(ref base, ref idx) => { let base_t = self.check_expr_with_needs(&base, needs); let idx_t = self.check_expr(&idx); if base_t.references_error() { base_t } else if idx_t.references_error() { idx_t } else { let base_t = self.structurally_resolved_type(base.span, base_t); match self.lookup_indexing(expr, base, base_t, idx_t, needs) { Some((index_ty, element_ty)) => { // two-phase not needed because index_ty is never mutable self.demand_coerce(idx, idx_t, index_ty, AllowTwoPhase::No); element_ty } None => { let mut err = type_error_struct!(tcx.sess, expr.span, base_t, E0608, "cannot index into a value of type `{}`", base_t); // Try to give some advice about indexing tuples. if let ty::TyTuple(..) = base_t.sty { let mut needs_note = true; // If the index is an integer, we can show the actual // fixed expression: if let hir::ExprKind::Lit(ref lit) = idx.node { if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node { let snip = tcx.sess.codemap().span_to_snippet(base.span); if let Ok(snip) = snip { err.span_suggestion(expr.span, "to access tuple elements, use", format!("{}.{}", snip, i)); needs_note = false; } } } if needs_note { err.help("to access tuple elements, use tuple indexing \ syntax (e.g. `tuple.0`)"); } } err.emit(); self.tcx.types.err } } } } hir::ExprKind::Yield(ref value) => { match self.yield_ty { Some(ty) => { self.check_expr_coercable_to_type(&value, ty); } None => { struct_span_err!(self.tcx.sess, expr.span, E0627, "yield statement outside of generator literal").emit(); } } tcx.mk_nil() } } } // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary. // The newly resolved definition is written into `type_dependent_defs`. fn finish_resolving_struct_path(&self, qpath: &hir::QPath, path_span: Span, node_id: ast::NodeId) -> (Def, Ty<'tcx>) { match *qpath { hir::QPath::Resolved(ref maybe_qself, ref path) => { let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself)); let ty = AstConv::def_to_ty(self, opt_self_ty, path, true); (path.def, ty) } hir::QPath::TypeRelative(ref qself, ref segment) => { let ty = self.to_ty(qself); let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node { path.def } else { Def::Err }; let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span, ty, def, segment); // Write back the new resolution. let hir_id = self.tcx.hir.node_to_hir_id(node_id); self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def); (def, ty) } } } // Resolve associated value path into a base type and associated constant or method definition. // The newly resolved definition is written into `type_dependent_defs`. pub fn resolve_ty_and_def_ufcs<'b>(&self, qpath: &'b hir::QPath, node_id: ast::NodeId, span: Span) -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment]) { let (ty, item_segment) = match *qpath { hir::QPath::Resolved(ref opt_qself, ref path) => { return (path.def, opt_qself.as_ref().map(|qself| self.to_ty(qself)), &path.segments[..]); } hir::QPath::TypeRelative(ref qself, ref segment) => { (self.to_ty(qself), segment) } }; let hir_id = self.tcx.hir.node_to_hir_id(node_id); if let Some(cached_def) = self.tables.borrow().type_dependent_defs().get(hir_id) { // Return directly on cache hit. This is useful to avoid doubly reporting // errors with default match binding modes. See #44614. return (*cached_def, Some(ty), slice::from_ref(&**item_segment)) } let item_name = item_segment.ident; let def = match self.resolve_ufcs(span, item_name, ty, node_id) { Ok(def) => def, Err(error) => { let def = match error { method::MethodError::PrivateMatch(def, _) => def, _ => Def::Err, }; if item_name.name != keywords::Invalid.name() { self.report_method_error(span, ty, item_name, None, error, None); } def } }; // Write back the new resolution. self.tables.borrow_mut().type_dependent_defs_mut().insert(hir_id, def); (def, Some(ty), slice::from_ref(&**item_segment)) } pub fn check_decl_initializer(&self, local: &'gcx hir::Local, init: &'gcx hir::Expr) -> Ty<'tcx> { // FIXME(tschottdorf): contains_explicit_ref_binding() must be removed // for #42640 (default match binding modes). // // See #44848. let ref_bindings = local.pat.contains_explicit_ref_binding(); let local_ty = self.local_ty(init.span, local.id); if let Some(m) = ref_bindings { // Somewhat subtle: if we have a `ref` binding in the pattern, // we want to avoid introducing coercions for the RHS. This is // both because it helps preserve sanity and, in the case of // ref mut, for soundness (issue #23116). In particular, in // the latter case, we need to be clear that the type of the // referent for the reference that results is *equal to* the // type of the place it is referencing, and not some // supertype thereof. let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m)); self.demand_eqtype(init.span, local_ty, init_ty); init_ty } else { self.check_expr_coercable_to_type(init, local_ty) } } pub fn check_decl_local(&self, local: &'gcx hir::Local) { let t = self.local_ty(local.span, local.id); self.write_ty(local.hir_id, t); if let Some(ref init) = local.init { let init_ty = self.check_decl_initializer(local, &init); if init_ty.references_error() { self.write_ty(local.hir_id, init_ty); } } self.check_pat_walk(&local.pat, t, ty::BindingMode::BindByValue(hir::Mutability::MutImmutable), true); let pat_ty = self.node_ty(local.pat.hir_id); if pat_ty.references_error() { self.write_ty(local.hir_id, pat_ty); } } pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) { // Don't do all the complex logic below for DeclItem. match stmt.node { hir::StmtKind::Decl(ref decl, _) => { match decl.node { hir::DeclKind::Local(_) => {} hir::DeclKind::Item(_) => { return; } } } hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} } self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement"); // Hide the outer diverging and has_errors flags. let old_diverges = self.diverges.get(); let old_has_errors = self.has_errors.get(); self.diverges.set(Diverges::Maybe); self.has_errors.set(false); match stmt.node { hir::StmtKind::Decl(ref decl, _) => { match decl.node { hir::DeclKind::Local(ref l) => { self.check_decl_local(&l); } hir::DeclKind::Item(_) => {/* ignore for now */} } } hir::StmtKind::Expr(ref expr, _) => { // Check with expected type of () self.check_expr_has_type_or_error(&expr, self.tcx.mk_nil()); } hir::StmtKind::Semi(ref expr, _) => { self.check_expr(&expr); } } // Combine the diverging and has_error flags. self.diverges.set(self.diverges.get() | old_diverges); self.has_errors.set(self.has_errors.get() | old_has_errors); } pub fn check_block_no_value(&self, blk: &'gcx hir::Block) { let unit = self.tcx.mk_nil(); let ty = self.check_block_with_expected(blk, ExpectHasType(unit)); // if the block produces a `!` value, that can always be // (effectively) coerced to unit. if !ty.is_never() { self.demand_suptype(blk.span, unit, ty); } } fn check_block_with_expected(&self, blk: &'gcx hir::Block, expected: Expectation<'tcx>) -> Ty<'tcx> { let prev = { let mut fcx_ps = self.ps.borrow_mut(); let unsafety_state = fcx_ps.recurse(blk); replace(&mut *fcx_ps, unsafety_state) }; // In some cases, blocks have just one exit, but other blocks // can be targeted by multiple breaks. This can happen both // with labeled blocks as well as when we desugar // a `do catch { ... }` expression. // // Example 1: // // 'a: { if true { break 'a Err(()); } Ok(()) } // // Here we would wind up with two coercions, one from // `Err(())` and the other from the tail expression // `Ok(())`. If the tail expression is omitted, that's a // "forced unit" -- unless the block diverges, in which // case we can ignore the tail expression (e.g., `'a: { // break 'a 22; }` would not force the type of the block // to be `()`). let tail_expr = blk.expr.as_ref(); let coerce_to_ty = expected.coercion_target_type(self, blk.span); let coerce = if blk.targeted_by_break { CoerceMany::new(coerce_to_ty) } else { let tail_expr: &[P<hir::Expr>] = match tail_expr { Some(e) => slice::from_ref(e), None => &[], }; CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr) }; let prev_diverges = self.diverges.get(); let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false, }; let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || { for s in &blk.stmts { self.check_stmt(s); } // check the tail expression **without** holding the // `enclosing_breakables` lock below. let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected)); let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); let ctxt = enclosing_breakables.find_breakable(blk.id); let coerce = ctxt.coerce.as_mut().unwrap(); if let Some(tail_expr_ty) = tail_expr_ty { let tail_expr = tail_expr.unwrap(); let cause = self.cause(tail_expr.span, ObligationCauseCode::BlockTailExpression(blk.id)); coerce.coerce(self, &cause, tail_expr, tail_expr_ty); } else { // Subtle: if there is no explicit tail expression, // that is typically equivalent to a tail expression // of `()` -- except if the block diverges. In that // case, there is no value supplied from the tail // expression (assuming there are no other breaks, // this implies that the type of the block will be // `!`). // // #41425 -- label the implicit `()` as being the // "found type" here, rather than the "expected type". // // #44579 -- if the block was recovered during parsing, // the type would be nonsensical and it is not worth it // to perform the type check, so we avoid generating the // diagnostic output. if !self.diverges.get().always() && !blk.recovered { coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| { if let Some(expected_ty) = expected.only_has_type(self) { self.consider_hint_about_removing_semicolon(blk, expected_ty, err); } }, false); } } }); if ctxt.may_break { // If we can break from the block, then the block's exit is always reachable // (... as long as the entry is reachable) - regardless of the tail of the block. self.diverges.set(prev_diverges); } let mut ty = ctxt.coerce.unwrap().complete(self); if self.has_errors.get() || ty.references_error() { ty = self.tcx.types.err } self.write_ty(blk.hir_id, ty); *self.ps.borrow_mut() = prev; ty } /// Given a `NodeId`, return the `FnDecl` of the method it is enclosed by and whether a /// suggestion can be made, `None` otherwise. pub fn get_fn_decl(&self, blk_id: ast::NodeId) -> Option<(hir::FnDecl, bool)> { // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or // `while` before reaching it, as block tail returns are not available in them. if let Some(fn_id) = self.tcx.hir.get_return_block(blk_id) { let parent = self.tcx.hir.get(fn_id); if let Node::NodeItem(&hir::Item { name, node: hir::ItemKind::Fn(ref decl, ..), .. }) = parent { decl.clone().and_then(|decl| { // This is less than ideal, it will not suggest a return type span on any // method called `main`, regardless of whether it is actually the entry point, // but it will still present it as the reason for the expected type. Some((decl, name != Symbol::intern("main"))) }) } else if let Node::NodeTraitItem(&hir::TraitItem { node: hir::TraitItemKind::Method(hir::MethodSig { ref decl, .. }, ..), .. }) = parent { decl.clone().and_then(|decl| { Some((decl, true)) }) } else if let Node::NodeImplItem(&hir::ImplItem { node: hir::ImplItemKind::Method(hir::MethodSig { ref decl, .. }, ..), .. }) = parent { decl.clone().and_then(|decl| { Some((decl, false)) }) } else { None } } else { None } } /// On implicit return expressions with mismatched types, provide the following suggestions: /// /// - Point out the method's return type as the reason for the expected type /// - Possible missing semicolon /// - Possible missing return type if the return type is the default, and not `fn main()` pub fn suggest_mismatched_types_on_tail(&self, err: &mut DiagnosticBuilder<'tcx>, expression: &'gcx hir::Expr, expected: Ty<'tcx>, found: Ty<'tcx>, cause_span: Span, blk_id: ast::NodeId) { self.suggest_missing_semicolon(err, expression, expected, cause_span); if let Some((fn_decl, can_suggest)) = self.get_fn_decl(blk_id) { self.suggest_missing_return_type(err, &fn_decl, expected, found, can_suggest); } self.suggest_ref_or_into(err, expression, expected, found); } pub fn suggest_ref_or_into( &self, err: &mut DiagnosticBuilder<'tcx>, expr: &hir::Expr, expected: Ty<'tcx>, found: Ty<'tcx>, ) { if let Some((sp, msg, suggestion)) = self.check_ref(expr, found, expected) { err.span_suggestion(sp, msg, suggestion); } else if !self.check_for_cast(err, expr, found, expected) { let methods = self.get_conversion_methods(expr.span, expected, found); if let Ok(expr_text) = self.sess().codemap().span_to_snippet(expr.span) { let suggestions = iter::repeat(expr_text).zip(methods.iter()) .map(|(receiver, method)| format!("{}.{}()", receiver, method.ident)) .collect::<Vec<_>>(); if !suggestions.is_empty() { err.span_suggestions(expr.span, "try using a conversion method", suggestions); } } } } /// A common error is to forget to add a semicolon at the end of a block: /// /// ``` /// fn foo() { /// bar_that_returns_u32() /// } /// ``` /// /// This routine checks if the return expression in a block would make sense on its own as a /// statement and the return type has been left as default or has been specified as `()`. If so, /// it suggests adding a semicolon. fn suggest_missing_semicolon(&self, err: &mut DiagnosticBuilder<'tcx>, expression: &'gcx hir::Expr, expected: Ty<'tcx>, cause_span: Span) { if expected.is_nil() { // `BlockTailExpression` only relevant if the tail expr would be // useful on its own. match expression.node { hir::ExprKind::Call(..) | hir::ExprKind::MethodCall(..) | hir::ExprKind::If(..) | hir::ExprKind::While(..) | hir::ExprKind::Loop(..) | hir::ExprKind::Match(..) | hir::ExprKind::Block(..) => { let sp = self.tcx.sess.codemap().next_point(cause_span); err.span_suggestion(sp, "try adding a semicolon", ";".to_string()); } _ => (), } } } /// A possible error is to forget to add a return type that is needed: /// /// ``` /// fn foo() { /// bar_that_returns_u32() /// } /// ``` /// /// This routine checks if the return type is left as default, the method is not part of an /// `impl` block and that it isn't the `main` method. If so, it suggests setting the return /// type. fn suggest_missing_return_type(&self, err: &mut DiagnosticBuilder<'tcx>, fn_decl: &hir::FnDecl, expected: Ty<'tcx>, found: Ty<'tcx>, can_suggest: bool) { // Only suggest changing the return type for methods that // haven't set a return type at all (and aren't `fn main()` or an impl). match (&fn_decl.output, found.is_suggestable(), can_suggest, expected.is_nil()) { (&hir::FunctionRetTy::DefaultReturn(span), true, true, true) => { err.span_suggestion(span, "try adding a return type", format!("-> {} ", self.resolve_type_vars_with_obligations(found))); } (&hir::FunctionRetTy::DefaultReturn(span), false, true, true) => { err.span_label(span, "possibly return type missing here?"); } (&hir::FunctionRetTy::DefaultReturn(span), _, false, true) => { // `fn main()` must return `()`, do not suggest changing return type err.span_label(span, "expected `()` because of default return type"); } // expectation was caused by something else, not the default return (&hir::FunctionRetTy::DefaultReturn(_), _, _, false) => {} (&hir::FunctionRetTy::Return(ref ty), _, _, _) => { // Only point to return type if the expected type is the return type, as if they // are not, the expectation must have been caused by something else. debug!("suggest_missing_return_type: return type {:?} node {:?}", ty, ty.node); let sp = ty.span; let ty = AstConv::ast_ty_to_ty(self, ty); debug!("suggest_missing_return_type: return type sty {:?}", ty.sty); debug!("suggest_missing_return_type: expected type sty {:?}", ty.sty); if ty.sty == expected.sty { err.span_label(sp, format!("expected `{}` because of return type", expected)); } } } } /// A common error is to add an extra semicolon: /// /// ``` /// fn foo() -> usize { /// 22; /// } /// ``` /// /// This routine checks if the final statement in a block is an /// expression with an explicit semicolon whose type is compatible /// with `expected_ty`. If so, it suggests removing the semicolon. fn consider_hint_about_removing_semicolon(&self, blk: &'gcx hir::Block, expected_ty: Ty<'tcx>, err: &mut DiagnosticBuilder) { // Be helpful when the user wrote `{... expr;}` and // taking the `;` off is enough to fix the error. let last_stmt = match blk.stmts.last() { Some(s) => s, None => return, }; let last_expr = match last_stmt.node { hir::StmtKind::Semi(ref e, _) => e, _ => return, }; let last_expr_ty = self.node_ty(last_expr.hir_id); if self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err() { return; } let original_span = original_sp(last_stmt.span, blk.span); let span_semi = original_span.with_lo(original_span.hi() - BytePos(1)); err.span_suggestion(span_semi, "consider removing this semicolon", "".to_string()); } // Instantiates the given path, which must refer to an item with the given // number of type parameters and type. pub fn instantiate_value_path(&self, segments: &[hir::PathSegment], opt_self_ty: Option<Ty<'tcx>>, def: Def, span: Span, node_id: ast::NodeId) -> Ty<'tcx> { debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})", segments, def, node_id); // We need to extract the type parameters supplied by the user in // the path `path`. Due to the current setup, this is a bit of a // tricky-process; the problem is that resolve only tells us the // end-point of the path resolution, and not the intermediate steps. // Luckily, we can (at least for now) deduce the intermediate steps // just from the end-point. // // There are basically four cases to consider: // // 1. Reference to a constructor of enum variant or struct: // // struct Foo<T>(...) // enum E<T> { Foo(...) } // // In these cases, the parameters are declared in the type // space. // // 2. Reference to a fn item or a free constant: // // fn foo<T>() { } // // In this case, the path will again always have the form // `a::b::foo::<T>` where only the final segment should have // type parameters. However, in this case, those parameters are // declared on a value, and hence are in the `FnSpace`. // // 3. Reference to a method or an associated constant: // // impl<A> SomeStruct<A> { // fn foo<B>(...) // } // // Here we can have a path like // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters // may appear in two places. The penultimate segment, // `SomeStruct::<A>`, contains parameters in TypeSpace, and the // final segment, `foo::<B>` contains parameters in fn space. // // 4. Reference to a local variable // // Local variables can't have any type parameters. // // The first step then is to categorize the segments appropriately. assert!(!segments.is_empty()); let mut ufcs_associated = None; let mut type_segment = None; let mut fn_segment = None; match def { // Case 1. Reference to a struct/variant constructor. Def::StructCtor(def_id, ..) | Def::VariantCtor(def_id, ..) => { // Everything but the final segment should have no // parameters at all. let mut generics = self.tcx.generics_of(def_id); if let Some(def_id) = generics.parent { // Variant and struct constructors use the // generics of their parent type definition. generics = self.tcx.generics_of(def_id); } type_segment = Some((segments.last().unwrap(), generics)); } // Case 2. Reference to a top-level value. Def::Fn(def_id) | Def::Const(def_id) | Def::Static(def_id, _) => { fn_segment = Some((segments.last().unwrap(), self.tcx.generics_of(def_id))); } // Case 3. Reference to a method or associated const. Def::Method(def_id) | Def::AssociatedConst(def_id) => { let container = self.tcx.associated_item(def_id).container; match container { ty::TraitContainer(trait_did) => { callee::check_legal_trait_for_method_call(self.tcx, span, trait_did) } ty::ImplContainer(_) => {} } let generics = self.tcx.generics_of(def_id); if segments.len() >= 2 { let parent_generics = self.tcx.generics_of(generics.parent.unwrap()); type_segment = Some((&segments[segments.len() - 2], parent_generics)); } else { // `<T>::assoc` will end up here, and so can `T::assoc`. let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self"); ufcs_associated = Some((container, self_ty)); } fn_segment = Some((segments.last().unwrap(), generics)); } // Case 4. Local variable, no generics. Def::Local(..) | Def::Upvar(..) => {} _ => bug!("unexpected definition: {:?}", def), } debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment); // Now that we have categorized what space the parameters for each // segment belong to, let's sort out the parameters that the user // provided (if any) into their appropriate spaces. We'll also report // errors if type parameters are provided in an inappropriate place. let poly_segments = type_segment.is_some() as usize + fn_segment.is_some() as usize; AstConv::prohibit_generics(self, &segments[..segments.len() - poly_segments]); match def { Def::Local(nid) | Def::Upvar(nid, ..) => { let ty = self.local_ty(span, nid); let ty = self.normalize_associated_types_in(span, &ty); self.write_ty(self.tcx.hir.node_to_hir_id(node_id), ty); return ty; } _ => {} } // Now we have to compare the types that the user *actually* // provided against the types that were *expected*. If the user // did not provide any types, then we want to substitute inference // variables. If the user provided some types, we may still need // to add defaults. If the user provided *too many* types, that's // a problem. let supress_mismatch = self.check_impl_trait(span, fn_segment); self.check_generic_arg_count(span, &mut type_segment, false, supress_mismatch); self.check_generic_arg_count(span, &mut fn_segment, false, supress_mismatch); let (fn_start, has_self) = match (type_segment, fn_segment) { (_, Some((_, generics))) => { (generics.parent_count, generics.has_self) } (Some((_, generics)), None) => { (generics.params.len(), generics.has_self) } (None, None) => (0, false) }; // FIXME(varkor): Separating out the parameters is messy. let mut lifetimes_type_seg = vec![]; let mut types_type_seg = vec![]; let mut infer_types_type_seg = true; if let Some((seg, _)) = type_segment { if let Some(ref data) = seg.args { for arg in &data.args { match arg { GenericArg::Lifetime(lt) => lifetimes_type_seg.push(lt), GenericArg::Type(ty) => types_type_seg.push(ty), } } } infer_types_type_seg = seg.infer_types; } let mut lifetimes_fn_seg = vec![]; let mut types_fn_seg = vec![]; let mut infer_types_fn_seg = true; if let Some((seg, _)) = fn_segment { if let Some(ref data) = seg.args { for arg in &data.args { match arg { GenericArg::Lifetime(lt) => lifetimes_fn_seg.push(lt), GenericArg::Type(ty) => types_fn_seg.push(ty), } } } infer_types_fn_seg = seg.infer_types; } let substs = Substs::for_item(self.tcx, def.def_id(), |param, substs| { let mut i = param.index as usize; let (segment, lifetimes, types, infer_types) = if i < fn_start { if let GenericParamDefKind::Type { .. } = param.kind { // Handle Self first, so we can adjust the index to match the AST. if has_self && i == 0 { return opt_self_ty.map(|ty| ty.into()).unwrap_or_else(|| { self.var_for_def(span, param) }); } } i -= has_self as usize; (type_segment, &lifetimes_type_seg, &types_type_seg, infer_types_type_seg) } else { i -= fn_start; (fn_segment, &lifetimes_fn_seg, &types_fn_seg, infer_types_fn_seg) }; match param.kind { GenericParamDefKind::Lifetime => { if let Some(lifetime) = lifetimes.get(i) { AstConv::ast_region_to_region(self, lifetime, Some(param)).into() } else { self.re_infer(span, Some(param)).unwrap().into() } } GenericParamDefKind::Type { .. } => { // Skip over the lifetimes in the same segment. if let Some((_, generics)) = segment { i -= generics.own_counts().lifetimes; } let has_default = match param.kind { GenericParamDefKind::Type { has_default, .. } => has_default, _ => unreachable!() }; if let Some(ast_ty) = types.get(i) { // A provided type parameter. self.to_ty(ast_ty).into() } else if !infer_types && has_default { // No type parameter provided, but a default exists. let default = self.tcx.type_of(param.def_id); self.normalize_ty( span, default.subst_spanned(self.tcx, substs, Some(span)) ).into() } else { // No type parameters were provided, we can infer all. // This can also be reached in some error cases: // We prefer to use inference variables instead of // TyError to let type inference recover somewhat. self.var_for_def(span, param) } } } }); // The things we are substituting into the type should not contain // escaping late-bound regions, and nor should the base type scheme. let ty = self.tcx.type_of(def.def_id()); assert!(!substs.has_escaping_regions()); assert!(!ty.has_escaping_regions()); // Add all the obligations that are required, substituting and // normalized appropriately. let bounds = self.instantiate_bounds(span, def.def_id(), &substs); self.add_obligations_for_parameters( traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())), &bounds); // Substitute the values for the type parameters into the type of // the referenced item. let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty); if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated { // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method` // is inherent, there is no `Self` parameter, instead, the impl needs // type parameters, which we can infer by unifying the provided `Self` // with the substituted impl type. let ty = self.tcx.type_of(impl_def_id); let impl_ty = self.instantiate_type_scheme(span, &substs, &ty); match self.at(&self.misc(span), self.param_env).sup(impl_ty, self_ty) { Ok(ok) => self.register_infer_ok_obligations(ok), Err(_) => { span_bug!(span, "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", self_ty, impl_ty); } } } self.check_rustc_args_require_const(def.def_id(), node_id, span); debug!("instantiate_value_path: type of {:?} is {:?}", node_id, ty_substituted); self.write_substs(self.tcx.hir.node_to_hir_id(node_id), substs); ty_substituted } fn check_rustc_args_require_const(&self, def_id: DefId, node_id: ast::NodeId, span: Span) { // We're only interested in functions tagged with // #[rustc_args_required_const], so ignore anything that's not. if !self.tcx.has_attr(def_id, "rustc_args_required_const") { return } // If our calling expression is indeed the function itself, we're good! // If not, generate an error that this can only be called directly. match self.tcx.hir.get(self.tcx.hir.get_parent_node(node_id)) { Node::NodeExpr(expr) => { match expr.node { hir::ExprKind::Call(ref callee, ..) => { if callee.id == node_id { return } } _ => {} } } _ => {} } self.tcx.sess.span_err(span, "this function can only be invoked \ directly, not through a function pointer"); } /// Report errors if the provided parameters are too few or too many. fn check_generic_arg_count(&self, span: Span, segment: &mut Option<(&hir::PathSegment, &ty::Generics)>, is_method_call: bool, supress_mismatch_error: bool) { let (lifetimes, types, infer_types, bindings) = segment.map_or( (vec![], vec![], true, &[][..]), |(s, _)| { s.args.as_ref().map_or( (vec![], vec![], s.infer_types, &[][..]), |data| { let (mut lifetimes, mut types) = (vec![], vec![]); data.args.iter().for_each(|arg| match arg { GenericArg::Lifetime(lt) => lifetimes.push(lt), GenericArg::Type(ty) => types.push(ty), }); (lifetimes, types, s.infer_types, &data.bindings[..]) } ) }); // Check provided parameters. let ((ty_required, ty_accepted), lt_accepted) = segment.map_or(((0, 0), 0), |(_, generics)| { struct ParamRange { required: usize, accepted: usize }; let mut lt_accepted = 0; let mut ty_params = ParamRange { required: 0, accepted: 0 }; for param in &generics.params { match param.kind { GenericParamDefKind::Lifetime => lt_accepted += 1, GenericParamDefKind::Type { has_default, .. } => { ty_params.accepted += 1; if !has_default { ty_params.required += 1; } } }; } if generics.parent.is_none() && generics.has_self { ty_params.required -= 1; ty_params.accepted -= 1; } ((ty_params.required, ty_params.accepted), lt_accepted) }); let count_type_params = |n| { format!("{} type parameter{}", n, if n == 1 { "" } else { "s" }) }; let expected_text = count_type_params(ty_accepted); let actual_text = count_type_params(types.len()); if let Some((mut err, span)) = if types.len() > ty_accepted { // To prevent derived errors to accumulate due to extra // type parameters, we force instantiate_value_path to // use inference variables instead of the provided types. *segment = None; let span = types[ty_accepted].span; Some((struct_span_err!(self.tcx.sess, span, E0087, "too many type parameters provided: \ expected at most {}, found {}", expected_text, actual_text), span)) } else if types.len() < ty_required && !infer_types && !supress_mismatch_error { Some((struct_span_err!(self.tcx.sess, span, E0089, "too few type parameters provided: \ expected {}, found {}", expected_text, actual_text), span)) } else { None } { err.span_label(span, format!("expected {}", expected_text)).emit(); } if !bindings.is_empty() { AstConv::prohibit_projection(self, bindings[0].span); } let infer_lifetimes = lifetimes.len() == 0; // Prohibit explicit lifetime arguments if late bound lifetime parameters are present. let has_late_bound_lifetime_defs = segment.map_or(None, |(_, generics)| generics.has_late_bound_regions); if let (Some(span_late), false) = (has_late_bound_lifetime_defs, lifetimes.is_empty()) { // Report this as a lint only if no error was reported previously. let primary_msg = "cannot specify lifetime arguments explicitly \ if late bound lifetime parameters are present"; let note_msg = "the late bound lifetime parameter is introduced here"; if !is_method_call && (lifetimes.len() > lt_accepted || lifetimes.len() < lt_accepted && !infer_lifetimes) { let mut err = self.tcx.sess.struct_span_err(lifetimes[0].span, primary_msg); err.span_note(span_late, note_msg); err.emit(); *segment = None; } else { let mut multispan = MultiSpan::from_span(lifetimes[0].span); multispan.push_span_label(span_late, note_msg.to_string()); self.tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS, lifetimes[0].id, multispan, primary_msg); } return; } let count_lifetime_params = |n| { format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" }) }; let expected_text = count_lifetime_params(lt_accepted); let actual_text = count_lifetime_params(lifetimes.len()); if let Some((mut err, span)) = if lifetimes.len() > lt_accepted { let span = lifetimes[lt_accepted].span; Some((struct_span_err!(self.tcx.sess, span, E0088, "too many lifetime parameters provided: \ expected at most {}, found {}", expected_text, actual_text), span)) } else if lifetimes.len() < lt_accepted && !infer_lifetimes { Some((struct_span_err!(self.tcx.sess, span, E0090, "too few lifetime parameters provided: \ expected {}, found {}", expected_text, actual_text), span)) } else { None } { err.span_label(span, format!("expected {}", expected_text)).emit(); } } /// Report error if there is an explicit type parameter when using `impl Trait`. fn check_impl_trait(&self, span: Span, segment: Option<(&hir::PathSegment, &ty::Generics)>) -> bool { let segment = segment.map(|(path_segment, generics)| { let explicit = !path_segment.infer_types; let impl_trait = generics.params.iter().any(|param| match param.kind { ty::GenericParamDefKind::Type { synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), .. } => true, _ => false, }); if explicit && impl_trait { let mut err = struct_span_err! { self.tcx.sess, span, E0632, "cannot provide explicit type parameters when `impl Trait` is \ used in argument position." }; err.emit(); } impl_trait }); segment.unwrap_or(false) } // Resolves `typ` by a single level if `typ` is a type variable. // If no resolution is possible, then an error is reported. // Numeric inference variables may be left unresolved. pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { let ty = self.resolve_type_vars_with_obligations(ty); if !ty.is_ty_var() { ty } else { if !self.is_tainted_by_errors() { self.need_type_info_err((**self).body_id, sp, ty) .note("type must be known at this point") .emit(); } self.demand_suptype(sp, self.tcx.types.err, ty); self.tcx.types.err } } fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId, ctxt: BreakableCtxt<'gcx, 'tcx>, f: F) -> (BreakableCtxt<'gcx, 'tcx>, R) { let index; { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); index = enclosing_breakables.stack.len(); enclosing_breakables.by_id.insert(id, index); enclosing_breakables.stack.push(ctxt); } let result = f(); let ctxt = { let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); debug_assert!(enclosing_breakables.stack.len() == index + 1); enclosing_breakables.by_id.remove(&id).expect("missing breakable context"); enclosing_breakables.stack.pop().expect("missing breakable context") }; (ctxt, result) } } pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, generics: &ty::Generics, ty: Ty<'tcx>) { let own_counts = generics.own_counts(); debug!("check_bounds_are_used(n_tps={}, ty={:?})", own_counts.types, ty); if own_counts.types == 0 { return; } // Make a vector of booleans initially false, set to true when used. let mut types_used = vec![false; own_counts.types]; for leaf_ty in ty.walk() { if let ty::TyParam(ty::ParamTy { idx, .. }) = leaf_ty.sty { debug!("Found use of ty param num {}", idx); types_used[idx as usize - own_counts.lifetimes] = true; } else if let ty::TyError = leaf_ty.sty { // If there is already another error, do not emit // an error for not using a type Parameter. assert!(tcx.sess.err_count() > 0); return; } } let types = generics.params.iter().filter(|param| match param.kind { ty::GenericParamDefKind::Type { .. } => true, _ => false, }); for (&used, param) in types_used.iter().zip(types) { if !used { let id = tcx.hir.as_local_node_id(param.def_id).unwrap(); let span = tcx.hir.span(id); struct_span_err!(tcx.sess, span, E0091, "type parameter `{}` is unused", param.name) .span_label(span, "unused type parameter") .emit(); } } } fn fatally_break_rust(sess: &Session) { let handler = sess.diagnostic(); handler.span_bug_no_panic( MultiSpan::new(), "It looks like you're trying to break rust; would you like some ICE?", ); handler.note_without_error("the compiler expectedly panicked. this is a feature."); handler.note_without_error( "we would appreciate a joke overview: \ https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675" ); handler.note_without_error(&format!("rustc {} running on {}", option_env!("CFG_VERSION").unwrap_or("unknown_version"), ::session::config::host_triple(), )); }
42.557678
100
0.51053
64f4695776e60ebdea93802282fe40b783a55731
12,120
use serde::de::DeserializeOwned; use serde::ser::Serialize; use std::collections::BTreeMap; use std::io::{Read, Write}; use crate::error::Error; use crate::interchange::DataInterchange; use crate::Result; pub(crate) mod pretty; pub(crate) mod shims; pub use pretty::JsonPretty; /// JSON data interchange. /// /// # Schema /// /// This doesn't use JSON Schema because that specification language is rage inducing. Here's /// something else instead. /// /// ## Common Entities /// /// `NATURAL_NUMBER` is an integer in the range `[1, 2**32)`. /// /// `EXPIRES` is an ISO-8601 date time in format `YYYY-MM-DD'T'hh:mm:ss'Z'`. /// /// `KEY_ID` is the hex encoded value of `sha256(cjson(pub_key))`. /// /// `PUB_KEY` is the following: /// /// ```bash /// { /// "type": KEY_TYPE, /// "scheme": SCHEME, /// "value": PUBLIC /// } /// ``` /// /// `PUBLIC` is a base64url encoded `SubjectPublicKeyInfo` DER public key. /// /// `KEY_TYPE` is a string (either `rsa` or `ed25519`). /// /// `SCHEME` is a string (either `ed25519`, `rsassa-pss-sha256`, or `rsassa-pss-sha512` /// /// `HASH_VALUE` is a hex encoded hash value. /// /// `SIG_VALUE` is a hex encoded signature value. /// /// `METADATA_DESCRIPTION` is the following: /// /// ```bash /// { /// "version": NATURAL_NUMBER, /// "length": NATURAL_NUMBER, /// "hashes": { /// HASH_ALGORITHM: HASH_VALUE /// ... /// } /// } /// ``` /// /// ## `SignedMetadata` /// /// ```bash /// { /// "signatures": [SIGNATURE], /// "signed": SIGNED /// } /// ``` /// /// `SIGNATURE` is: /// /// ```bash /// { /// "keyid": KEY_ID, /// "signature": SIG_VALUE /// } /// ``` /// /// `SIGNED` is one of: /// /// - `RootMetadata` /// - `SnapshotMetadata` /// - `TargetsMetadata` /// - `TimestampMetadata` /// /// The the elements of `signatures` must have unique `key_id`s. /// /// ## `RootMetadata` /// /// ```bash /// { /// "_type": "root", /// "version": NATURAL_NUMBER, /// "expires": EXPIRES, /// "keys": [PUB_KEY, ...] /// "roles": { /// "root": ROLE_DESCRIPTION, /// "snapshot": ROLE_DESCRIPTION, /// "targets": ROLE_DESCRIPTION, /// "timestamp": ROLE_DESCRIPTION /// } /// } /// ``` /// /// `ROLE_DESCRIPTION` is the following: /// /// ```bash /// { /// "threshold": NATURAL_NUMBER, /// "keyids": [KEY_ID, ...] /// } /// ``` /// /// ## `SnapshotMetadata` /// /// ```bash /// { /// "_type": "snapshot", /// "version": NATURAL_NUMBER, /// "expires": EXPIRES, /// "meta": { /// META_PATH: METADATA_DESCRIPTION /// } /// } /// ``` /// /// `META_PATH` is a string. /// /// /// ## `TargetsMetadata` /// /// ```bash /// { /// "_type": "timestamp", /// "version": NATURAL_NUMBER, /// "expires": EXPIRES, /// "targets": { /// TARGET_PATH: TARGET_DESCRIPTION /// ... /// }, /// "delegations": DELEGATIONS /// } /// ``` /// /// `DELEGATIONS` is optional and is described by the following: /// /// ```bash /// { /// "keys": [PUB_KEY, ...] /// "roles": { /// ROLE: DELEGATION, /// ... /// } /// } /// ``` /// /// `DELEGATION` is: /// /// ```bash /// { /// "name": ROLE, /// "threshold": NATURAL_NUMBER, /// "terminating": BOOLEAN, /// "keyids": [KEY_ID, ...], /// "paths": [PATH, ...] /// } /// ``` /// /// `ROLE` is a string, /// /// `PATH` is a string. /// /// ## `TimestampMetadata` /// /// ```bash /// { /// "_type": "timestamp", /// "version": NATURAL_NUMBER, /// "expires": EXPIRES, /// "snapshot": METADATA_DESCRIPTION /// } /// ``` #[derive(Debug, Clone, PartialEq)] pub struct Json; impl DataInterchange for Json { type RawData = serde_json::Value; /// ``` /// # use tuf::interchange::{DataInterchange, Json}; /// assert_eq!(Json::extension(), "json"); /// ``` fn extension() -> &'static str { "json" } /// ``` /// # use tuf::interchange::{DataInterchange, Json}; /// # use std::collections::HashMap; /// let jsn: &[u8] = br#"{"foo": "bar", "baz": "quux"}"#; /// let raw = Json::from_reader(jsn).unwrap(); /// let out = Json::canonicalize(&raw).unwrap(); /// assert_eq!(out, br#"{"baz":"quux","foo":"bar"}"#); /// ``` fn canonicalize(raw_data: &Self::RawData) -> Result<Vec<u8>> { canonicalize(raw_data).map_err(Error::Opaque) } /// ``` /// # use serde_derive::Deserialize; /// # use serde_json::json; /// # use std::collections::HashMap; /// # use tuf::interchange::{DataInterchange, Json}; /// # /// #[derive(Deserialize, Debug, PartialEq)] /// struct Thing { /// foo: String, /// bar: String, /// } /// /// let jsn = json!({"foo": "wat", "bar": "lol"}); /// let thing = Thing { foo: "wat".into(), bar: "lol".into() }; /// let de: Thing = Json::deserialize(&jsn).unwrap(); /// assert_eq!(de, thing); /// ``` fn deserialize<T>(raw_data: &Self::RawData) -> Result<T> where T: DeserializeOwned, { Ok(serde_json::from_value(raw_data.clone())?) } /// ``` /// # use serde_derive::Serialize; /// # use serde_json::json; /// # use std::collections::HashMap; /// # use tuf::interchange::{DataInterchange, Json}; /// # /// #[derive(Serialize)] /// struct Thing { /// foo: String, /// bar: String, /// } /// /// let jsn = json!({"foo": "wat", "bar": "lol"}); /// let thing = Thing { foo: "wat".into(), bar: "lol".into() }; /// let se: serde_json::Value = Json::serialize(&thing).unwrap(); /// assert_eq!(se, jsn); /// ``` fn serialize<T>(data: &T) -> Result<Self::RawData> where T: Serialize, { Ok(serde_json::to_value(data)?) } /// ``` /// # use serde_json::json; /// # use tuf::interchange::{DataInterchange, Json}; /// let json = json!({ /// "o": { /// "a": [1, 2, 3], /// "s": "string", /// "n": 123, /// "t": true, /// "f": false, /// "0": null, /// }, /// }); /// /// let mut buf = Vec::new(); /// Json::to_writer(&mut buf, &json).unwrap(); /// assert_eq!( /// &String::from_utf8(buf).unwrap(), /// r#"{"o":{"0":null,"a":[1,2,3],"f":false,"n":123,"s":"string","t":true}}"# /// ); /// ``` fn to_writer<W, T: Sized>(mut writer: W, value: &T) -> Result<()> where W: Write, T: Serialize, { let bytes = Self::canonicalize(&Self::serialize(value)?)?; writer.write_all(&bytes)?; Ok(()) } /// ``` /// # use tuf::interchange::{DataInterchange, Json}; /// # use std::collections::HashMap; /// let jsn: &[u8] = br#"{"foo": "bar", "baz": "quux"}"#; /// let _: HashMap<String, String> = Json::from_reader(jsn).unwrap(); /// ``` fn from_reader<R, T>(rdr: R) -> Result<T> where R: Read, T: DeserializeOwned, { Ok(serde_json::from_reader(rdr)?) } /// ``` /// # use tuf::interchange::{DataInterchange, Json}; /// # use std::collections::HashMap; /// let jsn: &[u8] = br#"{"foo": "bar", "baz": "quux"}"#; /// let _: HashMap<String, String> = Json::from_slice(&jsn).unwrap(); /// ``` fn from_slice<T>(slice: &[u8]) -> Result<T> where T: DeserializeOwned, { Ok(serde_json::from_slice(slice)?) } } fn canonicalize(jsn: &serde_json::Value) -> std::result::Result<Vec<u8>, String> { let converted = convert(jsn)?; let mut buf = Vec::new(); let _ = converted.write(&mut buf); // Vec<u8> impl always succeeds (or panics). Ok(buf) } enum Value { Array(Vec<Value>), Bool(bool), Null, Number(Number), Object(BTreeMap<String, Value>), String(String), } impl Value { fn write(&self, mut buf: &mut Vec<u8>) -> std::result::Result<(), String> { match *self { Value::Null => { buf.extend(b"null"); Ok(()) } Value::Bool(true) => { buf.extend(b"true"); Ok(()) } Value::Bool(false) => { buf.extend(b"false"); Ok(()) } Value::Number(Number::I64(n)) => itoa::write(buf, n) .map(|_| ()) .map_err(|err| format!("Write error: {}", err)), Value::Number(Number::U64(n)) => itoa::write(buf, n) .map(|_| ()) .map_err(|err| format!("Write error: {}", err)), Value::String(ref s) => { // this mess is abusing serde_json to get json escaping let s = serde_json::Value::String(s.clone()); let s = serde_json::to_string(&s).map_err(|e| format!("{:?}", e))?; buf.extend(s.as_bytes()); Ok(()) } Value::Array(ref arr) => { buf.push(b'['); let mut first = true; for a in arr.iter() { if !first { buf.push(b','); } a.write(&mut buf)?; first = false; } buf.push(b']'); Ok(()) } Value::Object(ref obj) => { buf.push(b'{'); let mut first = true; for (k, v) in obj.iter() { if !first { buf.push(b','); } first = false; // this mess is abusing serde_json to get json escaping let k = serde_json::Value::String(k.clone()); let k = serde_json::to_string(&k).map_err(|e| format!("{:?}", e))?; buf.extend(k.as_bytes()); buf.push(b':'); v.write(&mut buf)?; } buf.push(b'}'); Ok(()) } } } } enum Number { I64(i64), U64(u64), } fn convert(jsn: &serde_json::Value) -> std::result::Result<Value, String> { match *jsn { serde_json::Value::Null => Ok(Value::Null), serde_json::Value::Bool(b) => Ok(Value::Bool(b)), serde_json::Value::Number(ref n) => n .as_i64() .map(Number::I64) .or_else(|| n.as_u64().map(Number::U64)) .map(Value::Number) .ok_or_else(|| String::from("only i64 and u64 are supported")), serde_json::Value::Array(ref arr) => { let mut out = Vec::new(); for res in arr.iter().map(|v| convert(v)) { out.push(res?) } Ok(Value::Array(out)) } serde_json::Value::Object(ref obj) => { let mut out = BTreeMap::new(); for (k, v) in obj.iter() { let _ = out.insert(k.clone(), convert(v)?); } Ok(Value::Object(out)) } serde_json::Value::String(ref s) => Ok(Value::String(s.clone())), } } #[cfg(test)] mod test { use super::*; #[test] fn write_str() { let jsn = Value::String(String::from("wat")); let mut out = Vec::new(); jsn.write(&mut out).unwrap(); assert_eq!(&out, b"\"wat\""); } #[test] fn write_arr() { let jsn = Value::Array(vec![ Value::String(String::from("wat")), Value::String(String::from("lol")), Value::String(String::from("no")), ]); let mut out = Vec::new(); jsn.write(&mut out).unwrap(); assert_eq!(&out, b"[\"wat\",\"lol\",\"no\"]"); } #[test] fn write_obj() { let mut map = BTreeMap::new(); let arr = Value::Array(vec![ Value::String(String::from("haha")), Value::String(String::from("new\nline")), ]); let _ = map.insert(String::from("lol"), arr); let jsn = Value::Object(map); let mut out = Vec::new(); jsn.write(&mut out).unwrap(); assert_eq!(&out, &b"{\"lol\":[\"haha\",\"new\\nline\"]}"); } }
25.787234
93
0.474257
9c7f779ebfa1de12158368b468f613143f92eef3
346
#![feature(plugin, use_extern_macros)] #![plugin(dotenv_macros)] extern crate diesel; extern crate dotenv; use dotenv::dotenv; use diesel::Connection; fn main() { dotenv().ok(); let connection = diesel::pg::PgConnection::establish(dotenv!("DATABASE_URL")).ok().unwrap(); diesel::migrations::run_pending_migrations(&connection).ok(); }
23.066667
94
0.719653
f5b8ebb772a24509a01fd0ae11ed4dc54e0e8589
7,573
mod helpers; use helpers::{in_directory as cwd, Playground, Stub::*}; #[test] fn can_convert_table_to_csv_text_and_from_csv_text_back_into_table() { nu!( output, cwd("tests/fixtures/formats"), "open caco3_plastics.csv | to-csv | from-csv | first 1 | get origin | echo $it" ); assert_eq!(output, "SPAIN"); } #[test] fn converts_structured_table_to_csv_text() { Playground::setup_for("filter_to_csv_test_1").with_files(vec![FileWithContentToBeTrimmed( "sample.txt", r#" importer,shipper,tariff_item,name,origin Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_to_csv_test_1"), r#"open sample.txt | lines | split-column "," a b c d origin | last 1 | to-csv | lines | nth 1 | echo "$it""# ); assert!(output.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")); } #[test] fn converts_structured_table_to_csv_text_skipping_headers_after_conversion() { Playground::setup_for("filter_to_csv_test_2").with_files(vec![FileWithContentToBeTrimmed( "sample.txt", r#" importer,shipper,tariff_item,name,origin Plasticos Rival,Reverte,2509000000,Calcium carbonate,Spain Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_to_csv_test_2"), r#"open sample.txt | lines | split-column "," a b c d origin | last 1 | to-csv --headerless | echo "$it""# ); assert!(output.contains("Tigre Ecuador,OMYA Andina,3824909999,Calcium carbonate,Colombia")); } #[test] fn converts_from_csv_text_to_structured_table() { Playground::setup_for("filter_from_csv_test_1").with_files(vec![FileWithContentToBeTrimmed( "los_tres_amigos.txt", r#" first_name,last_name,rusty_luck Andrés,Robalino,1 Jonathan,Turner,1 Yehuda,Katz,1 "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_from_csv_test_1"), "open los_tres_amigos.txt | from-csv | get rusty_luck | str --to-int | sum | echo $it" ); assert_eq!(output, "3"); } #[test] fn converts_from_csv_text_skipping_headers_to_structured_table() { Playground::setup_for("filter_from_csv_test_2").with_files(vec![FileWithContentToBeTrimmed( "los_tres_amigos.txt", r#" first_name,last_name,rusty_luck Andrés,Robalino,1 Jonathan,Turner,1 Yehuda,Katz,1 "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_from_csv_test_2"), "open los_tres_amigos.txt | from-csv --headerless | get Column3 | str --to-int | sum | echo $it" ); assert_eq!(output, "3"); } #[test] fn can_convert_table_to_json_text_and_from_json_text_back_into_table() { nu!( output, cwd("tests/fixtures/formats"), "open sgml_description.json | to-json | from-json | get glossary.GlossDiv.GlossList.GlossEntry.GlossSee | echo $it" ); assert_eq!(output, "markup"); } #[test] fn converts_from_json_text_to_structured_table() { Playground::setup_for("filter_from_json_test_1").with_files(vec![FileWithContentToBeTrimmed( "katz.txt", r#" { "katz": [ {"name": "Yehuda", "rusty_luck": 1}, {"name": "Jonathan", "rusty_luck": 1}, {"name": "Andres", "rusty_luck": 1}, {"name":"GorbyPuff", "rusty_luck": 1} ] } "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_from_json_test_1"), "open katz.txt | from-json | get katz | get rusty_luck | sum | echo $it" ); assert_eq!(output, "4"); } #[test] fn converts_from_json_text_recognizing_objects_independendtly_to_structured_table() { Playground::setup_for("filter_from_json_test_2").with_files(vec![FileWithContentToBeTrimmed( "katz.txt", r#" {"name": "Yehuda", "rusty_luck": 1} {"name": "Jonathan", "rusty_luck": 1} {"name": "Andres", "rusty_luck": 1} {"name":"GorbyPuff", "rusty_luck": 3} "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_from_json_test_2"), r#"open katz.txt | from-json --objects | where name == "GorbyPuff" | get rusty_luck | echo $it"# ); assert_eq!(output, "3"); } #[test] fn converts_structured_table_to_json_text() { Playground::setup_for("filter_to_json_test_1").with_files(vec![FileWithContentToBeTrimmed( "sample.txt", r#" JonAndrehudaTZ,3 GorbyPuff,100 "#, )]); nu!( output, cwd("tests/fixtures/nuplayground/filter_to_json_test_1"), r#"open sample.txt | lines | split-column "," name luck | pick name | to-json | nth 0 | from-json | get name | echo $it"# ); assert_eq!(output, "JonAndrehudaTZ"); } #[test] fn can_convert_json_text_to_bson_and_back_into_table() { nu!( output, cwd("tests/fixtures/formats"), "open sample.bson | to-bson | from-bson | get root | nth 1 | get b | echo $it" ); assert_eq!(output, "whel"); } #[test] fn can_convert_table_to_toml_text_and_from_toml_text_back_into_table() { nu!( output, cwd("tests/fixtures/formats"), "open cargo_sample.toml | to-toml | from-toml | get package.name | echo $it" ); assert_eq!(output, "nu"); } #[test] fn can_convert_table_to_yaml_text_and_from_yaml_text_back_into_table() { nu!( output, cwd("tests/fixtures/formats"), "open appveyor.yml | to-yaml | from-yaml | get environment.global.PROJECT_NAME | echo $it" ); assert_eq!(output, "nushell"); } #[test] fn can_sort_by_column() { nu!( output, cwd("tests/fixtures/formats"), r#"open cargo_sample.toml --raw | lines | skip 1 | first 4 | split-column "=" | sort-by Column1 | skip 1 | first 1 | get Column1 | trim | echo $it"# ); assert_eq!(output, "description"); } #[test] fn can_split_by_column() { nu!( output, cwd("tests/fixtures/formats"), r#"open cargo_sample.toml --raw | lines | skip 1 | first 1 | split-column "=" | get Column1 | trim | echo $it"# ); assert_eq!(output, "name"); } #[test] fn can_sum() { nu!( output, cwd("tests/fixtures/formats"), "open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Sections | sum | echo $it" ); assert_eq!(output, "203") } #[test] fn can_filter_by_unit_size_comparison() { nu!( output, cwd("tests/fixtures/formats"), "ls | where size > 1kb | sort-by size | get name | skip 1 | trim | echo $it" ); assert_eq!(output, "caco3_plastics.csv"); } #[test] fn can_get_last() { nu!( output, cwd("tests/fixtures/formats"), "ls | sort-by name | last 1 | get name | trim | echo $it" ); assert_eq!(output, "utf16.ini"); } #[test] fn can_get_reverse_first() { nu!( output, cwd("tests/fixtures/formats"), "ls | sort-by name | reverse | first 1 | get name | trim | echo $it" ); assert_eq!(output, "utf16.ini"); }
27.841912
156
0.604516
d732af77be8b85bd746760fca3983e64171d5dd7
5,030
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy // SPDX-License-Identifier: Apache-2.0 // SPDX-License-Identifier: MIT use crate::{ api::{config::Config, PackageInfo}, hooks::{InvokeError, InvokeMessage, InvokeResolver}, runtime::Runtime, Invoke, Window, }; use serde::{Deserialize, Serialize}; use serde_json::Value as JsonValue; use std::sync::Arc; mod app; mod cli; mod clipboard; mod dialog; mod event; #[allow(unused_imports)] mod file_system; mod global_shortcut; mod http; mod internal; mod notification; mod process; mod shell; mod window; /// The response for a JS `invoke` call. pub struct InvokeResponse { json: crate::Result<JsonValue>, } impl<T: Serialize> From<T> for InvokeResponse { fn from(value: T) -> Self { Self { json: serde_json::to_value(value).map_err(Into::into), } } } #[derive(Deserialize)] #[serde(tag = "module", content = "message")] enum Module { App(app::Cmd), Process(process::Cmd), Fs(file_system::Cmd), Window(Box<window::Cmd>), Shell(shell::Cmd), Event(event::Cmd), Internal(internal::Cmd), Dialog(dialog::Cmd), Cli(cli::Cmd), Notification(notification::Cmd), Http(http::Cmd), GlobalShortcut(global_shortcut::Cmd), Clipboard(clipboard::Cmd), } impl Module { fn run<R: Runtime>( self, window: Window<R>, resolver: InvokeResolver<R>, config: Arc<Config>, package_info: PackageInfo, ) { match self { Self::App(cmd) => resolver.respond_async(async move { cmd .run(package_info) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Process(cmd) => resolver .respond_async(async move { cmd.run().and_then(|r| r.json).map_err(InvokeError::from) }), Self::Fs(cmd) => resolver.respond_async(async move { cmd .run(config, &package_info) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Window(cmd) => resolver.respond_async(async move { cmd .run(window) .await .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Shell(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Event(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Internal(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), // on macOS, the dialog must run on another thread: https://github.com/rust-windowing/winit/issues/1779 // we do the same on Windows just to stay consistent with `tao` (and it also improves UX because of the event loop) #[cfg(not(target_os = "linux"))] Self::Dialog(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), // on Linux, the dialog must run on the rpc task. #[cfg(target_os = "linux")] Self::Dialog(cmd) => { resolver.respond_closure(move || { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }); } Self::Cli(cmd) => { if let Some(cli_config) = config.tauri.cli.clone() { resolver.respond_async(async move { cmd .run(&cli_config) .and_then(|r| r.json) .map_err(InvokeError::from) }) } } Self::Notification(cmd) => resolver.respond_closure(move || { cmd .run(config, &package_info) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Http(cmd) => resolver.respond_async(async move { cmd .run() .await .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::GlobalShortcut(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), Self::Clipboard(cmd) => resolver.respond_async(async move { cmd .run(window) .and_then(|r| r.json) .map_err(InvokeError::from) }), } } } pub(crate) fn handle<R: Runtime>( module: String, invoke: Invoke<R>, config: Arc<Config>, package_info: &PackageInfo, ) { let Invoke { message, resolver } = invoke; let InvokeMessage { mut payload, window, .. } = message; if let JsonValue::Object(ref mut obj) = payload { obj.insert("module".to_string(), JsonValue::String(module)); } match serde_json::from_value::<Module>(payload) { Ok(module) => module.run(window, resolver, config, package_info.clone()), Err(e) => resolver.reject(e.to_string()), } }
26.473684
121
0.583101
6a529bfc8df97f8ad4644bb1e622e252927133e0
104,046
// ignore-tidy-filelength // This file almost exclusively consists of the definition of `Iterator`. We // can't split that into multiple files. use crate::cmp::{self, Ordering}; use crate::ops::{Add, Try}; use super::super::LoopState; use super::super::{Chain, Cloned, Copied, Cycle, Enumerate, Filter, FilterMap, Fuse}; use super::super::{FlatMap, Flatten}; use super::super::{FromIterator, Product, Sum, Zip}; use super::super::{ Inspect, Map, MapWhile, Peekable, Rev, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, }; fn _assert_is_object_safe(_: &dyn Iterator<Item = ()>) {} /// An interface for dealing with iterators. /// /// This is the main iterator trait. For more about the concept of iterators /// generally, please see the [module-level documentation]. In particular, you /// may want to know how to [implement `Iterator`][impl]. /// /// [module-level documentation]: index.html /// [impl]: index.html#implementing-iterator #[stable(feature = "rust1", since = "1.0.0")] #[rustc_on_unimplemented( on( _Self = "[std::ops::Range<Idx>; 1]", label = "if you meant to iterate between two values, remove the square brackets", note = "`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \ without the brackets: `start..end`" ), on( _Self = "[std::ops::RangeFrom<Idx>; 1]", label = "if you meant to iterate from a value onwards, remove the square brackets", note = "`[start..]` is an array of one `RangeFrom`; you might have meant to have a \ `RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \ unbounded iterator will run forever unless you `break` or `return` from within the \ loop" ), on( _Self = "[std::ops::RangeTo<Idx>; 1]", label = "if you meant to iterate until a value, remove the square brackets and add a \ starting value", note = "`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \ `Range` without the brackets: `0..end`" ), on( _Self = "[std::ops::RangeInclusive<Idx>; 1]", label = "if you meant to iterate between two values, remove the square brackets", note = "`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \ `RangeInclusive` without the brackets: `start..=end`" ), on( _Self = "[std::ops::RangeToInclusive<Idx>; 1]", label = "if you meant to iterate until a value (including it), remove the square brackets \ and add a starting value", note = "`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \ bounded `RangeInclusive` without the brackets: `0..=end`" ), on( _Self = "std::ops::RangeTo<Idx>", label = "if you meant to iterate until a value, add a starting value", note = "`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \ bounded `Range`: `0..end`" ), on( _Self = "std::ops::RangeToInclusive<Idx>", label = "if you meant to iterate until a value (including it), add a starting value", note = "`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \ to have a bounded `RangeInclusive`: `0..=end`" ), on( _Self = "&str", label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" ), on( _Self = "std::string::String", label = "`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`" ), on( _Self = "[]", label = "borrow the array with `&` or call `.iter()` on it to iterate over it", note = "arrays are not iterators, but slices like the following are: `&[1, 2, 3]`" ), on( _Self = "{integral}", note = "if you want to iterate between `start` until a value `end`, use the exclusive range \ syntax `start..end` or the inclusive range syntax `start..=end`" ), label = "`{Self}` is not an iterator", message = "`{Self}` is not an iterator" )] #[doc(spotlight)] #[must_use = "iterators are lazy and do nothing unless consumed"] pub trait Iterator { /// The type of the elements being iterated over. #[stable(feature = "rust1", since = "1.0.0")] type Item; /// Advances the iterator and returns the next value. /// /// Returns [`None`] when iteration is finished. Individual iterator /// implementations may choose to resume iteration, and so calling `next()` /// again may or may not eventually start returning [`Some(Item)`] again at some /// point. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// // A call to next() returns the next value... /// assert_eq!(Some(&1), iter.next()); /// assert_eq!(Some(&2), iter.next()); /// assert_eq!(Some(&3), iter.next()); /// /// // ... and then None once it's over. /// assert_eq!(None, iter.next()); /// /// // More calls may or may not return `None`. Here, they always will. /// assert_eq!(None, iter.next()); /// assert_eq!(None, iter.next()); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn next(&mut self) -> Option<Self::Item>; /// Returns the bounds on the remaining length of the iterator. /// /// Specifically, `size_hint()` returns a tuple where the first element /// is the lower bound, and the second element is the upper bound. /// /// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`. /// A [`None`] here means that either there is no known upper bound, or the /// upper bound is larger than [`usize`]. /// /// # Implementation notes /// /// It is not enforced that an iterator implementation yields the declared /// number of elements. A buggy iterator may yield less than the lower bound /// or more than the upper bound of elements. /// /// `size_hint()` is primarily intended to be used for optimizations such as /// reserving space for the elements of the iterator, but must not be /// trusted to e.g., omit bounds checks in unsafe code. An incorrect /// implementation of `size_hint()` should not lead to memory safety /// violations. /// /// That said, the implementation should provide a correct estimation, /// because otherwise it would be a violation of the trait's protocol. /// /// The default implementation returns `(0, `[`None`]`)` which is correct for any /// iterator. /// /// [`usize`]: ../../std/primitive.usize.html /// [`Option`]: ../../std/option/enum.Option.html /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// let iter = a.iter(); /// /// assert_eq!((3, Some(3)), iter.size_hint()); /// ``` /// /// A more complex example: /// /// ``` /// // The even numbers from zero to ten. /// let iter = (0..10).filter(|x| x % 2 == 0); /// /// // We might iterate from zero to ten times. Knowing that it's five /// // exactly wouldn't be possible without executing filter(). /// assert_eq!((0, Some(10)), iter.size_hint()); /// /// // Let's add five more numbers with chain() /// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20); /// /// // now both bounds are increased by five /// assert_eq!((5, Some(15)), iter.size_hint()); /// ``` /// /// Returning `None` for an upper bound: /// /// ``` /// // an infinite iterator has no upper bound /// // and the maximum possible lower bound /// let iter = 0..; /// /// assert_eq!((usize::max_value(), None), iter.size_hint()); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn size_hint(&self) -> (usize, Option<usize>) { (0, None) } /// Consumes the iterator, counting the number of iterations and returning it. /// /// This method will call [`next`] repeatedly until [`None`] is encountered, /// returning the number of times it saw [`Some`]. Note that [`next`] has to be /// called at least once even if the iterator does not have any elements. /// /// [`next`]: #tymethod.next /// [`None`]: ../../std/option/enum.Option.html#variant.None /// [`Some`]: ../../std/option/enum.Option.html#variant.Some /// /// # Overflow Behavior /// /// The method does no guarding against overflows, so counting elements of /// an iterator with more than [`usize::MAX`] elements either produces the /// wrong result or panics. If debug assertions are enabled, a panic is /// guaranteed. /// /// # Panics /// /// This function might panic if the iterator has more than [`usize::MAX`] /// elements. /// /// [`usize::MAX`]: ../../std/usize/constant.MAX.html /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// assert_eq!(a.iter().count(), 3); /// /// let a = [1, 2, 3, 4, 5]; /// assert_eq!(a.iter().count(), 5); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn count(self) -> usize where Self: Sized, { #[inline] fn add1<T>(count: usize, _: T) -> usize { // Might overflow. Add::add(count, 1) } self.fold(0, add1) } /// Consumes the iterator, returning the last element. /// /// This method will evaluate the iterator until it returns [`None`]. While /// doing so, it keeps track of the current element. After [`None`] is /// returned, `last()` will then return the last element it saw. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// assert_eq!(a.iter().last(), Some(&3)); /// /// let a = [1, 2, 3, 4, 5]; /// assert_eq!(a.iter().last(), Some(&5)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn last(self) -> Option<Self::Item> where Self: Sized, { #[inline] fn some<T>(_: Option<T>, x: T) -> Option<T> { Some(x) } self.fold(None, some) } /// Returns the `n`th element of the iterator. /// /// Like most indexing operations, the count starts from zero, so `nth(0)` /// returns the first value, `nth(1)` the second, and so on. /// /// Note that all preceding elements, as well as the returned element, will be /// consumed from the iterator. That means that the preceding elements will be /// discarded, and also that calling `nth(0)` multiple times on the same iterator /// will return different elements. /// /// `nth()` will return [`None`] if `n` is greater than or equal to the length of the /// iterator. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// assert_eq!(a.iter().nth(1), Some(&2)); /// ``` /// /// Calling `nth()` multiple times doesn't rewind the iterator: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// assert_eq!(iter.nth(1), Some(&2)); /// assert_eq!(iter.nth(1), None); /// ``` /// /// Returning `None` if there are less than `n + 1` elements: /// /// ``` /// let a = [1, 2, 3]; /// assert_eq!(a.iter().nth(10), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn nth(&mut self, mut n: usize) -> Option<Self::Item> { for x in self { if n == 0 { return Some(x); } n -= 1; } None } /// Creates an iterator starting at the same point, but stepping by /// the given amount at each iteration. /// /// Note 1: The first element of the iterator will always be returned, /// regardless of the step given. /// /// Note 2: The time at which ignored elements are pulled is not fixed. /// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`, /// but is also free to behave like the sequence /// `advance_n_and_return_first(step), advance_n_and_return_first(step), …` /// Which way is used may change for some iterators for performance reasons. /// The second way will advance the iterator earlier and may consume more items. /// /// `advance_n_and_return_first` is the equivalent of: /// ``` /// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item> /// where /// I: Iterator, /// { /// let next = iter.next(); /// if total_step > 1 { /// iter.nth(total_step-2); /// } /// next /// } /// ``` /// /// # Panics /// /// The method will panic if the given step is `0`. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [0, 1, 2, 3, 4, 5]; /// let mut iter = a.iter().step_by(2); /// /// assert_eq!(iter.next(), Some(&0)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), Some(&4)); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "iterator_step_by", since = "1.28.0")] fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized, { StepBy::new(self, step) } /// Takes two iterators and creates a new iterator over both in sequence. /// /// `chain()` will return a new iterator which will first iterate over /// values from the first iterator and then over values from the second /// iterator. /// /// In other words, it links two iterators together, in a chain. 🔗 /// /// [`once`] is commonly used to adapt a single value into a chain of /// other kinds of iteration. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a1 = [1, 2, 3]; /// let a2 = [4, 5, 6]; /// /// let mut iter = a1.iter().chain(a2.iter()); /// /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), Some(&4)); /// assert_eq!(iter.next(), Some(&5)); /// assert_eq!(iter.next(), Some(&6)); /// assert_eq!(iter.next(), None); /// ``` /// /// Since the argument to `chain()` uses [`IntoIterator`], we can pass /// anything that can be converted into an [`Iterator`], not just an /// [`Iterator`] itself. For example, slices (`&[T]`) implement /// [`IntoIterator`], and so can be passed to `chain()` directly: /// /// ``` /// let s1 = &[1, 2, 3]; /// let s2 = &[4, 5, 6]; /// /// let mut iter = s1.iter().chain(s2); /// /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), Some(&4)); /// assert_eq!(iter.next(), Some(&5)); /// assert_eq!(iter.next(), Some(&6)); /// assert_eq!(iter.next(), None); /// ``` /// /// If you work with Windows API, you may wish to convert [`OsStr`] to `Vec<u16>`: /// /// ``` /// #[cfg(windows)] /// fn os_str_to_utf16(s: &std::ffi::OsStr) -> Vec<u16> { /// use std::os::windows::ffi::OsStrExt; /// s.encode_wide().chain(std::iter::once(0)).collect() /// } /// ``` /// /// [`once`]: fn.once.html /// [`Iterator`]: trait.Iterator.html /// [`IntoIterator`]: trait.IntoIterator.html /// [`OsStr`]: ../../std/ffi/struct.OsStr.html #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where Self: Sized, U: IntoIterator<Item = Self::Item>, { Chain::new(self, other.into_iter()) } /// 'Zips up' two iterators into a single iterator of pairs. /// /// `zip()` returns a new iterator that will iterate over two other /// iterators, returning a tuple where the first element comes from the /// first iterator, and the second element comes from the second iterator. /// /// In other words, it zips two iterators together, into a single one. /// /// If either iterator returns [`None`], [`next`] from the zipped iterator /// will return [`None`]. If the first iterator returns [`None`], `zip` will /// short-circuit and `next` will not be called on the second iterator. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a1 = [1, 2, 3]; /// let a2 = [4, 5, 6]; /// /// let mut iter = a1.iter().zip(a2.iter()); /// /// assert_eq!(iter.next(), Some((&1, &4))); /// assert_eq!(iter.next(), Some((&2, &5))); /// assert_eq!(iter.next(), Some((&3, &6))); /// assert_eq!(iter.next(), None); /// ``` /// /// Since the argument to `zip()` uses [`IntoIterator`], we can pass /// anything that can be converted into an [`Iterator`], not just an /// [`Iterator`] itself. For example, slices (`&[T]`) implement /// [`IntoIterator`], and so can be passed to `zip()` directly: /// /// [`IntoIterator`]: trait.IntoIterator.html /// [`Iterator`]: trait.Iterator.html /// /// ``` /// let s1 = &[1, 2, 3]; /// let s2 = &[4, 5, 6]; /// /// let mut iter = s1.iter().zip(s2); /// /// assert_eq!(iter.next(), Some((&1, &4))); /// assert_eq!(iter.next(), Some((&2, &5))); /// assert_eq!(iter.next(), Some((&3, &6))); /// assert_eq!(iter.next(), None); /// ``` /// /// `zip()` is often used to zip an infinite iterator to a finite one. /// This works because the finite iterator will eventually return [`None`], /// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]: /// /// ``` /// let enumerate: Vec<_> = "foo".chars().enumerate().collect(); /// /// let zipper: Vec<_> = (0..).zip("foo".chars()).collect(); /// /// assert_eq!((0, 'f'), enumerate[0]); /// assert_eq!((0, 'f'), zipper[0]); /// /// assert_eq!((1, 'o'), enumerate[1]); /// assert_eq!((1, 'o'), zipper[1]); /// /// assert_eq!((2, 'o'), enumerate[2]); /// assert_eq!((2, 'o'), zipper[2]); /// ``` /// /// [`enumerate`]: trait.Iterator.html#method.enumerate /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next /// [`None`]: ../../std/option/enum.Option.html#variant.None #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where Self: Sized, U: IntoIterator, { Zip::new(self, other.into_iter()) } /// Takes a closure and creates an iterator which calls that closure on each /// element. /// /// `map()` transforms one iterator into another, by means of its argument: /// something that implements [`FnMut`]. It produces a new iterator which /// calls this closure on each element of the original iterator. /// /// If you are good at thinking in types, you can think of `map()` like this: /// If you have an iterator that gives you elements of some type `A`, and /// you want an iterator of some other type `B`, you can use `map()`, /// passing a closure that takes an `A` and returns a `B`. /// /// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is /// lazy, it is best used when you're already working with other iterators. /// If you're doing some sort of looping for a side effect, it's considered /// more idiomatic to use [`for`] than `map()`. /// /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for /// [`FnMut`]: ../../std/ops/trait.FnMut.html /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter().map(|x| 2 * x); /// /// assert_eq!(iter.next(), Some(2)); /// assert_eq!(iter.next(), Some(4)); /// assert_eq!(iter.next(), Some(6)); /// assert_eq!(iter.next(), None); /// ``` /// /// If you're doing some sort of side effect, prefer [`for`] to `map()`: /// /// ``` /// # #![allow(unused_must_use)] /// // don't do this: /// (0..5).map(|x| println!("{}", x)); /// /// // it won't even execute, as it is lazy. Rust will warn you about this. /// /// // Instead, use for: /// for x in 0..5 { /// println!("{}", x); /// } /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn map<B, F>(self, f: F) -> Map<Self, F> where Self: Sized, F: FnMut(Self::Item) -> B, { Map::new(self, f) } /// Calls a closure on each element of an iterator. /// /// This is equivalent to using a [`for`] loop on the iterator, although /// `break` and `continue` are not possible from a closure. It's generally /// more idiomatic to use a `for` loop, but `for_each` may be more legible /// when processing items at the end of longer iterator chains. In some /// cases `for_each` may also be faster than a loop, because it will use /// internal iteration on adaptors like `Chain`. /// /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for /// /// # Examples /// /// Basic usage: /// /// ``` /// use std::sync::mpsc::channel; /// /// let (tx, rx) = channel(); /// (0..5).map(|x| x * 2 + 1) /// .for_each(move |x| tx.send(x).unwrap()); /// /// let v: Vec<_> = rx.iter().collect(); /// assert_eq!(v, vec![1, 3, 5, 7, 9]); /// ``` /// /// For such a small example, a `for` loop may be cleaner, but `for_each` /// might be preferable to keep a functional style with longer iterators: /// /// ``` /// (0..5).flat_map(|x| x * 100 .. x * 110) /// .enumerate() /// .filter(|&(i, x)| (i + x) % 3 == 0) /// .for_each(|(i, x)| println!("{}:{}", i, x)); /// ``` #[inline] #[stable(feature = "iterator_for_each", since = "1.21.0")] fn for_each<F>(self, f: F) where Self: Sized, F: FnMut(Self::Item), { #[inline] fn call<T>(mut f: impl FnMut(T)) -> impl FnMut((), T) { move |(), item| f(item) } self.fold((), call(f)); } /// Creates an iterator which uses a closure to determine if an element /// should be yielded. /// /// The closure must return `true` or `false`. `filter()` creates an /// iterator which calls this closure on each element. If the closure /// returns `true`, then the element is returned. If the closure returns /// `false`, it will try again, and call the closure on the next element, /// seeing if it passes the test. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [0i32, 1, 2]; /// /// let mut iter = a.iter().filter(|x| x.is_positive()); /// /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), None); /// ``` /// /// Because the closure passed to `filter()` takes a reference, and many /// iterators iterate over references, this leads to a possibly confusing /// situation, where the type of the closure is a double reference: /// /// ``` /// let a = [0, 1, 2]; /// /// let mut iter = a.iter().filter(|x| **x > 1); // need two *s! /// /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), None); /// ``` /// /// It's common to instead use destructuring on the argument to strip away /// one: /// /// ``` /// let a = [0, 1, 2]; /// /// let mut iter = a.iter().filter(|&x| *x > 1); // both & and * /// /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), None); /// ``` /// /// or both: /// /// ``` /// let a = [0, 1, 2]; /// /// let mut iter = a.iter().filter(|&&x| x > 1); // two &s /// /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), None); /// ``` /// /// of these layers. /// /// Note that `iter.filter(f).next()` is equivalent to `iter.find(f)`. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn filter<P>(self, predicate: P) -> Filter<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, { Filter::new(self, predicate) } /// Creates an iterator that both filters and maps. /// /// The closure must return an [`Option<T>`]. `filter_map` creates an /// iterator which calls this closure on each element. If the closure /// returns [`Some(element)`][`Some`], then that element is returned. If the /// closure returns [`None`], it will try again, and call the closure on the /// next element, seeing if it will return [`Some`]. /// /// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this /// part: /// /// [`filter`]: #method.filter /// [`map`]: #method.map /// /// > If the closure returns [`Some(element)`][`Some`], then that element is returned. /// /// In other words, it removes the [`Option<T>`] layer automatically. If your /// mapping is already returning an [`Option<T>`] and you want to skip over /// [`None`]s, then `filter_map` is much, much nicer to use. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = ["1", "lol", "3", "NaN", "5"]; /// /// let mut iter = a.iter().filter_map(|s| s.parse().ok()); /// /// assert_eq!(iter.next(), Some(1)); /// assert_eq!(iter.next(), Some(3)); /// assert_eq!(iter.next(), Some(5)); /// assert_eq!(iter.next(), None); /// ``` /// /// Here's the same example, but with [`filter`] and [`map`]: /// /// ``` /// let a = ["1", "lol", "3", "NaN", "5"]; /// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap()); /// assert_eq!(iter.next(), Some(1)); /// assert_eq!(iter.next(), Some(3)); /// assert_eq!(iter.next(), Some(5)); /// assert_eq!(iter.next(), None); /// ``` /// /// [`Option<T>`]: ../../std/option/enum.Option.html /// [`Some`]: ../../std/option/enum.Option.html#variant.Some /// [`None`]: ../../std/option/enum.Option.html#variant.None #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where Self: Sized, F: FnMut(Self::Item) -> Option<B>, { FilterMap::new(self, f) } /// Creates an iterator which gives the current iteration count as well as /// the next value. /// /// The iterator returned yields pairs `(i, val)`, where `i` is the /// current index of iteration and `val` is the value returned by the /// iterator. /// /// `enumerate()` keeps its count as a [`usize`]. If you want to count by a /// different sized integer, the [`zip`] function provides similar /// functionality. /// /// # Overflow Behavior /// /// The method does no guarding against overflows, so enumerating more than /// [`usize::MAX`] elements either produces the wrong result or panics. If /// debug assertions are enabled, a panic is guaranteed. /// /// # Panics /// /// The returned iterator might panic if the to-be-returned index would /// overflow a [`usize`]. /// /// [`usize::MAX`]: ../../std/usize/constant.MAX.html /// [`usize`]: ../../std/primitive.usize.html /// [`zip`]: #method.zip /// /// # Examples /// /// ``` /// let a = ['a', 'b', 'c']; /// /// let mut iter = a.iter().enumerate(); /// /// assert_eq!(iter.next(), Some((0, &'a'))); /// assert_eq!(iter.next(), Some((1, &'b'))); /// assert_eq!(iter.next(), Some((2, &'c'))); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn enumerate(self) -> Enumerate<Self> where Self: Sized, { Enumerate::new(self) } /// Creates an iterator which can use `peek` to look at the next element of /// the iterator without consuming it. /// /// Adds a [`peek`] method to an iterator. See its documentation for /// more information. /// /// Note that the underlying iterator is still advanced when [`peek`] is /// called for the first time: In order to retrieve the next element, /// [`next`] is called on the underlying iterator, hence any side effects (i.e. /// anything other than fetching the next value) of the [`next`] method /// will occur. /// /// [`peek`]: struct.Peekable.html#method.peek /// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next /// /// # Examples /// /// Basic usage: /// /// ``` /// let xs = [1, 2, 3]; /// /// let mut iter = xs.iter().peekable(); /// /// // peek() lets us see into the future /// assert_eq!(iter.peek(), Some(&&1)); /// assert_eq!(iter.next(), Some(&1)); /// /// assert_eq!(iter.next(), Some(&2)); /// /// // we can peek() multiple times, the iterator won't advance /// assert_eq!(iter.peek(), Some(&&3)); /// assert_eq!(iter.peek(), Some(&&3)); /// /// assert_eq!(iter.next(), Some(&3)); /// /// // after the iterator is finished, so is peek() /// assert_eq!(iter.peek(), None); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn peekable(self) -> Peekable<Self> where Self: Sized, { Peekable::new(self) } /// Creates an iterator that [`skip`]s elements based on a predicate. /// /// [`skip`]: #method.skip /// /// `skip_while()` takes a closure as an argument. It will call this /// closure on each element of the iterator, and ignore elements /// until it returns `false`. /// /// After `false` is returned, `skip_while()`'s job is over, and the /// rest of the elements are yielded. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [-1i32, 0, 1]; /// /// let mut iter = a.iter().skip_while(|x| x.is_negative()); /// /// assert_eq!(iter.next(), Some(&0)); /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), None); /// ``` /// /// Because the closure passed to `skip_while()` takes a reference, and many /// iterators iterate over references, this leads to a possibly confusing /// situation, where the type of the closure is a double reference: /// /// ``` /// let a = [-1, 0, 1]; /// /// let mut iter = a.iter().skip_while(|x| **x < 0); // need two *s! /// /// assert_eq!(iter.next(), Some(&0)); /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), None); /// ``` /// /// Stopping after an initial `false`: /// /// ``` /// let a = [-1, 0, 1, -2]; /// /// let mut iter = a.iter().skip_while(|x| **x < 0); /// /// assert_eq!(iter.next(), Some(&0)); /// assert_eq!(iter.next(), Some(&1)); /// /// // while this would have been false, since we already got a false, /// // skip_while() isn't used any more /// assert_eq!(iter.next(), Some(&-2)); /// /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, { SkipWhile::new(self, predicate) } /// Creates an iterator that yields elements based on a predicate. /// /// `take_while()` takes a closure as an argument. It will call this /// closure on each element of the iterator, and yield elements /// while it returns `true`. /// /// After `false` is returned, `take_while()`'s job is over, and the /// rest of the elements are ignored. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [-1i32, 0, 1]; /// /// let mut iter = a.iter().take_while(|x| x.is_negative()); /// /// assert_eq!(iter.next(), Some(&-1)); /// assert_eq!(iter.next(), None); /// ``` /// /// Because the closure passed to `take_while()` takes a reference, and many /// iterators iterate over references, this leads to a possibly confusing /// situation, where the type of the closure is a double reference: /// /// ``` /// let a = [-1, 0, 1]; /// /// let mut iter = a.iter().take_while(|x| **x < 0); // need two *s! /// /// assert_eq!(iter.next(), Some(&-1)); /// assert_eq!(iter.next(), None); /// ``` /// /// Stopping after an initial `false`: /// /// ``` /// let a = [-1, 0, 1, -2]; /// /// let mut iter = a.iter().take_while(|x| **x < 0); /// /// assert_eq!(iter.next(), Some(&-1)); /// /// // We have more elements that are less than zero, but since we already /// // got a false, take_while() isn't used any more /// assert_eq!(iter.next(), None); /// ``` /// /// Because `take_while()` needs to look at the value in order to see if it /// should be included or not, consuming iterators will see that it is /// removed: /// /// ``` /// let a = [1, 2, 3, 4]; /// let mut iter = a.iter(); /// /// let result: Vec<i32> = iter.by_ref() /// .take_while(|n| **n != 3) /// .cloned() /// .collect(); /// /// assert_eq!(result, &[1, 2]); /// /// let result: Vec<i32> = iter.cloned().collect(); /// /// assert_eq!(result, &[4]); /// ``` /// /// The `3` is no longer there, because it was consumed in order to see if /// the iteration should stop, but wasn't placed back into the iterator. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where Self: Sized, P: FnMut(&Self::Item) -> bool, { TakeWhile::new(self, predicate) } /// Creates an iterator that both yields elements based on a predicate and maps. /// /// `map_while()` takes a closure as an argument. It will call this /// closure on each element of the iterator, and yield elements /// while it returns [`Some(_)`][`Some`]. /// /// After [`None`] is returned, `map_while()`'s job is over, and the /// rest of the elements are ignored. /// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(iter_map_while)] /// let a = [-1i32, 4, 0, 1]; /// /// let mut iter = a.iter().map_while(|x| 16i32.checked_div(*x)); /// /// assert_eq!(iter.next(), Some(-16)); /// assert_eq!(iter.next(), Some(4)); /// assert_eq!(iter.next(), None); /// ``` /// /// Here's the same example, but with [`take_while`] and [`map`]: /// /// [`take_while`]: #method.take_while /// [`map`]: #method.map /// /// ``` /// let a = [-1i32, 4, 0, 1]; /// /// let mut iter = a.iter() /// .map(|x| 16i32.checked_div(*x)) /// .take_while(|x| x.is_some()) /// .map(|x| x.unwrap()); /// /// assert_eq!(iter.next(), Some(-16)); /// assert_eq!(iter.next(), Some(4)); /// assert_eq!(iter.next(), None); /// ``` /// /// Stopping after an initial [`None`]: /// /// ``` /// #![feature(iter_map_while)] /// use std::convert::TryFrom; /// /// let a = [0, -1, 1, -2]; /// /// let mut iter = a.iter().map_while(|x| u32::try_from(*x).ok()); /// /// assert_eq!(iter.next(), Some(0u32)); /// /// // We have more elements that are fit in u32, but since we already /// // got a None, map_while() isn't used any more /// assert_eq!(iter.next(), None); /// ``` /// /// Because `map_while()` needs to look at the value in order to see if it /// should be included or not, consuming iterators will see that it is /// removed: /// /// ``` /// #![feature(iter_map_while)] /// use std::convert::TryFrom; /// /// let a = [1, 2, -3, 4]; /// let mut iter = a.iter(); /// /// let result: Vec<u32> = iter.by_ref() /// .map_while(|n| u32::try_from(*n).ok()) /// .collect(); /// /// assert_eq!(result, &[1, 2]); /// /// let result: Vec<i32> = iter.cloned().collect(); /// /// assert_eq!(result, &[4]); /// ``` /// /// The `-3` is no longer there, because it was consumed in order to see if /// the iteration should stop, but wasn't placed back into the iterator. /// /// [`Some`]: ../../std/option/enum.Option.html#variant.Some /// [`None`]: ../../std/option/enum.Option.html#variant.None #[inline] #[unstable(feature = "iter_map_while", reason = "recently added", issue = "68537")] fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P> where Self: Sized, P: FnMut(Self::Item) -> Option<B>, { MapWhile::new(self, predicate) } /// Creates an iterator that skips the first `n` elements. /// /// After they have been consumed, the rest of the elements are yielded. /// Rather than overriding this method directly, instead override the `nth` method. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter().skip(2); /// /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn skip(self, n: usize) -> Skip<Self> where Self: Sized, { Skip::new(self, n) } /// Creates an iterator that yields its first `n` elements. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter().take(2); /// /// assert_eq!(iter.next(), Some(&1)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), None); /// ``` /// /// `take()` is often used with an infinite iterator, to make it finite: /// /// ``` /// let mut iter = (0..).take(3); /// /// assert_eq!(iter.next(), Some(0)); /// assert_eq!(iter.next(), Some(1)); /// assert_eq!(iter.next(), Some(2)); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn take(self, n: usize) -> Take<Self> where Self: Sized, { Take::new(self, n) } /// An iterator adaptor similar to [`fold`] that holds internal state and /// produces a new iterator. /// /// [`fold`]: #method.fold /// /// `scan()` takes two arguments: an initial value which seeds the internal /// state, and a closure with two arguments, the first being a mutable /// reference to the internal state and the second an iterator element. /// The closure can assign to the internal state to share state between /// iterations. /// /// On iteration, the closure will be applied to each element of the /// iterator and the return value from the closure, an [`Option`], is /// yielded by the iterator. /// /// [`Option`]: ../../std/option/enum.Option.html /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter().scan(1, |state, &x| { /// // each iteration, we'll multiply the state by the element /// *state = *state * x; /// /// // then, we'll yield the negation of the state /// Some(-*state) /// }); /// /// assert_eq!(iter.next(), Some(-1)); /// assert_eq!(iter.next(), Some(-2)); /// assert_eq!(iter.next(), Some(-6)); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F> where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>, { Scan::new(self, initial_state, f) } /// Creates an iterator that works like map, but flattens nested structure. /// /// The [`map`] adapter is very useful, but only when the closure /// argument produces values. If it produces an iterator instead, there's /// an extra layer of indirection. `flat_map()` will remove this extra layer /// on its own. /// /// You can think of `flat_map(f)` as the semantic equivalent /// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`. /// /// Another way of thinking about `flat_map()`: [`map`]'s closure returns /// one item for each element, and `flat_map()`'s closure returns an /// iterator for each element. /// /// [`map`]: #method.map /// [`flatten`]: #method.flatten /// /// # Examples /// /// Basic usage: /// /// ``` /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator /// let merged: String = words.iter() /// .flat_map(|s| s.chars()) /// .collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F> where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U, { FlatMap::new(self, f) } /// Creates an iterator that flattens nested structure. /// /// This is useful when you have an iterator of iterators or an iterator of /// things that can be turned into iterators and you want to remove one /// level of indirection. /// /// # Examples /// /// Basic usage: /// /// ``` /// let data = vec![vec![1, 2, 3, 4], vec![5, 6]]; /// let flattened = data.into_iter().flatten().collect::<Vec<u8>>(); /// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]); /// ``` /// /// Mapping and then flattening: /// /// ``` /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator /// let merged: String = words.iter() /// .map(|s| s.chars()) /// .flatten() /// .collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` /// /// You can also rewrite this in terms of [`flat_map()`], which is preferable /// in this case since it conveys intent more clearly: /// /// ``` /// let words = ["alpha", "beta", "gamma"]; /// /// // chars() returns an iterator /// let merged: String = words.iter() /// .flat_map(|s| s.chars()) /// .collect(); /// assert_eq!(merged, "alphabetagamma"); /// ``` /// /// Flattening once only removes one level of nesting: /// /// ``` /// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]; /// /// let d2 = d3.iter().flatten().collect::<Vec<_>>(); /// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]); /// /// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>(); /// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]); /// ``` /// /// Here we see that `flatten()` does not perform a "deep" flatten. /// Instead, only one level of nesting is removed. That is, if you /// `flatten()` a three-dimensional array the result will be /// two-dimensional and not one-dimensional. To get a one-dimensional /// structure, you have to `flatten()` again. /// /// [`flat_map()`]: #method.flat_map #[inline] #[stable(feature = "iterator_flatten", since = "1.29.0")] fn flatten(self) -> Flatten<Self> where Self: Sized, Self::Item: IntoIterator, { Flatten::new(self) } /// Creates an iterator which ends after the first [`None`]. /// /// After an iterator returns [`None`], future calls may or may not yield /// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a /// [`None`] is given, it will always return [`None`] forever. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some /// /// # Examples /// /// Basic usage: /// /// ``` /// // an iterator which alternates between Some and None /// struct Alternate { /// state: i32, /// } /// /// impl Iterator for Alternate { /// type Item = i32; /// /// fn next(&mut self) -> Option<i32> { /// let val = self.state; /// self.state = self.state + 1; /// /// // if it's even, Some(i32), else None /// if val % 2 == 0 { /// Some(val) /// } else { /// None /// } /// } /// } /// /// let mut iter = Alternate { state: 0 }; /// /// // we can see our iterator going back and forth /// assert_eq!(iter.next(), Some(0)); /// assert_eq!(iter.next(), None); /// assert_eq!(iter.next(), Some(2)); /// assert_eq!(iter.next(), None); /// /// // however, once we fuse it... /// let mut iter = iter.fuse(); /// /// assert_eq!(iter.next(), Some(4)); /// assert_eq!(iter.next(), None); /// /// // it will always return `None` after the first time. /// assert_eq!(iter.next(), None); /// assert_eq!(iter.next(), None); /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn fuse(self) -> Fuse<Self> where Self: Sized, { Fuse::new(self) } /// Does something with each element of an iterator, passing the value on. /// /// When using iterators, you'll often chain several of them together. /// While working on such code, you might want to check out what's /// happening at various parts in the pipeline. To do that, insert /// a call to `inspect()`. /// /// It's more common for `inspect()` to be used as a debugging tool than to /// exist in your final code, but applications may find it useful in certain /// situations when errors need to be logged before being discarded. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 4, 2, 3]; /// /// // this iterator sequence is complex. /// let sum = a.iter() /// .cloned() /// .filter(|x| x % 2 == 0) /// .fold(0, |sum, i| sum + i); /// /// println!("{}", sum); /// /// // let's add some inspect() calls to investigate what's happening /// let sum = a.iter() /// .cloned() /// .inspect(|x| println!("about to filter: {}", x)) /// .filter(|x| x % 2 == 0) /// .inspect(|x| println!("made it through filter: {}", x)) /// .fold(0, |sum, i| sum + i); /// /// println!("{}", sum); /// ``` /// /// This will print: /// /// ```text /// 6 /// about to filter: 1 /// about to filter: 4 /// made it through filter: 4 /// about to filter: 2 /// made it through filter: 2 /// about to filter: 3 /// 6 /// ``` /// /// Logging errors before discarding them: /// /// ``` /// let lines = ["1", "2", "a"]; /// /// let sum: i32 = lines /// .iter() /// .map(|line| line.parse::<i32>()) /// .inspect(|num| { /// if let Err(ref e) = *num { /// println!("Parsing error: {}", e); /// } /// }) /// .filter_map(Result::ok) /// .sum(); /// /// println!("Sum: {}", sum); /// ``` /// /// This will print: /// /// ```text /// Parsing error: invalid digit found in string /// Sum: 3 /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn inspect<F>(self, f: F) -> Inspect<Self, F> where Self: Sized, F: FnMut(&Self::Item), { Inspect::new(self, f) } /// Borrows an iterator, rather than consuming it. /// /// This is useful to allow applying iterator adaptors while still /// retaining ownership of the original iterator. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let iter = a.iter(); /// /// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i ); /// /// assert_eq!(sum, 6); /// /// // if we try to use iter again, it won't work. The following line /// // gives "error: use of moved value: `iter` /// // assert_eq!(iter.next(), None); /// /// // let's try that again /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// // instead, we add in a .by_ref() /// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i ); /// /// assert_eq!(sum, 3); /// /// // now this is just fine: /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), None); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn by_ref(&mut self) -> &mut Self where Self: Sized, { self } /// Transforms an iterator into a collection. /// /// `collect()` can take anything iterable, and turn it into a relevant /// collection. This is one of the more powerful methods in the standard /// library, used in a variety of contexts. /// /// The most basic pattern in which `collect()` is used is to turn one /// collection into another. You take a collection, call [`iter`] on it, /// do a bunch of transformations, and then `collect()` at the end. /// /// One of the keys to `collect()`'s power is that many things you might /// not think of as 'collections' actually are. For example, a [`String`] /// is a collection of [`char`]s. And a collection of /// [`Result<T, E>`][`Result`] can be thought of as single /// [`Result`]`<Collection<T>, E>`. See the examples below for more. /// /// Because `collect()` is so general, it can cause problems with type /// inference. As such, `collect()` is one of the few times you'll see /// the syntax affectionately known as the 'turbofish': `::<>`. This /// helps the inference algorithm understand specifically which collection /// you're trying to collect into. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let doubled: Vec<i32> = a.iter() /// .map(|&x| x * 2) /// .collect(); /// /// assert_eq!(vec![2, 4, 6], doubled); /// ``` /// /// Note that we needed the `: Vec<i32>` on the left-hand side. This is because /// we could collect into, for example, a [`VecDeque<T>`] instead: /// /// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html /// /// ``` /// use std::collections::VecDeque; /// /// let a = [1, 2, 3]; /// /// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect(); /// /// assert_eq!(2, doubled[0]); /// assert_eq!(4, doubled[1]); /// assert_eq!(6, doubled[2]); /// ``` /// /// Using the 'turbofish' instead of annotating `doubled`: /// /// ``` /// let a = [1, 2, 3]; /// /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>(); /// /// assert_eq!(vec![2, 4, 6], doubled); /// ``` /// /// Because `collect()` only cares about what you're collecting into, you can /// still use a partial type hint, `_`, with the turbofish: /// /// ``` /// let a = [1, 2, 3]; /// /// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>(); /// /// assert_eq!(vec![2, 4, 6], doubled); /// ``` /// /// Using `collect()` to make a [`String`]: /// /// ``` /// let chars = ['g', 'd', 'k', 'k', 'n']; /// /// let hello: String = chars.iter() /// .map(|&x| x as u8) /// .map(|x| (x + 1) as char) /// .collect(); /// /// assert_eq!("hello", hello); /// ``` /// /// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to /// see if any of them failed: /// /// ``` /// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")]; /// /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect(); /// /// // gives us the first error /// assert_eq!(Err("nope"), result); /// /// let results = [Ok(1), Ok(3)]; /// /// let result: Result<Vec<_>, &str> = results.iter().cloned().collect(); /// /// // gives us the list of answers /// assert_eq!(Ok(vec![1, 3]), result); /// ``` /// /// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next /// [`String`]: ../../std/string/struct.String.html /// [`char`]: ../../std/primitive.char.html /// [`Result`]: ../../std/result/enum.Result.html #[inline] #[stable(feature = "rust1", since = "1.0.0")] #[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"] fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized, { FromIterator::from_iter(self) } /// Consumes an iterator, creating two collections from it. /// /// The predicate passed to `partition()` can return `true`, or `false`. /// `partition()` returns a pair, all of the elements for which it returned /// `true`, and all of the elements for which it returned `false`. /// /// See also [`is_partitioned()`] and [`partition_in_place()`]. /// /// [`is_partitioned()`]: #method.is_partitioned /// [`partition_in_place()`]: #method.partition_in_place /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let (even, odd): (Vec<i32>, Vec<i32>) = a /// .iter() /// .partition(|&n| n % 2 == 0); /// /// assert_eq!(even, vec![2]); /// assert_eq!(odd, vec![1, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn partition<B, F>(self, f: F) -> (B, B) where Self: Sized, B: Default + Extend<Self::Item>, F: FnMut(&Self::Item) -> bool, { #[inline] fn extend<'a, T, B: Extend<T>>( mut f: impl FnMut(&T) -> bool + 'a, left: &'a mut B, right: &'a mut B, ) -> impl FnMut(T) + 'a { move |x| { if f(&x) { left.extend(Some(x)); } else { right.extend(Some(x)); } } } let mut left: B = Default::default(); let mut right: B = Default::default(); self.for_each(extend(f, &mut left, &mut right)); (left, right) } /// Reorders the elements of this iterator *in-place* according to the given predicate, /// such that all those that return `true` precede all those that return `false`. /// Returns the number of `true` elements found. /// /// The relative order of partitioned items is not maintained. /// /// See also [`is_partitioned()`] and [`partition()`]. /// /// [`is_partitioned()`]: #method.is_partitioned /// [`partition()`]: #method.partition /// /// # Examples /// /// ``` /// #![feature(iter_partition_in_place)] /// /// let mut a = [1, 2, 3, 4, 5, 6, 7]; /// /// // Partition in-place between evens and odds /// let i = a.iter_mut().partition_in_place(|&n| n % 2 == 0); /// /// assert_eq!(i, 3); /// assert!(a[..i].iter().all(|&n| n % 2 == 0)); // evens /// assert!(a[i..].iter().all(|&n| n % 2 == 1)); // odds /// ``` #[unstable(feature = "iter_partition_in_place", reason = "new API", issue = "62543")] fn partition_in_place<'a, T: 'a, P>(mut self, ref mut predicate: P) -> usize where Self: Sized + DoubleEndedIterator<Item = &'a mut T>, P: FnMut(&T) -> bool, { // FIXME: should we worry about the count overflowing? The only way to have more than // `usize::MAX` mutable references is with ZSTs, which aren't useful to partition... // These closure "factory" functions exist to avoid genericity in `Self`. #[inline] fn is_false<'a, T>( predicate: &'a mut impl FnMut(&T) -> bool, true_count: &'a mut usize, ) -> impl FnMut(&&mut T) -> bool + 'a { move |x| { let p = predicate(&**x); *true_count += p as usize; !p } } #[inline] fn is_true<T>(predicate: &mut impl FnMut(&T) -> bool) -> impl FnMut(&&mut T) -> bool + '_ { move |x| predicate(&**x) } // Repeatedly find the first `false` and swap it with the last `true`. let mut true_count = 0; while let Some(head) = self.find(is_false(predicate, &mut true_count)) { if let Some(tail) = self.rfind(is_true(predicate)) { crate::mem::swap(head, tail); true_count += 1; } else { break; } } true_count } /// Checks if the elements of this iterator are partitioned according to the given predicate, /// such that all those that return `true` precede all those that return `false`. /// /// See also [`partition()`] and [`partition_in_place()`]. /// /// [`partition()`]: #method.partition /// [`partition_in_place()`]: #method.partition_in_place /// /// # Examples /// /// ``` /// #![feature(iter_is_partitioned)] /// /// assert!("Iterator".chars().is_partitioned(char::is_uppercase)); /// assert!(!"IntoIterator".chars().is_partitioned(char::is_uppercase)); /// ``` #[unstable(feature = "iter_is_partitioned", reason = "new API", issue = "62544")] fn is_partitioned<P>(mut self, mut predicate: P) -> bool where Self: Sized, P: FnMut(Self::Item) -> bool, { // Either all items test `true`, or the first clause stops at `false` // and we check that there are no more `true` items after that. self.all(&mut predicate) || !self.any(predicate) } /// An iterator method that applies a function as long as it returns /// successfully, producing a single, final value. /// /// `try_fold()` takes two arguments: an initial value, and a closure with /// two arguments: an 'accumulator', and an element. The closure either /// returns successfully, with the value that the accumulator should have /// for the next iteration, or it returns failure, with an error value that /// is propagated back to the caller immediately (short-circuiting). /// /// The initial value is the value the accumulator will have on the first /// call. If applying the closure succeeded against every element of the /// iterator, `try_fold()` returns the final accumulator as success. /// /// Folding is useful whenever you have a collection of something, and want /// to produce a single value from it. /// /// # Note to Implementors /// /// Most of the other (forward) methods have default implementations in /// terms of this one, so try to implement this explicitly if it can /// do something better than the default `for` loop implementation. /// /// In particular, try to have this call `try_fold()` on the internal parts /// from which this iterator is composed. If multiple calls are needed, /// the `?` operator may be convenient for chaining the accumulator value /// along, but beware any invariants that need to be upheld before those /// early returns. This is a `&mut self` method, so iteration needs to be /// resumable after hitting an error here. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// // the checked sum of all of the elements of the array /// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x)); /// /// assert_eq!(sum, Some(6)); /// ``` /// /// Short-circuiting: /// /// ``` /// let a = [10, 20, 30, 100, 40, 50]; /// let mut it = a.iter(); /// /// // This sum overflows when adding the 100 element /// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x)); /// assert_eq!(sum, None); /// /// // Because it short-circuited, the remaining elements are still /// // available through the iterator. /// assert_eq!(it.len(), 2); /// assert_eq!(it.next(), Some(&40)); /// ``` #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok = B>, { let mut accum = init; while let Some(x) = self.next() { accum = f(accum, x)?; } Try::from_ok(accum) } /// An iterator method that applies a fallible function to each item in the /// iterator, stopping at the first error and returning that error. /// /// This can also be thought of as the fallible form of [`for_each()`] /// or as the stateless version of [`try_fold()`]. /// /// [`for_each()`]: #method.for_each /// [`try_fold()`]: #method.try_fold /// /// # Examples /// /// ``` /// use std::fs::rename; /// use std::io::{stdout, Write}; /// use std::path::Path; /// /// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"]; /// /// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x)); /// assert!(res.is_ok()); /// /// let mut it = data.iter().cloned(); /// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old"))); /// assert!(res.is_err()); /// // It short-circuited, so the remaining items are still in the iterator: /// assert_eq!(it.next(), Some("stale_bread.json")); /// ``` #[inline] #[stable(feature = "iterator_try_fold", since = "1.27.0")] fn try_for_each<F, R>(&mut self, f: F) -> R where Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok = ()>, { #[inline] fn call<T, R>(mut f: impl FnMut(T) -> R) -> impl FnMut((), T) -> R { move |(), x| f(x) } self.try_fold((), call(f)) } /// An iterator method that applies a function, producing a single, final value. /// /// `fold()` takes two arguments: an initial value, and a closure with two /// arguments: an 'accumulator', and an element. The closure returns the value that /// the accumulator should have for the next iteration. /// /// The initial value is the value the accumulator will have on the first /// call. /// /// After applying this closure to every element of the iterator, `fold()` /// returns the accumulator. /// /// This operation is sometimes called 'reduce' or 'inject'. /// /// Folding is useful whenever you have a collection of something, and want /// to produce a single value from it. /// /// Note: `fold()`, and similar methods that traverse the entire iterator, /// may not terminate for infinite iterators, even on traits for which a /// result is determinable in finite time. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// // the sum of all of the elements of the array /// let sum = a.iter().fold(0, |acc, x| acc + x); /// /// assert_eq!(sum, 6); /// ``` /// /// Let's walk through each step of the iteration here: /// /// | element | acc | x | result | /// |---------|-----|---|--------| /// | | 0 | | | /// | 1 | 0 | 1 | 1 | /// | 2 | 1 | 2 | 3 | /// | 3 | 3 | 3 | 6 | /// /// And so, our final result, `6`. /// /// It's common for people who haven't used iterators a lot to /// use a `for` loop with a list of things to build up a result. Those /// can be turned into `fold()`s: /// /// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for /// /// ``` /// let numbers = [1, 2, 3, 4, 5]; /// /// let mut result = 0; /// /// // for loop: /// for i in &numbers { /// result = result + i; /// } /// /// // fold: /// let result2 = numbers.iter().fold(0, |acc, &x| acc + x); /// /// // they're the same /// assert_eq!(result, result2); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn fold<B, F>(mut self, init: B, f: F) -> B where Self: Sized, F: FnMut(B, Self::Item) -> B, { #[inline] fn ok<B, T>(mut f: impl FnMut(B, T) -> B) -> impl FnMut(B, T) -> Result<B, !> { move |acc, x| Ok(f(acc, x)) } self.try_fold(init, ok(f)).unwrap() } /// Tests if every element of the iterator matches a predicate. /// /// `all()` takes a closure that returns `true` or `false`. It applies /// this closure to each element of the iterator, and if they all return /// `true`, then so does `all()`. If any of them return `false`, it /// returns `false`. /// /// `all()` is short-circuiting; in other words, it will stop processing /// as soon as it finds a `false`, given that no matter what else happens, /// the result will also be `false`. /// /// An empty iterator returns `true`. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// assert!(a.iter().all(|&x| x > 0)); /// /// assert!(!a.iter().all(|&x| x > 2)); /// ``` /// /// Stopping at the first `false`: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// assert!(!iter.all(|&x| x != 2)); /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next(), Some(&3)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn all<F>(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool, { #[inline] fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> { move |(), x| { if f(x) { LoopState::Continue(()) } else { LoopState::Break(()) } } } self.try_fold((), check(f)) == LoopState::Continue(()) } /// Tests if any element of the iterator matches a predicate. /// /// `any()` takes a closure that returns `true` or `false`. It applies /// this closure to each element of the iterator, and if any of them return /// `true`, then so does `any()`. If they all return `false`, it /// returns `false`. /// /// `any()` is short-circuiting; in other words, it will stop processing /// as soon as it finds a `true`, given that no matter what else happens, /// the result will also be `true`. /// /// An empty iterator returns `false`. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// assert!(a.iter().any(|&x| x > 0)); /// /// assert!(!a.iter().any(|&x| x > 5)); /// ``` /// /// Stopping at the first `true`: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// assert!(iter.any(|&x| x != 2)); /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next(), Some(&2)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn any<F>(&mut self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> bool, { #[inline] fn check<T>(mut f: impl FnMut(T) -> bool) -> impl FnMut((), T) -> LoopState<(), ()> { move |(), x| { if f(x) { LoopState::Break(()) } else { LoopState::Continue(()) } } } self.try_fold((), check(f)) == LoopState::Break(()) } /// Searches for an element of an iterator that satisfies a predicate. /// /// `find()` takes a closure that returns `true` or `false`. It applies /// this closure to each element of the iterator, and if any of them return /// `true`, then `find()` returns [`Some(element)`]. If they all return /// `false`, it returns [`None`]. /// /// `find()` is short-circuiting; in other words, it will stop processing /// as soon as the closure returns `true`. /// /// Because `find()` takes a reference, and many iterators iterate over /// references, this leads to a possibly confusing situation where the /// argument is a double reference. You can see this effect in the /// examples below, with `&&x`. /// /// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2)); /// /// assert_eq!(a.iter().find(|&&x| x == 5), None); /// ``` /// /// Stopping at the first `true`: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// assert_eq!(iter.find(|&&x| x == 2), Some(&2)); /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next(), Some(&3)); /// ``` /// /// Note that `iter.find(f)` is equivalent to `iter.filter(f).next()`. #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn find<P>(&mut self, predicate: P) -> Option<Self::Item> where Self: Sized, P: FnMut(&Self::Item) -> bool, { #[inline] fn check<T>( mut predicate: impl FnMut(&T) -> bool, ) -> impl FnMut((), T) -> LoopState<(), T> { move |(), x| { if predicate(&x) { LoopState::Break(x) } else { LoopState::Continue(()) } } } self.try_fold((), check(predicate)).break_value() } /// Applies function to the elements of iterator and returns /// the first non-none result. /// /// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`. /// /// /// # Examples /// /// ``` /// let a = ["lol", "NaN", "2", "5"]; /// /// let first_number = a.iter().find_map(|s| s.parse().ok()); /// /// assert_eq!(first_number, Some(2)); /// ``` #[inline] #[stable(feature = "iterator_find_map", since = "1.30.0")] fn find_map<B, F>(&mut self, f: F) -> Option<B> where Self: Sized, F: FnMut(Self::Item) -> Option<B>, { #[inline] fn check<T, B>(mut f: impl FnMut(T) -> Option<B>) -> impl FnMut((), T) -> LoopState<(), B> { move |(), x| match f(x) { Some(x) => LoopState::Break(x), None => LoopState::Continue(()), } } self.try_fold((), check(f)).break_value() } /// Applies function to the elements of iterator and returns /// the first non-none result or the first error. /// /// # Examples /// /// ``` /// #![feature(try_find)] /// /// let a = ["1", "2", "lol", "NaN", "5"]; /// /// let is_my_num = |s: &str, search: i32| -> Result<bool, std::num::ParseIntError> { /// Ok(s.parse::<i32>()? == search) /// }; /// /// let result = a.iter().try_find(|&&s| is_my_num(s, 2)); /// assert_eq!(result, Ok(Some(&"2"))); /// /// let result = a.iter().try_find(|&&s| is_my_num(s, 5)); /// assert!(result.is_err()); /// ``` #[inline] #[unstable(feature = "try_find", reason = "new API", issue = "63178")] fn try_find<F, E, R>(&mut self, mut f: F) -> Result<Option<Self::Item>, E> where Self: Sized, F: FnMut(&Self::Item) -> R, R: Try<Ok = bool, Error = E>, { self.try_for_each(move |x| match f(&x).into_result() { Ok(false) => LoopState::Continue(()), Ok(true) => LoopState::Break(Ok(x)), Err(x) => LoopState::Break(Err(x)), }) .break_value() .transpose() } /// Searches for an element in an iterator, returning its index. /// /// `position()` takes a closure that returns `true` or `false`. It applies /// this closure to each element of the iterator, and if one of them /// returns `true`, then `position()` returns [`Some(index)`]. If all of /// them return `false`, it returns [`None`]. /// /// `position()` is short-circuiting; in other words, it will stop /// processing as soon as it finds a `true`. /// /// # Overflow Behavior /// /// The method does no guarding against overflows, so if there are more /// than [`usize::MAX`] non-matching elements, it either produces the wrong /// result or panics. If debug assertions are enabled, a panic is /// guaranteed. /// /// # Panics /// /// This function might panic if the iterator has more than `usize::MAX` /// non-matching elements. /// /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some /// [`None`]: ../../std/option/enum.Option.html#variant.None /// [`usize::MAX`]: ../../std/usize/constant.MAX.html /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// assert_eq!(a.iter().position(|&x| x == 2), Some(1)); /// /// assert_eq!(a.iter().position(|&x| x == 5), None); /// ``` /// /// Stopping at the first `true`: /// /// ``` /// let a = [1, 2, 3, 4]; /// /// let mut iter = a.iter(); /// /// assert_eq!(iter.position(|&x| x >= 2), Some(1)); /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next(), Some(&3)); /// /// // The returned index depends on iterator state /// assert_eq!(iter.position(|&x| x == 4), Some(0)); /// /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn position<P>(&mut self, predicate: P) -> Option<usize> where Self: Sized, P: FnMut(Self::Item) -> bool, { #[inline] fn check<T>( mut predicate: impl FnMut(T) -> bool, ) -> impl FnMut(usize, T) -> LoopState<usize, usize> { // The addition might panic on overflow move |i, x| { if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(Add::add(i, 1)) } } } self.try_fold(0, check(predicate)).break_value() } /// Searches for an element in an iterator from the right, returning its /// index. /// /// `rposition()` takes a closure that returns `true` or `false`. It applies /// this closure to each element of the iterator, starting from the end, /// and if one of them returns `true`, then `rposition()` returns /// [`Some(index)`]. If all of them return `false`, it returns [`None`]. /// /// `rposition()` is short-circuiting; in other words, it will stop /// processing as soon as it finds a `true`. /// /// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2)); /// /// assert_eq!(a.iter().rposition(|&x| x == 5), None); /// ``` /// /// Stopping at the first `true`: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter(); /// /// assert_eq!(iter.rposition(|&x| x == 2), Some(1)); /// /// // we can still use `iter`, as there are more elements. /// assert_eq!(iter.next(), Some(&1)); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn rposition<P>(&mut self, predicate: P) -> Option<usize> where P: FnMut(Self::Item) -> bool, Self: Sized + ExactSizeIterator + DoubleEndedIterator, { // No need for an overflow check here, because `ExactSizeIterator` // implies that the number of elements fits into a `usize`. #[inline] fn check<T>( mut predicate: impl FnMut(T) -> bool, ) -> impl FnMut(usize, T) -> LoopState<usize, usize> { move |i, x| { let i = i - 1; if predicate(x) { LoopState::Break(i) } else { LoopState::Continue(i) } } } let n = self.len(); self.try_rfold(n, check(predicate)).break_value() } /// Returns the maximum element of an iterator. /// /// If several elements are equally maximum, the last element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// let b: Vec<u32> = Vec::new(); /// /// assert_eq!(a.iter().max(), Some(&3)); /// assert_eq!(b.iter().max(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord, { self.max_by(Ord::cmp) } /// Returns the minimum element of an iterator. /// /// If several elements are equally minimum, the first element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// let b: Vec<u32> = Vec::new(); /// /// assert_eq!(a.iter().min(), Some(&1)); /// assert_eq!(b.iter().min(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord, { self.min_by(Ord::cmp) } /// Returns the element that gives the maximum value from the /// specified function. /// /// If several elements are equally maximum, the last element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// ``` /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10); /// ``` #[inline] #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item> where Self: Sized, F: FnMut(&Self::Item) -> B, { #[inline] fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { move |x| (f(&x), x) } #[inline] fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { x_p.cmp(y_p) } let (_, x) = self.map(key(f)).max_by(compare)?; Some(x) } /// Returns the element that gives the maximum value with respect to the /// specified comparison function. /// /// If several elements are equally maximum, the last element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// ``` /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5); /// ``` #[inline] #[stable(feature = "iter_max_by", since = "1.15.0")] fn max_by<F>(self, compare: F) -> Option<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, { #[inline] fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { move |x, y| cmp::max_by(x, y, &mut compare) } fold1(self, fold(compare)) } /// Returns the element that gives the minimum value from the /// specified function. /// /// If several elements are equally minimum, the first element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// ``` /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0); /// ``` #[inline] #[stable(feature = "iter_cmp_by_key", since = "1.6.0")] fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item> where Self: Sized, F: FnMut(&Self::Item) -> B, { #[inline] fn key<T, B>(mut f: impl FnMut(&T) -> B) -> impl FnMut(T) -> (B, T) { move |x| (f(&x), x) } #[inline] fn compare<T, B: Ord>((x_p, _): &(B, T), (y_p, _): &(B, T)) -> Ordering { x_p.cmp(y_p) } let (_, x) = self.map(key(f)).min_by(compare)?; Some(x) } /// Returns the element that gives the minimum value with respect to the /// specified comparison function. /// /// If several elements are equally minimum, the first element is /// returned. If the iterator is empty, [`None`] is returned. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// ``` /// let a = [-3_i32, 0, 1, 5, -10]; /// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10); /// ``` #[inline] #[stable(feature = "iter_min_by", since = "1.15.0")] fn min_by<F>(self, compare: F) -> Option<Self::Item> where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering, { #[inline] fn fold<T>(mut compare: impl FnMut(&T, &T) -> Ordering) -> impl FnMut(T, T) -> T { move |x, y| cmp::min_by(x, y, &mut compare) } fold1(self, fold(compare)) } /// Reverses an iterator's direction. /// /// Usually, iterators iterate from left to right. After using `rev()`, /// an iterator will instead iterate from right to left. /// /// This is only possible if the iterator has an end, so `rev()` only /// works on [`DoubleEndedIterator`]s. /// /// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html /// /// # Examples /// /// ``` /// let a = [1, 2, 3]; /// /// let mut iter = a.iter().rev(); /// /// assert_eq!(iter.next(), Some(&3)); /// assert_eq!(iter.next(), Some(&2)); /// assert_eq!(iter.next(), Some(&1)); /// /// assert_eq!(iter.next(), None); /// ``` #[inline] #[stable(feature = "rust1", since = "1.0.0")] fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator, { Rev::new(self) } /// Converts an iterator of pairs into a pair of containers. /// /// `unzip()` consumes an entire iterator of pairs, producing two /// collections: one from the left elements of the pairs, and one /// from the right elements. /// /// This function is, in some sense, the opposite of [`zip`]. /// /// [`zip`]: #method.zip /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [(1, 2), (3, 4)]; /// /// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip(); /// /// assert_eq!(left, [1, 3]); /// assert_eq!(right, [2, 4]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where FromA: Default + Extend<A>, FromB: Default + Extend<B>, Self: Sized + Iterator<Item = (A, B)>, { fn extend<'a, A, B>( ts: &'a mut impl Extend<A>, us: &'a mut impl Extend<B>, ) -> impl FnMut((A, B)) + 'a { move |(t, u)| { ts.extend(Some(t)); us.extend(Some(u)); } } let mut ts: FromA = Default::default(); let mut us: FromB = Default::default(); self.for_each(extend(&mut ts, &mut us)); (ts, us) } /// Creates an iterator which copies all of its elements. /// /// This is useful when you have an iterator over `&T`, but you need an /// iterator over `T`. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let v_cloned: Vec<_> = a.iter().copied().collect(); /// /// // copied is the same as .map(|&x| x) /// let v_map: Vec<_> = a.iter().map(|&x| x).collect(); /// /// assert_eq!(v_cloned, vec![1, 2, 3]); /// assert_eq!(v_map, vec![1, 2, 3]); /// ``` #[stable(feature = "iter_copied", since = "1.36.0")] fn copied<'a, T: 'a>(self) -> Copied<Self> where Self: Sized + Iterator<Item = &'a T>, T: Copy, { Copied::new(self) } /// Creates an iterator which [`clone`]s all of its elements. /// /// This is useful when you have an iterator over `&T`, but you need an /// iterator over `T`. /// /// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let v_cloned: Vec<_> = a.iter().cloned().collect(); /// /// // cloned is the same as .map(|&x| x), for integers /// let v_map: Vec<_> = a.iter().map(|&x| x).collect(); /// /// assert_eq!(v_cloned, vec![1, 2, 3]); /// assert_eq!(v_map, vec![1, 2, 3]); /// ``` #[stable(feature = "rust1", since = "1.0.0")] fn cloned<'a, T: 'a>(self) -> Cloned<Self> where Self: Sized + Iterator<Item = &'a T>, T: Clone, { Cloned::new(self) } /// Repeats an iterator endlessly. /// /// Instead of stopping at [`None`], the iterator will instead start again, /// from the beginning. After iterating again, it will start at the /// beginning again. And again. And again. Forever. /// /// [`None`]: ../../std/option/enum.Option.html#variant.None /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// /// let mut it = a.iter().cycle(); /// /// assert_eq!(it.next(), Some(&1)); /// assert_eq!(it.next(), Some(&2)); /// assert_eq!(it.next(), Some(&3)); /// assert_eq!(it.next(), Some(&1)); /// assert_eq!(it.next(), Some(&2)); /// assert_eq!(it.next(), Some(&3)); /// assert_eq!(it.next(), Some(&1)); /// ``` #[stable(feature = "rust1", since = "1.0.0")] #[inline] fn cycle(self) -> Cycle<Self> where Self: Sized + Clone, { Cycle::new(self) } /// Sums the elements of an iterator. /// /// Takes each element, adds them together, and returns the result. /// /// An empty iterator returns the zero value of the type. /// /// # Panics /// /// When calling `sum()` and a primitive integer type is being returned, this /// method will panic if the computation overflows and debug assertions are /// enabled. /// /// # Examples /// /// Basic usage: /// /// ``` /// let a = [1, 2, 3]; /// let sum: i32 = a.iter().sum(); /// /// assert_eq!(sum, 6); /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] fn sum<S>(self) -> S where Self: Sized, S: Sum<Self::Item>, { Sum::sum(self) } /// Iterates over the entire iterator, multiplying all the elements /// /// An empty iterator returns the one value of the type. /// /// # Panics /// /// When calling `product()` and a primitive integer type is being returned, /// method will panic if the computation overflows and debug assertions are /// enabled. /// /// # Examples /// /// ``` /// fn factorial(n: u32) -> u32 { /// (1..=n).product() /// } /// assert_eq!(factorial(0), 1); /// assert_eq!(factorial(1), 1); /// assert_eq!(factorial(5), 120); /// ``` #[stable(feature = "iter_arith", since = "1.11.0")] fn product<P>(self) -> P where Self: Sized, P: Product<Self::Item>, { Product::product(self) } /// Lexicographically compares the elements of this `Iterator` with those /// of another. /// /// # Examples /// /// ``` /// use std::cmp::Ordering; /// /// assert_eq!([1].iter().cmp([1].iter()), Ordering::Equal); /// assert_eq!([1].iter().cmp([1, 2].iter()), Ordering::Less); /// assert_eq!([1, 2].iter().cmp([1].iter()), Ordering::Greater); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn cmp<I>(self, other: I) -> Ordering where I: IntoIterator<Item = Self::Item>, Self::Item: Ord, Self: Sized, { self.cmp_by(other, |x, y| x.cmp(&y)) } /// Lexicographically compares the elements of this `Iterator` with those /// of another with respect to the specified comparison function. /// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(iter_order_by)] /// /// use std::cmp::Ordering; /// /// let xs = [1, 2, 3, 4]; /// let ys = [1, 4, 9, 16]; /// /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| x.cmp(&y)), Ordering::Less); /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (x * x).cmp(&y)), Ordering::Equal); /// assert_eq!(xs.iter().cmp_by(&ys, |&x, &y| (2 * x).cmp(&y)), Ordering::Greater); /// ``` #[unstable(feature = "iter_order_by", issue = "64295")] fn cmp_by<I, F>(mut self, other: I, mut cmp: F) -> Ordering where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, I::Item) -> Ordering, { let mut other = other.into_iter(); loop { let x = match self.next() { None => { if other.next().is_none() { return Ordering::Equal; } else { return Ordering::Less; } } Some(val) => val, }; let y = match other.next() { None => return Ordering::Greater, Some(val) => val, }; match cmp(x, y) { Ordering::Equal => (), non_eq => return non_eq, } } } /// Lexicographically compares the elements of this `Iterator` with those /// of another. /// /// # Examples /// /// ``` /// use std::cmp::Ordering; /// /// assert_eq!([1.].iter().partial_cmp([1.].iter()), Some(Ordering::Equal)); /// assert_eq!([1.].iter().partial_cmp([1., 2.].iter()), Some(Ordering::Less)); /// assert_eq!([1., 2.].iter().partial_cmp([1.].iter()), Some(Ordering::Greater)); /// /// assert_eq!([std::f64::NAN].iter().partial_cmp([1.].iter()), None); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn partial_cmp<I>(self, other: I) -> Option<Ordering> where I: IntoIterator, Self::Item: PartialOrd<I::Item>, Self: Sized, { self.partial_cmp_by(other, |x, y| x.partial_cmp(&y)) } /// Lexicographically compares the elements of this `Iterator` with those /// of another with respect to the specified comparison function. /// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(iter_order_by)] /// /// use std::cmp::Ordering; /// /// let xs = [1.0, 2.0, 3.0, 4.0]; /// let ys = [1.0, 4.0, 9.0, 16.0]; /// /// assert_eq!( /// xs.iter().partial_cmp_by(&ys, |&x, &y| x.partial_cmp(&y)), /// Some(Ordering::Less) /// ); /// assert_eq!( /// xs.iter().partial_cmp_by(&ys, |&x, &y| (x * x).partial_cmp(&y)), /// Some(Ordering::Equal) /// ); /// assert_eq!( /// xs.iter().partial_cmp_by(&ys, |&x, &y| (2.0 * x).partial_cmp(&y)), /// Some(Ordering::Greater) /// ); /// ``` #[unstable(feature = "iter_order_by", issue = "64295")] fn partial_cmp_by<I, F>(mut self, other: I, mut partial_cmp: F) -> Option<Ordering> where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, I::Item) -> Option<Ordering>, { let mut other = other.into_iter(); loop { let x = match self.next() { None => { if other.next().is_none() { return Some(Ordering::Equal); } else { return Some(Ordering::Less); } } Some(val) => val, }; let y = match other.next() { None => return Some(Ordering::Greater), Some(val) => val, }; match partial_cmp(x, y) { Some(Ordering::Equal) => (), non_eq => return non_eq, } } } /// Determines if the elements of this `Iterator` are equal to those of /// another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().eq([1].iter()), true); /// assert_eq!([1].iter().eq([1, 2].iter()), false); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn eq<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialEq<I::Item>, Self: Sized, { self.eq_by(other, |x, y| x == y) } /// Determines if the elements of this `Iterator` are equal to those of /// another with respect to the specified equality function. /// /// # Examples /// /// Basic usage: /// /// ``` /// #![feature(iter_order_by)] /// /// let xs = [1, 2, 3, 4]; /// let ys = [1, 4, 9, 16]; /// /// assert!(xs.iter().eq_by(&ys, |&x, &y| x * x == y)); /// ``` #[unstable(feature = "iter_order_by", issue = "64295")] fn eq_by<I, F>(mut self, other: I, mut eq: F) -> bool where Self: Sized, I: IntoIterator, F: FnMut(Self::Item, I::Item) -> bool, { let mut other = other.into_iter(); loop { let x = match self.next() { None => return other.next().is_none(), Some(val) => val, }; let y = match other.next() { None => return false, Some(val) => val, }; if !eq(x, y) { return false; } } } /// Determines if the elements of this `Iterator` are unequal to those of /// another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().ne([1].iter()), false); /// assert_eq!([1].iter().ne([1, 2].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn ne<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialEq<I::Item>, Self: Sized, { !self.eq(other) } /// Determines if the elements of this `Iterator` are lexicographically /// less than those of another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().lt([1].iter()), false); /// assert_eq!([1].iter().lt([1, 2].iter()), true); /// assert_eq!([1, 2].iter().lt([1].iter()), false); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn lt<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialOrd<I::Item>, Self: Sized, { self.partial_cmp(other) == Some(Ordering::Less) } /// Determines if the elements of this `Iterator` are lexicographically /// less or equal to those of another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().le([1].iter()), true); /// assert_eq!([1].iter().le([1, 2].iter()), true); /// assert_eq!([1, 2].iter().le([1].iter()), false); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn le<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialOrd<I::Item>, Self: Sized, { matches!(self.partial_cmp(other), Some(Ordering::Less) | Some(Ordering::Equal)) } /// Determines if the elements of this `Iterator` are lexicographically /// greater than those of another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().gt([1].iter()), false); /// assert_eq!([1].iter().gt([1, 2].iter()), false); /// assert_eq!([1, 2].iter().gt([1].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn gt<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialOrd<I::Item>, Self: Sized, { self.partial_cmp(other) == Some(Ordering::Greater) } /// Determines if the elements of this `Iterator` are lexicographically /// greater than or equal to those of another. /// /// # Examples /// /// ``` /// assert_eq!([1].iter().ge([1].iter()), true); /// assert_eq!([1].iter().ge([1, 2].iter()), false); /// assert_eq!([1, 2].iter().ge([1].iter()), true); /// ``` #[stable(feature = "iter_order", since = "1.5.0")] fn ge<I>(self, other: I) -> bool where I: IntoIterator, Self::Item: PartialOrd<I::Item>, Self: Sized, { matches!(self.partial_cmp(other), Some(Ordering::Greater) | Some(Ordering::Equal)) } /// Checks if the elements of this iterator are sorted. /// /// That is, for each element `a` and its following element `b`, `a <= b` must hold. If the /// iterator yields exactly zero or one element, `true` is returned. /// /// Note that if `Self::Item` is only `PartialOrd`, but not `Ord`, the above definition /// implies that this function returns `false` if any two consecutive items are not /// comparable. /// /// # Examples /// /// ``` /// #![feature(is_sorted)] /// /// assert!([1, 2, 2, 9].iter().is_sorted()); /// assert!(![1, 3, 2, 4].iter().is_sorted()); /// assert!([0].iter().is_sorted()); /// assert!(std::iter::empty::<i32>().is_sorted()); /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted()); /// ``` #[inline] #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] fn is_sorted(self) -> bool where Self: Sized, Self::Item: PartialOrd, { self.is_sorted_by(PartialOrd::partial_cmp) } /// Checks if the elements of this iterator are sorted using the given comparator function. /// /// Instead of using `PartialOrd::partial_cmp`, this function uses the given `compare` /// function to determine the ordering of two elements. Apart from that, it's equivalent to /// [`is_sorted`]; see its documentation for more information. /// /// # Examples /// /// ``` /// #![feature(is_sorted)] /// /// assert!([1, 2, 2, 9].iter().is_sorted_by(|a, b| a.partial_cmp(b))); /// assert!(![1, 3, 2, 4].iter().is_sorted_by(|a, b| a.partial_cmp(b))); /// assert!([0].iter().is_sorted_by(|a, b| a.partial_cmp(b))); /// assert!(std::iter::empty::<i32>().is_sorted_by(|a, b| a.partial_cmp(b))); /// assert!(![0.0, 1.0, std::f32::NAN].iter().is_sorted_by(|a, b| a.partial_cmp(b))); /// ``` /// /// [`is_sorted`]: trait.Iterator.html#method.is_sorted #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] fn is_sorted_by<F>(mut self, mut compare: F) -> bool where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Option<Ordering>, { let mut last = match self.next() { Some(e) => e, None => return true, }; while let Some(curr) = self.next() { if let Some(Ordering::Greater) | None = compare(&last, &curr) { return false; } last = curr; } true } /// Checks if the elements of this iterator are sorted using the given key extraction /// function. /// /// Instead of comparing the iterator's elements directly, this function compares the keys of /// the elements, as determined by `f`. Apart from that, it's equivalent to [`is_sorted`]; see /// its documentation for more information. /// /// [`is_sorted`]: trait.Iterator.html#method.is_sorted /// /// # Examples /// /// ``` /// #![feature(is_sorted)] /// /// assert!(["c", "bb", "aaa"].iter().is_sorted_by_key(|s| s.len())); /// assert!(![-2i32, -1, 0, 3].iter().is_sorted_by_key(|n| n.abs())); /// ``` #[inline] #[unstable(feature = "is_sorted", reason = "new API", issue = "53485")] fn is_sorted_by_key<F, K>(self, f: F) -> bool where Self: Sized, F: FnMut(Self::Item) -> K, K: PartialOrd, { self.map(f).is_sorted() } } /// Fold an iterator without having to provide an initial value. #[inline] fn fold1<I, F>(mut it: I, f: F) -> Option<I::Item> where I: Iterator, F: FnMut(I::Item, I::Item) -> I::Item, { // start with the first element as our selection. This avoids // having to use `Option`s inside the loop, translating to a // sizeable performance gain (6x in one case). let first = it.next()?; Some(it.fold(first, f)) } #[stable(feature = "rust1", since = "1.0.0")] impl<I: Iterator + ?Sized> Iterator for &mut I { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<Self::Item> { (**self).nth(n) } }
32.073366
101
0.509851
396527ef449015aff4a83f574805ec7996c8b7ab
3,085
//! Middleware for setting headers on requests and responses. //! //! See [request] and [response] for more details. use http::{header::HeaderName, HeaderMap, HeaderValue, Request, Response}; pub mod request; pub mod response; #[doc(inline)] pub use self::{ request::{SetRequestHeader, SetRequestHeaderLayer}, response::{SetResponseHeader, SetResponseHeaderLayer}, }; /// Trait for producing header values. /// /// Used by [`SetRequestHeader`] and [`SetResponseHeader`]. /// /// This trait is implemented for closures with the correct type signature. Typically users will /// not have to implement this trait for their own types. /// /// It is also implemented directly for [`HeaderValue`]. When a fixed header value should be added /// to all responses, it can be supplied directly to the middleware. pub trait MakeHeaderValue<T> { /// Try to create a header value from the request or response. fn make_header_value(&mut self, message: &T) -> Option<HeaderValue>; } impl<F, T> MakeHeaderValue<T> for F where F: FnMut(&T) -> Option<HeaderValue>, { fn make_header_value(&mut self, message: &T) -> Option<HeaderValue> { self(message) } } impl<T> MakeHeaderValue<T> for HeaderValue { fn make_header_value(&mut self, _message: &T) -> Option<HeaderValue> { Some(self.clone()) } } impl<T> MakeHeaderValue<T> for Option<HeaderValue> { fn make_header_value(&mut self, _message: &T) -> Option<HeaderValue> { self.clone() } } #[derive(Debug, Clone, Copy)] enum InsertHeaderMode { Override, Append, IfNotPresent, } impl InsertHeaderMode { fn apply<T, M>(self, header_name: &HeaderName, target: &mut T, make: &mut M) where T: Headers, M: MakeHeaderValue<T>, { match self { InsertHeaderMode::Override => { if let Some(value) = make.make_header_value(target) { target.headers_mut().insert(header_name.clone(), value); } } InsertHeaderMode::IfNotPresent => { if !target.headers().contains_key(header_name) { if let Some(value) = make.make_header_value(target) { target.headers_mut().insert(header_name.clone(), value); } } } InsertHeaderMode::Append => { if let Some(value) = make.make_header_value(target) { target.headers_mut().append(header_name.clone(), value); } } } } } trait Headers { fn headers(&self) -> &HeaderMap; fn headers_mut(&mut self) -> &mut HeaderMap; } impl<B> Headers for Request<B> { fn headers(&self) -> &HeaderMap { Request::headers(self) } fn headers_mut(&mut self) -> &mut HeaderMap { Request::headers_mut(self) } } impl<B> Headers for Response<B> { fn headers(&self) -> &HeaderMap { Response::headers(self) } fn headers_mut(&mut self) -> &mut HeaderMap { Response::headers_mut(self) } }
27.792793
98
0.611345
8a64879c66b160ca684207f43c1734bf7c0cb924
609
// SPDX-License-Identifier: Apache-2.0 OR MIT // // Copyright (c) 2018-2021 by the author(s) // // Author(s): // - Andre Richter <andre.o.richter@gmail.com> //! Vector Base Address Register - EL1 //! //! Holds the vector base address for any exception that is taken to EL1. use tock_registers::interfaces::{Readable, Writeable}; pub struct Reg; impl Readable for Reg { type T = u64; type R = (); sys_coproc_read_raw!(u64, "VBAR_EL1", "x"); } impl Writeable for Reg { type T = u64; type R = (); sys_coproc_write_raw!(u64, "VBAR_EL1", "x"); } pub const VBAR_EL1: Reg = Reg {};
19.645161
73
0.643678
f5ea70aa0d235c4bc3d09aaf07647f844e1600a0
1,004
use std::collections::BTreeMap; #[derive(Clone)] pub struct StringyMap<K, V>(BTreeMap<String, (K, V)>); impl<K, V> StringyMap<K, V> where K: ToString, { pub fn new() -> Self { StringyMap(BTreeMap::new()) } pub fn insert(&mut self, k: K, v: V) -> Option<V> { let s = k.to_string(); self.0.insert(s, (k, v)).map(|(_, v)| v) } pub fn remove(&mut self, k: &K) -> Option<V> { let s = k.to_string(); self.0.remove(&s).map(|(_, v)| v) } pub fn iter(&self) -> impl Iterator<Item = &(K, V)> { self.0.values() } pub fn keys(&self) -> impl Iterator<Item = &K> { self.0.values().map(|(k, _)| k) } } impl<K, V, OK, OV> From<Vec<(OK, OV)>> for StringyMap<K, V> where OK: Into<K>, OV: Into<V>, K: ToString, { fn from(vec: Vec<(OK, OV)>) -> Self { let mut out = Self::new(); for (key, value) in vec { out.insert(key.into(), value.into()); } out } }
21.361702
59
0.491036
9c7c7f1dd4079a91a9d48759d5e699ab962b5304
606
//! Types common for XML processing. //! //! References: //! //! * [Extensible Markup Language (XML) 1.0 (Fifth Edition)][XML10] //! * [Namespaces in XML 1.0 (Third Edition)][XML-NAMES10] //! //! [XML10]: http://www.w3.org/TR/2008/REC-xml-20081126/ //! [XML-NAMES10]: http://www.w3.org/TR/2009/REC-xml-names-20091208/ #![warn(missing_docs)] #![warn(clippy::missing_docs_in_private_items)] #[macro_use] mod macros; pub mod attribute; pub mod cdata_section; pub mod char_data; pub mod comment; pub mod error; pub mod name; pub(crate) mod parser; pub mod reference; pub mod text_content; pub mod text_node;
23.307692
68
0.70462
2832b0504a57f7595c178e417f750c95db1e7cea
8,109
// Copyright 2020, The Tari Project // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the // following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following // disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the // following disclaimer in the documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE // USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //! # Dedup Cache //! //! Keeps track of messages seen before by this node and discards duplicates. mod dedup_cache; use std::task::Poll; pub use dedup_cache::DedupCacheDatabase; use digest::Digest; use futures::{future::BoxFuture, task::Context}; use log::*; use tari_comms::{pipeline::PipelineError, types::Challenge}; use tari_utilities::hex::Hex; use tower::{layer::Layer, Service, ServiceExt}; use crate::{ actor::DhtRequester, inbound::{DecryptedDhtMessage, DhtInboundMessage}, }; const LOG_TARGET: &str = "comms::dht::dedup"; pub fn hash_inbound_message(msg: &DhtInboundMessage) -> [u8; 32] { create_message_hash(&msg.dht_header.origin_mac, &msg.body) } pub fn create_message_hash(origin_mac: &[u8], body: &[u8]) -> [u8; 32] { Challenge::new().chain(origin_mac).chain(&body).finalize().into() } /// # DHT Deduplication middleware /// /// Takes in a `DecryptedDhtMessage` and checks the message signature cache for duplicates. /// If a duplicate message is detected, it is discarded. #[derive(Clone)] pub struct DedupMiddleware<S> { next_service: S, dht_requester: DhtRequester, allowed_message_occurrences: usize, } impl<S> DedupMiddleware<S> { pub fn new(service: S, dht_requester: DhtRequester, allowed_message_occurrences: usize) -> Self { Self { next_service: service, dht_requester, allowed_message_occurrences, } } } impl<S> Service<DecryptedDhtMessage> for DedupMiddleware<S> where S: Service<DecryptedDhtMessage, Response = (), Error = PipelineError> + Clone + Send + 'static, S::Future: Send, { type Error = PipelineError; type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>; type Response = (); fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, mut message: DecryptedDhtMessage) -> Self::Future { let next_service = self.next_service.clone(); let mut dht_requester = self.dht_requester.clone(); let allowed_message_occurrences = self.allowed_message_occurrences; Box::pin(async move { trace!( target: LOG_TARGET, "Inserting message hash {} for message {} (Trace: {})", message.dedup_hash.to_hex(), message.tag, message.dht_header.message_tag ); message.dedup_hit_count = dht_requester .add_message_to_dedup_cache(message.dedup_hash.clone(), message.source_peer.public_key.clone()) .await?; if message.dedup_hit_count as usize > allowed_message_occurrences { trace!( target: LOG_TARGET, "Received duplicate message {} (hit_count = {}) from peer '{}' (Trace: {}). Message discarded.", message.tag, message.dedup_hit_count, message.source_peer.node_id.short_str(), message.dht_header.message_tag, ); return Ok(()); } trace!( target: LOG_TARGET, "Passing message {} (hit_count = {}) onto next service (Trace: {})", message.tag, message.dedup_hit_count, message.dht_header.message_tag ); next_service.oneshot(message).await }) } } pub struct DedupLayer { dht_requester: DhtRequester, allowed_message_occurrences: usize, } impl DedupLayer { pub fn new(dht_requester: DhtRequester, allowed_message_occurrences: usize) -> Self { Self { dht_requester, allowed_message_occurrences, } } } impl<S> Layer<S> for DedupLayer { type Service = DedupMiddleware<S>; fn layer(&self, service: S) -> Self::Service { DedupMiddleware::new(service, self.dht_requester.clone(), self.allowed_message_occurrences) } } #[cfg(test)] mod test { use tari_comms::wrap_in_envelope_body; use tari_test_utils::panic_context; use tokio::runtime::Runtime; use super::*; use crate::{ envelope::DhtMessageFlags, test_utils::{create_dht_actor_mock, make_dht_inbound_message, make_node_identity, service_spy}, }; #[test] fn process_message() { let rt = Runtime::new().unwrap(); let spy = service_spy(); let (dht_requester, mock) = create_dht_actor_mock(1); let mock_state = mock.get_shared_state(); mock_state.set_number_of_message_hits(1); rt.spawn(mock.run()); let mut dedup = DedupLayer::new(dht_requester, 3).layer(spy.to_service::<PipelineError>()); panic_context!(cx); assert!(dedup.poll_ready(&mut cx).is_ready()); let node_identity = make_node_identity(); let inbound_message = make_dht_inbound_message(&node_identity, vec![], DhtMessageFlags::empty(), false, false); let decrypted_msg = DecryptedDhtMessage::succeeded(wrap_in_envelope_body!(vec![]), None, inbound_message); rt.block_on(dedup.call(decrypted_msg.clone())).unwrap(); assert_eq!(spy.call_count(), 1); mock_state.set_number_of_message_hits(4); rt.block_on(dedup.call(decrypted_msg)).unwrap(); assert_eq!(spy.call_count(), 1); // Drop dedup so that the DhtMock will stop running drop(dedup); } #[test] fn deterministic_hash() { const TEST_MSG: &[u8] = b"test123"; const EXPECTED_HASH: &str = "90cccd774db0ac8c6ea2deff0e26fc52768a827c91c737a2e050668d8c39c224"; let node_identity = make_node_identity(); let dht_message = make_dht_inbound_message( &node_identity, TEST_MSG.to_vec(), DhtMessageFlags::empty(), false, false, ); let decrypted1 = DecryptedDhtMessage::succeeded(wrap_in_envelope_body!(vec![]), None, dht_message); let node_identity = make_node_identity(); let dht_message = make_dht_inbound_message( &node_identity, TEST_MSG.to_vec(), DhtMessageFlags::empty(), false, false, ); let decrypted2 = DecryptedDhtMessage::succeeded(wrap_in_envelope_body!(vec![]), None, dht_message); assert_eq!(decrypted1.dedup_hash, decrypted2.dedup_hash); let subjects = &[decrypted1.dedup_hash, decrypted2.dedup_hash]; assert!(subjects.iter().all(|h| h.to_hex() == EXPECTED_HASH)); } }
36.527027
119
0.655815
fcdf8d324765ac360a58225557e9f6eddcb44fc7
136,562
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use snafu::{ResultExt, Snafu}; pub mod usage_details { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, expand: Option<&str>, filter: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, apply: Option<&str>, ) -> std::result::Result<UsageDetailsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/usageDetails", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, subscription_id: &str, billing_period_name: &str, expand: Option<&str>, filter: Option<&str>, apply: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, ) -> std::result::Result<UsageDetailsListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/usageDetails", operation_config.base_path(), subscription_id, billing_period_name ); let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod usage_details_by_billing_account { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, billing_account_id: &str, expand: Option<&str>, filter: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, apply: Option<&str>, ) -> std::result::Result<UsageDetailsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/usageDetails", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, billing_account_id: &str, billing_period_name: &str, expand: Option<&str>, filter: Option<&str>, apply: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, ) -> std::result::Result<UsageDetailsListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/usageDetails" , operation_config . base_path () , billing_account_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod usage_details_by_department { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, department_id: &str, expand: Option<&str>, filter: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, apply: Option<&str>, ) -> std::result::Result<UsageDetailsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/departments/{}/providers/Microsoft.Consumption/usageDetails", operation_config.base_path(), department_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, department_id: &str, billing_period_name: &str, expand: Option<&str>, filter: Option<&str>, apply: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, ) -> std::result::Result<UsageDetailsListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/departments/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/usageDetails" , operation_config . base_path () , department_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod usage_details_by_enrollment_account { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, enrollment_account_id: &str, expand: Option<&str>, filter: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, apply: Option<&str>, ) -> std::result::Result<UsageDetailsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/enrollmentAccounts/{}/providers/Microsoft.Consumption/usageDetails", operation_config.base_path(), enrollment_account_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, enrollment_account_id: &str, billing_period_name: &str, expand: Option<&str>, filter: Option<&str>, apply: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, ) -> std::result::Result<UsageDetailsListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/enrollmentAccounts/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/usageDetails" , operation_config . base_path () , enrollment_account_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(apply) = apply { url.query_pairs_mut().append_pair("$apply", apply); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: UsageDetailsListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod marketplaces { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, subscription_id: &str, ) -> std::result::Result<MarketplacesListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/marketplaces", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, subscription_id: &str, billing_period_name: &str, ) -> std::result::Result<MarketplacesListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/marketplaces", operation_config.base_path(), subscription_id, billing_period_name ); let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod marketplaces_by_billing_account { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, billing_account_id: &str, ) -> std::result::Result<MarketplacesListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/marketplaces", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, billing_account_id: &str, billing_period_name: &str, ) -> std::result::Result<MarketplacesListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/marketplaces" , operation_config . base_path () , billing_account_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod marketplaces_by_department { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, department_id: &str, ) -> std::result::Result<MarketplacesListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/departments/{}/providers/Microsoft.Consumption/marketplaces", operation_config.base_path(), department_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, department_id: &str, billing_period_name: &str, ) -> std::result::Result<MarketplacesListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/departments/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/marketplaces" , operation_config . base_path () , department_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod marketplaces_by_enrollment_accounts { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, enrollment_account_id: &str, ) -> std::result::Result<MarketplacesListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/enrollmentAccounts/{}/providers/Microsoft.Consumption/marketplaces", operation_config.base_path(), enrollment_account_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_billing_period( operation_config: &crate::OperationConfig, filter: Option<&str>, top: Option<i64>, skiptoken: Option<&str>, enrollment_account_id: &str, billing_period_name: &str, ) -> std::result::Result<MarketplacesListResult, list_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/enrollmentAccounts/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/marketplaces" , operation_config . base_path () , enrollment_account_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(list_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: MarketplacesListResult = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_billing_period::DeserializeError { body: rsp_body.clone() })?; list_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub async fn get_balances_by_billing_account( operation_config: &crate::OperationConfig, billing_account_id: &str, ) -> std::result::Result<Balance, get_balances_by_billing_account::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/balances", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(get_balances_by_billing_account::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get_balances_by_billing_account::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(get_balances_by_billing_account::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(get_balances_by_billing_account::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Balance = serde_json::from_slice(rsp_body).context(get_balances_by_billing_account::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get_balances_by_billing_account::DeserializeError { body: rsp_body.clone() })?; get_balances_by_billing_account::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get_balances_by_billing_account { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub mod get_balances_by_billing_account { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn by_billing_period( operation_config: &crate::OperationConfig, billing_account_id: &str, billing_period_name: &str, ) -> std::result::Result<Balance, by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/balances" , operation_config . base_path () , billing_account_id , billing_period_name) ; let mut url = url::Url::parse(url_str).context(by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Balance = serde_json::from_slice(rsp_body).context(by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(by_billing_period::DeserializeError { body: rsp_body.clone() })?; by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod reservations_summaries { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list_by_reservation_order( operation_config: &crate::OperationConfig, reservation_order_id: &str, grain: &str, filter: Option<&str>, ) -> std::result::Result<ReservationSummariesListResult, list_by_reservation_order::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Capacity/reservationorders/{}/providers/Microsoft.Consumption/reservationSummaries", operation_config.base_path(), reservation_order_id ); let mut url = url::Url::parse(url_str).context(list_by_reservation_order::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_reservation_order::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); url.query_pairs_mut().append_pair("grain", grain); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_reservation_order::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_reservation_order::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: ReservationSummariesListResult = serde_json::from_slice(rsp_body).context(list_by_reservation_order::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_reservation_order::DeserializeError { body: rsp_body.clone() })?; list_by_reservation_order::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_reservation_order { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_reservation_order_and_reservation( operation_config: &crate::OperationConfig, reservation_order_id: &str, reservation_id: &str, grain: &str, filter: Option<&str>, ) -> std::result::Result<ReservationSummariesListResult, list_by_reservation_order_and_reservation::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Capacity/reservationorders/{}/reservations/{}/providers/Microsoft.Consumption/reservationSummaries", operation_config.base_path(), reservation_order_id, reservation_id ); let mut url = url::Url::parse(url_str).context(list_by_reservation_order_and_reservation::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_reservation_order_and_reservation::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); url.query_pairs_mut().append_pair("grain", grain); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(list_by_reservation_order_and_reservation::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_reservation_order_and_reservation::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: ReservationSummariesListResult = serde_json::from_slice(rsp_body) .context(list_by_reservation_order_and_reservation::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body) .context(list_by_reservation_order_and_reservation::DeserializeError { body: rsp_body.clone() })?; list_by_reservation_order_and_reservation::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_reservation_order_and_reservation { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod reservations_details { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list_by_reservation_order( operation_config: &crate::OperationConfig, reservation_order_id: &str, filter: &str, ) -> std::result::Result<ReservationDetailsListResult, list_by_reservation_order::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Capacity/reservationorders/{}/providers/Microsoft.Consumption/reservationDetails", operation_config.base_path(), reservation_order_id ); let mut url = url::Url::parse(url_str).context(list_by_reservation_order::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_reservation_order::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); url.query_pairs_mut().append_pair("$filter", filter); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_reservation_order::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_reservation_order::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: ReservationDetailsListResult = serde_json::from_slice(rsp_body).context(list_by_reservation_order::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_reservation_order::DeserializeError { body: rsp_body.clone() })?; list_by_reservation_order::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_reservation_order { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_reservation_order_and_reservation( operation_config: &crate::OperationConfig, reservation_order_id: &str, reservation_id: &str, filter: &str, ) -> std::result::Result<ReservationDetailsListResult, list_by_reservation_order_and_reservation::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Capacity/reservationorders/{}/reservations/{}/providers/Microsoft.Consumption/reservationDetails", operation_config.base_path(), reservation_order_id, reservation_id ); let mut url = url::Url::parse(url_str).context(list_by_reservation_order_and_reservation::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_reservation_order_and_reservation::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); url.query_pairs_mut().append_pair("$filter", filter); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(list_by_reservation_order_and_reservation::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_reservation_order_and_reservation::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: ReservationDetailsListResult = serde_json::from_slice(rsp_body) .context(list_by_reservation_order_and_reservation::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body) .context(list_by_reservation_order_and_reservation::DeserializeError { body: rsp_body.clone() })?; list_by_reservation_order_and_reservation::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_reservation_order_and_reservation { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod reservation_recommendations { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, filter: Option<&str>, subscription_id: &str, ) -> std::result::Result<ReservationRecommendationsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/reservationRecommendations", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: ReservationRecommendationsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod budgets { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<BudgetsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/budgets", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: BudgetsListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_resource_group_name( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ) -> std::result::Result<BudgetsListResult, list_by_resource_group_name::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Consumption/budgets", operation_config.base_path(), subscription_id, resource_group_name ); let mut url = url::Url::parse(url_str).context(list_by_resource_group_name::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list_by_resource_group_name::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list_by_resource_group_name::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(list_by_resource_group_name::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: BudgetsListResult = serde_json::from_slice(rsp_body).context(list_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; list_by_resource_group_name::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_resource_group_name { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, budget_name: &str, ) -> std::result::Result<Budget, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, budget_name ); let mut url = url::Url::parse(url_str).context(get::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(get::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, budget_name: &str, parameters: &Budget, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, budget_name ); let mut url = url::Url::parse(url_str).context(create_or_update::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(create_or_update::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(create_or_update::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(create_or_update::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; create_or_update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create_or_update { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Budget), Created201(Budget), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, budget_name: &str, ) -> std::result::Result<(), delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, budget_name ); let mut url = url::Url::parse(url_str).context(delete::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(delete::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(delete::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(delete::DeserializeError { body: rsp_body.clone() })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get_by_resource_group_name( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, budget_name: &str, ) -> std::result::Result<Budget, get_by_resource_group_name::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, resource_group_name, budget_name ); let mut url = url::Url::parse(url_str).context(get_by_resource_group_name::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get_by_resource_group_name::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get_by_resource_group_name::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(get_by_resource_group_name::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body).context(get_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; get_by_resource_group_name::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get_by_resource_group_name { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create_or_update_by_resource_group_name( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, budget_name: &str, parameters: &Budget, ) -> std::result::Result<create_or_update_by_resource_group_name::Response, create_or_update_by_resource_group_name::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, resource_group_name, budget_name ); let mut url = url::Url::parse(url_str).context(create_or_update_by_resource_group_name::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(create_or_update_by_resource_group_name::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(create_or_update_by_resource_group_name::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(create_or_update_by_resource_group_name::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body) .context(create_or_update_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update_by_resource_group_name::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: Budget = serde_json::from_slice(rsp_body) .context(create_or_update_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update_by_resource_group_name::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body) .context(create_or_update_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; create_or_update_by_resource_group_name::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create_or_update_by_resource_group_name { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Budget), Created201(Budget), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete_by_resource_group_name( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, budget_name: &str, ) -> std::result::Result<(), delete_by_resource_group_name::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Consumption/budgets/{}", operation_config.base_path(), subscription_id, resource_group_name, budget_name ); let mut url = url::Url::parse(url_str).context(delete_by_resource_group_name::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(delete_by_resource_group_name::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .context(delete_by_resource_group_name::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(delete_by_resource_group_name::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(delete_by_resource_group_name::DeserializeError { body: rsp_body.clone() })?; delete_by_resource_group_name::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete_by_resource_group_name { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod operations { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<OperationListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/providers/Microsoft.Consumption/operations", operation_config.base_path(),); let mut url = url::Url::parse(url_str).context(list::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(list::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(list::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(list::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: OperationListResult = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(list::DeserializeError { body: rsp_body.clone() })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod price_sheet { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn get( operation_config: &crate::OperationConfig, expand: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, subscription_id: &str, ) -> std::result::Result<PriceSheetResult, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Consumption/pricesheets/default", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).context(get::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(get::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: PriceSheetResult = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn get_by_billing_period( operation_config: &crate::OperationConfig, expand: Option<&str>, skiptoken: Option<&str>, top: Option<i64>, subscription_id: &str, billing_period_name: &str, ) -> std::result::Result<PriceSheetResult, get_by_billing_period::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Billing/billingPeriods/{}/providers/Microsoft.Consumption/pricesheets/default", operation_config.base_path(), subscription_id, billing_period_name ); let mut url = url::Url::parse(url_str).context(get_by_billing_period::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get_by_billing_period::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); if let Some(expand) = expand { url.query_pairs_mut().append_pair("$expand", expand); } if let Some(skiptoken) = skiptoken { url.query_pairs_mut().append_pair("$skiptoken", skiptoken); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get_by_billing_period::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(get_by_billing_period::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: PriceSheetResult = serde_json::from_slice(rsp_body).context(get_by_billing_period::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get_by_billing_period::DeserializeError { body: rsp_body.clone() })?; get_by_billing_period::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get_by_billing_period { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod cost_tags { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn get(operation_config: &crate::OperationConfig, billing_account_id: &str) -> std::result::Result<CostTags, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/costTags", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(get::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(get::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: CostTags = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create_or_update( operation_config: &crate::OperationConfig, billing_account_id: &str, parameters: &CostTags, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.Billing/billingAccounts/{}/providers/Microsoft.Consumption/costTags", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(create_or_update::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(create_or_update::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(create_or_update::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .context(create_or_update::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: CostTags = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: CostTags = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(create_or_update::DeserializeError { body: rsp_body.clone() })?; create_or_update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create_or_update { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(CostTags), Created201(CostTags), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod tags { use crate::models::*; use snafu::{ResultExt, Snafu}; pub async fn get(operation_config: &crate::OperationConfig, billing_account_id: &str) -> std::result::Result<Tags, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/providers/Microsoft.CostManagement/billingAccounts/{}/providers/Microsoft.Consumption/tags", operation_config.base_path(), billing_account_id ); let mut url = url::Url::parse(url_str).context(get::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .context(get::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", operation_config.api_version()); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).context(get::BuildRequestError)?; let rsp = http_client.execute_request(req).await.context(get::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Tags = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: ErrorResponse = serde_json::from_slice(rsp_body).context(get::DeserializeError { body: rsp_body.clone() })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: http::StatusCode, value: models::ErrorResponse, }, ParseUrlError { source: url::ParseError, }, BuildRequestError { source: http::Error, }, ExecuteRequestError { source: Box<dyn std::error::Error + Sync + Send>, }, SerializeError { source: Box<dyn std::error::Error + Sync + Send>, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } }
42.122764
262
0.559592
387f480814ae767a9b927cd65217a26627cd9136
3,235
//! This module contains code to substitute new values into a //! `Canonical<'tcx, T>`. //! //! For an overview of what canonicalization is and how it fits into //! rustc, check out the [chapter in the rustc dev guide][c]. //! //! [c]: https://rust-lang.github.io/chalk/book/canonical_queries/canonicalization.html use crate::infer::canonical::{Canonical, CanonicalVarValues}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::GenericArgKind; use rustc_middle::ty::{self, TyCtxt}; pub(super) trait CanonicalExt<'tcx, V> { /// Instantiate the wrapped value, replacing each canonical value /// with the value given in `var_values`. fn substitute(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V where V: TypeFoldable<'tcx>; /// Allows one to apply a substitute to some subset of /// `self.value`. Invoke `projection_fn` with `self.value` to get /// a value V that is expressed in terms of the same canonical /// variables bound in `self` (usually this extracts from subset /// of `self`). Apply the substitution `var_values` to this value /// V, replacing each of the canonical variables. fn substitute_projected<T>( &self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>, projection_fn: impl FnOnce(&V) -> T, ) -> T where T: TypeFoldable<'tcx>; } impl<'tcx, V> CanonicalExt<'tcx, V> for Canonical<'tcx, V> { fn substitute(&self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>) -> V where V: TypeFoldable<'tcx>, { self.substitute_projected(tcx, var_values, |value| value.clone()) } fn substitute_projected<T>( &self, tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>, projection_fn: impl FnOnce(&V) -> T, ) -> T where T: TypeFoldable<'tcx>, { assert_eq!(self.variables.len(), var_values.len()); let value = projection_fn(&self.value); substitute_value(tcx, var_values, value) } } /// Substitute the values from `var_values` into `value`. `var_values` /// must be values for the set of canonical variables that appear in /// `value`. pub(super) fn substitute_value<'tcx, T>( tcx: TyCtxt<'tcx>, var_values: &CanonicalVarValues<'tcx>, value: T, ) -> T where T: TypeFoldable<'tcx>, { if var_values.var_values.is_empty() { value } else { let fld_r = |br: ty::BoundRegion| match var_values.var_values[br.assert_bound_var()].unpack() { GenericArgKind::Lifetime(l) => l, r => bug!("{:?} is a region but value is {:?}", br, r), }; let fld_t = |bound_ty: ty::BoundTy| match var_values.var_values[bound_ty.var].unpack() { GenericArgKind::Type(ty) => ty, r => bug!("{:?} is a type but value is {:?}", bound_ty, r), }; let fld_c = |bound_ct: ty::BoundVar, _| match var_values.var_values[bound_ct].unpack() { GenericArgKind::Const(ct) => ct, c => bug!("{:?} is a const but value is {:?}", bound_ct, c), }; tcx.replace_escaping_bound_vars(value, fld_r, fld_t, fld_c) } }
34.784946
96
0.61762
6a82dc2bd0105e43e61603cd47ab68e2953a91a8
2,058
use crate::{ compilation::{compile_validators, context::CompilationContext, JSONSchema}, error::{CompilationError, ErrorIterator}, keywords::{format_vec_of_validators, CompilationResult, InstancePath, Validators}, validator::Validate, }; use serde_json::{Map, Value}; pub(crate) struct AllOfValidator { schemas: Vec<Validators>, } impl AllOfValidator { #[inline] pub(crate) fn compile(schema: &Value, context: &CompilationContext) -> CompilationResult { if let Value::Array(items) = schema { let mut schemas = Vec::with_capacity(items.len()); for item in items { let validators = compile_validators(item, context)?; schemas.push(validators) } Ok(Box::new(AllOfValidator { schemas })) } else { Err(CompilationError::SchemaError) } } } impl Validate for AllOfValidator { fn is_valid(&self, schema: &JSONSchema, instance: &Value) -> bool { self.schemas.iter().all(move |validators| { validators .iter() .all(move |validator| validator.is_valid(schema, instance)) }) } fn validate<'a>( &self, schema: &'a JSONSchema, instance: &'a Value, instance_path: &InstancePath, ) -> ErrorIterator<'a> { let errors: Vec<_> = self .schemas .iter() .flat_map(move |validators| { validators .iter() .flat_map(move |validator| validator.validate(schema, instance, instance_path)) }) .collect(); Box::new(errors.into_iter()) } } impl ToString for AllOfValidator { fn to_string(&self) -> String { format!("allOf: [{}]", format_vec_of_validators(&self.schemas)) } } #[inline] pub(crate) fn compile( _: &Map<String, Value>, schema: &Value, context: &CompilationContext, ) -> Option<CompilationResult> { Some(AllOfValidator::compile(schema, context)) }
29.4
99
0.584062
8f3fc5f3c01f3a53169e205941894f74136f850c
19,929
use crate::error::*; use crate::object::{PlainRef, Resolve, Object, NoResolve, ObjectWrite, Updater}; use std::collections::{btree_map, BTreeMap}; use std::{str, fmt, io}; use std::ops::{Index, Range}; use chrono::{DateTime, FixedOffset}; use std::ops::Deref; use std::convert::TryInto; use std::borrow::{Borrow, Cow}; use itertools::Itertools; #[derive(Clone, Debug)] pub enum Primitive { Null, Integer (i32), Number (f32), Boolean (bool), String (PdfString), Stream (PdfStream), Dictionary (Dictionary), Array (Vec<Primitive>), Reference (PlainRef), Name (String), } impl fmt::Display for Primitive { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Primitive::Null => write!(f, "null"), Primitive::Integer(i) => i.fmt(f), Primitive::Number(n) => n.fmt(f), Primitive::Boolean(b) => b.fmt(f), Primitive::String(ref s) => write!(f, "{:?}", s), Primitive::Stream(_) => write!(f, "stream"), Primitive::Dictionary(ref d) => d.fmt(f), Primitive::Array(ref arr) => write!(f, "[{}]", arr.iter().format(", ")), Primitive::Reference(r) => write!(f, "@{}", r.id), Primitive::Name(ref s) => write!(f, "/{}", s) } } } impl Primitive { pub fn serialize(&self, out: &mut impl io::Write, level: usize) -> Result<()> { match self { Primitive::Null => write!(out, "null")?, Primitive::Integer(i) => write!(out, "{}", i)?, Primitive::Number(n) => write!(out, "{}", n)?, Primitive::Boolean(b) => write!(out, "{}", b)?, Primitive::String(ref s) => s.serialize(out)?, Primitive::Stream(ref s) => s.serialize(out)?, Primitive::Dictionary(ref d) => d.serialize(out, level)?, Primitive::Array(ref arr) => serialize_list(arr, out, level)?, Primitive::Reference(r) => write!(out, "{} {} R", r.id, r.gen)?, Primitive::Name(ref s) => serialize_name(s, out)?, } Ok(()) } pub fn array<O, T, I, U>(i: I, update: &mut U) -> Result<Primitive> where O: ObjectWrite, I: Iterator<Item=T>, T: Borrow<O>, U: Updater { i.map(|t| t.borrow().to_primitive(update)).collect::<Result<_>>().map(Primitive::Array) } pub fn name(name: impl Into<String>) -> Primitive { Primitive::Name(name.into()) } } fn serialize_list(arr: &[Primitive], out: &mut impl io::Write, level: usize) -> Result<()> { let mut parts = arr.iter(); write!(out, "{:w$}[", "", w=2*level)?; if let Some(first) = parts.next() { first.serialize(out, level+1)?; } for p in parts { write!(out, " ")?; p.serialize(out, level+1)?; } write!(out, "]")?; Ok(()) } pub fn serialize_name(s: &str, out: &mut impl io::Write) -> Result<()> { write!(out, "/")?; for b in s.chars() { match b { '\\' | '(' | ')' => write!(out, r"\")?, c if c > '~' => panic!("only ASCII"), _ => () } write!(out, "{}", b)?; } Ok(()) } #[derive(Debug)] pub struct Name<'a>(&'a str); impl<'a> Deref for Name<'a> { type Target = str; fn deref(&self) -> &str { &self.0 } } impl<'a> fmt::Display for Name<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "/{}", self.0) } } /// Primitive Dictionary type. #[derive(Default, Clone)] pub struct Dictionary { dict: BTreeMap<String, Primitive> } impl Dictionary { pub fn new() -> Dictionary { Dictionary { dict: BTreeMap::new()} } pub fn len(&self) -> usize { self.dict.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn get(&self, key: &str) -> Option<&Primitive> { self.dict.get(key) } pub fn insert(&mut self, key: impl Into<String>, val: Primitive) -> Option<Primitive> { self.dict.insert(key.into(), val) } pub fn iter(&self) -> btree_map::Iter<String, Primitive> { self.dict.iter() } pub fn remove(&mut self, key: &str) -> Option<Primitive> { self.dict.remove(key) } /// like remove, but takes the name of the calling type and returns `PdfError::MissingEntry` if the entry is not found pub fn require(&mut self, typ: &'static str, key: &str) -> Result<Primitive> { self.remove(key).ok_or( PdfError::MissingEntry { typ, field: key.into() } ) } /// assert that the given key/value pair is in the dictionary (`required=true`), /// or the key is not present at all (`required=false`) pub fn expect(&self, typ: &'static str, key: &str, value: &str, required: bool) -> Result<()> { match self.dict.get(key) { Some(ty) => { let ty = ty.as_name()?; if ty != value { Err(PdfError::KeyValueMismatch { key: key.into(), value: value.into(), found: ty.into() }) } else { Ok(()) } }, None if required => Err(PdfError::MissingEntry { typ, field: key.into() }), None => Ok(()) } } } impl ObjectWrite for Dictionary { fn to_primitive(&self, update: &mut impl Updater) -> Result<Primitive> { Ok(Primitive::Dictionary(self.clone())) } } impl Deref for Dictionary { type Target = BTreeMap<String, Primitive>; fn deref(&self) -> &BTreeMap<String, Primitive> { &self.dict } } impl Dictionary { fn serialize(&self, out: &mut impl io::Write, level: usize) -> Result<()> { write!(out, "<<\n")?; for (key, val) in self.iter() { write!(out, "{:w$}/{} ", "", key, w=2*level+2)?; val.serialize(out, level+2)?; out.write_all(b"\n")?; } write!(out, "{:w$}>>\n", "", w=2*level)?; Ok(()) } } impl fmt::Debug for Dictionary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{{")?; for (k, v) in self { writeln!(f, "{:>15}: {}", k, v)?; } write!(f, "}}") } } impl fmt::Display for Dictionary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<{}>", self.iter().format_with(", ", |(k, v), f| f(&format_args!("{}={}", k, v)))) } } impl<'a> Index<&'a str> for Dictionary { type Output = Primitive; fn index(&self, idx: &'a str) -> &Primitive { self.dict.index(idx) } } impl IntoIterator for Dictionary { type Item = (String, Primitive); type IntoIter = btree_map::IntoIter<String, Primitive>; fn into_iter(self) -> Self::IntoIter { self.dict.into_iter() } } impl<'a> IntoIterator for &'a Dictionary { type Item = (&'a String, &'a Primitive); type IntoIter = btree_map::Iter<'a, String, Primitive>; fn into_iter(self) -> Self::IntoIter { (&self.dict).iter() } } /// Primitive Stream (as opposed to the higher-level `Stream`) #[derive(Clone, Debug)] pub struct PdfStream { pub info: Dictionary, pub data: Vec<u8>, } impl Object for PdfStream { fn from_primitive(p: Primitive, resolve: &impl Resolve) -> Result<Self> { match p { Primitive::Stream (stream) => Ok(stream), Primitive::Reference (r) => PdfStream::from_primitive(resolve.resolve(r)?, resolve), p => Err(PdfError::UnexpectedPrimitive {expected: "Stream", found: p.get_debug_name()}) } } } impl PdfStream { pub fn serialize(&self, out: &mut impl io::Write) -> Result<()> { self.info.serialize(out, 0)?; writeln!(out, "stream")?; out.write_all(&self.data)?; writeln!(out, "\nendstream")?; Ok(()) } } macro_rules! unexpected_primitive { ($expected:ident, $found:expr) => ( Err(PdfError::UnexpectedPrimitive { expected: stringify!($expected), found: $found }) ) } /// Primitive String type. #[derive(Clone)] pub struct PdfString { pub data: Vec<u8>, } impl fmt::Debug for PdfString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\"")?; for &b in &self.data { match b { b'"' => write!(f, "\\\"")?, b' ' ..= b'~' => write!(f, "{}", b as char)?, o @ 0 ..= 7 => write!(f, "\\{}", o)?, x => write!(f, "\\x{:02x}", x)? } } write!(f, "\"") } } impl Object for PdfString { fn from_primitive(p: Primitive, r: &impl Resolve) -> Result<Self> { match p { Primitive::String (string) => Ok(string), Primitive::Reference(id) => PdfString::from_primitive(r.resolve(id)?, &NoResolve), _ => unexpected_primitive!(String, p.get_debug_name()), } } } impl ObjectWrite for PdfString { fn to_primitive(&self, update: &mut impl Updater) -> Result<Primitive> { Ok(Primitive::String(self.clone())) } } impl PdfString { pub fn serialize(&self, out: &mut impl io::Write) -> Result<()> { if self.data.iter().any(|&b| b >= 0x80) { write!(out, "<")?; for &b in &self.data { write!(out, "{:02x}", b)?; } write!(out, ">")?; } else { write!(out, r"(")?; for &b in &self.data { match b { b'\\' | b'(' | b')' => write!(out, r"\")?, _ => () } out.write_all(&[b])?; } write!(out, r")")?; } Ok(()) } } impl AsRef<[u8]> for PdfString { fn as_ref(&self) -> &[u8] { self.as_bytes() } } impl PdfString { pub fn new(data: Vec<u8>) -> PdfString { PdfString { data } } pub fn as_bytes(&self) -> &[u8] { &self.data } pub fn as_str(&self) -> Result<Cow<str>> { if self.data.starts_with(&[0xfe, 0xff]) { // FIXME: avoid extra allocation let utf16: Vec<u16> = self.data[2..].chunks(2).map(|c| (c[0] as u16) << 8 | c[1] as u16).collect(); Ok(Cow::Owned(String::from_utf16(&utf16)?)) } else { Ok(Cow::Borrowed(str::from_utf8(&self.data)?)) } } pub fn into_bytes(self) -> Vec<u8> { self.data } pub fn into_string(self) -> Result<String> { Ok(self.as_str()?.into_owned()) } } // TODO: // Noticed some inconsistency here.. I think to_* and as_* should not take Resolve, and not accept // Reference. Only from_primitive() for the respective type resolves References. impl Primitive { /// For debugging / error messages: get the name of the variant pub fn get_debug_name(&self) -> &'static str { match *self { Primitive::Null => "Null", Primitive::Integer (..) => "Integer", Primitive::Number (..) => "Number", Primitive::Boolean (..) => "Boolean", Primitive::String (..) => "String", Primitive::Stream (..) => "Stream", Primitive::Dictionary (..) => "Dictionary", Primitive::Array (..) => "Array", Primitive::Reference (..) => "Reference", Primitive::Name (..) => "Name", } } pub fn as_integer(&self) -> Result<i32> { match *self { Primitive::Integer(n) => Ok(n), ref p => unexpected_primitive!(Integer, p.get_debug_name()) } } pub fn as_u32(&self) -> Result<u32> { match *self { Primitive::Integer(n) if n >= 0 => Ok(n as u32), Primitive::Integer(_) => bail!("negative integer"), ref p => unexpected_primitive!(Integer, p.get_debug_name()) } } pub fn as_number(&self) -> Result<f32> { match *self { Primitive::Integer(n) => Ok(n as f32), Primitive::Number(f) => Ok(f), ref p => unexpected_primitive!(Number, p.get_debug_name()) } } pub fn as_bool(&self) -> Result<bool> { match *self { Primitive::Boolean (b) => Ok(b), ref p => unexpected_primitive!(Number, p.get_debug_name()) } } pub fn as_name(&self) -> Result<&str> { match self { Primitive::Name(ref name) => Ok(name.as_str()), p => unexpected_primitive!(Name, p.get_debug_name()) } } pub fn as_string(&self) -> Result<&PdfString> { match self { Primitive::String(ref data) => Ok(data), p => unexpected_primitive!(String, p.get_debug_name()) } } pub fn as_str(&self) -> Option<Cow<str>> { self.as_string().ok().and_then(|s| s.as_str().ok()) } /// Does not accept a Reference pub fn as_array(&self) -> Result<&[Primitive]> { match self { Primitive::Array(ref v) => Ok(v), p => unexpected_primitive!(Array, p.get_debug_name()) } } pub fn into_reference(self) -> Result<PlainRef> { match self { Primitive::Reference(id) => Ok(id), p => unexpected_primitive!(Reference, p.get_debug_name()) } } /// Does accept a Reference pub fn into_array(self, r: &impl Resolve) -> Result<Vec<Primitive>> { match self { Primitive::Array(v) => Ok(v), Primitive::Reference(id) => r.resolve(id)?.into_array(r), p => unexpected_primitive!(Array, p.get_debug_name()) } } pub fn into_dictionary(self, r: &impl Resolve) -> Result<Dictionary> { match self { Primitive::Dictionary(dict) => Ok(dict), Primitive::Reference(id) => r.resolve(id)?.into_dictionary(r), p => unexpected_primitive!(Dictionary, p.get_debug_name()) } } /// Doesn't accept a Reference pub fn into_name(self) -> Result<String> { match self { Primitive::Name(name) => Ok(name), p => unexpected_primitive!(Name, p.get_debug_name()) } } /// Doesn't accept a Reference pub fn into_string(self) -> Result<PdfString> { match self { Primitive::String(data) => Ok(data), p => unexpected_primitive!(String, p.get_debug_name()) } } /// Doesn't accept a Reference pub fn into_stream(self, _r: &impl Resolve) -> Result<PdfStream> { match self { Primitive::Stream (s) => Ok(s), // Primitive::Reference (id) => r.resolve(id)?.to_stream(r), p => unexpected_primitive!(Stream, p.get_debug_name()) } } } impl From<i32> for Primitive { fn from(x: i32) -> Primitive { Primitive::Integer(x) } } impl From<f32> for Primitive { fn from(x: f32) -> Primitive { Primitive::Number(x) } } impl From<bool> for Primitive { fn from(x: bool) -> Primitive { Primitive::Boolean(x) } } impl<'a> From<Name<'a>> for Primitive { fn from(Name(s): Name<'a>) -> Primitive { Primitive::Name(s.into()) } } impl From<PdfString> for Primitive { fn from(x: PdfString) -> Primitive { Primitive::String (x) } } impl From<PdfStream> for Primitive { fn from(x: PdfStream) -> Primitive { Primitive::Stream (x) } } impl From<Dictionary> for Primitive { fn from(x: Dictionary) -> Primitive { Primitive::Dictionary (x) } } impl From<Vec<Primitive>> for Primitive { fn from(x: Vec<Primitive>) -> Primitive { Primitive::Array (x) } } impl From<PlainRef> for Primitive { fn from(x: PlainRef) -> Primitive { Primitive::Reference (x) } } impl From<String> for Primitive { fn from(x: String) -> Primitive { Primitive::Name (x) } } impl<'a> TryInto<f32> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<f32> { self.as_number() } } impl<'a> TryInto<i32> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<i32> { self.as_integer() } } impl<'a> TryInto<Name<'a>> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<Name<'a>> { match self { &Primitive::Name(ref s) => Ok(Name(s.as_str())), p => Err(PdfError::UnexpectedPrimitive { expected: "Name", found: p.get_debug_name() }) } } } impl<'a> TryInto<&'a [Primitive]> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<&'a [Primitive]> { self.as_array() } } impl<'a> TryInto<&'a [u8]> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<&'a [u8]> { match self { Primitive::Name(ref s) => Ok(s.as_bytes()), Primitive::String(ref s) => Ok(s.as_bytes()), ref p => Err(PdfError::UnexpectedPrimitive { expected: "Name or String", found: p.get_debug_name() }) } } } impl<'a> TryInto<Cow<'a, str>> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<Cow<'a, str>> { match self { Primitive::Name(ref s) => Ok(Cow::Borrowed(&*s)), Primitive::String(ref s) => Ok(s.as_str()?), ref p => Err(PdfError::UnexpectedPrimitive { expected: "Name or String", found: p.get_debug_name() }) } } } impl<'a> TryInto<String> for &'a Primitive { type Error = PdfError; fn try_into(self) -> Result<String> { match self { Primitive::Name(ref s) => Ok(s.clone()), Primitive::String(ref s) => Ok(s.as_str()?.into_owned()), ref p => Err(PdfError::UnexpectedPrimitive { expected: "Name or String", found: p.get_debug_name() }) } } } fn parse_or<T: str::FromStr + Clone>(buffer: &str, range: Range<usize>, default: T) -> T { buffer.get(range) .map(|s| str::parse::<T>(s).unwrap_or_else(|_| default.clone())) .unwrap_or(default) } impl Object for DateTime<FixedOffset> { fn from_primitive(p: Primitive, _: &impl Resolve) -> Result<Self> { use chrono::{NaiveDateTime, NaiveDate, NaiveTime}; match p { Primitive::String (PdfString {data}) => { let s = str::from_utf8(&data)?; let len = s.len(); if len > 2 && &s[0..2] == "D:" { let year = match s.get(2..6) { Some(year) => { str::parse::<i32>(year)? } None => bail!("Missing obligatory year in date") }; let month = parse_or(s, 6..8, 1); let day = parse_or(s, 8..10, 1); let hour = parse_or(s, 10..12, 0); let minute = parse_or(s, 12..14, 0); let second = parse_or(s, 14..16, 0); let tz_hour = parse_or(s, 16..18, 0); let tz_minute = parse_or(s, 19..21, 0); let tz = FixedOffset::east(tz_hour * 60 + tz_minute); Ok(DateTime::from_utc( NaiveDateTime::new(NaiveDate::from_ymd(year, month, day), NaiveTime::from_hms(hour, minute, second)), tz )) } else { bail!("Failed parsing date"); } } _ => unexpected_primitive!(String, p.get_debug_name()), } } }
31.683625
122
0.510161
6a03b0a23d3d04b90798ba99144890a81e37c0ae
1,159
use std::fmt; use std::time::Instant; struct Struct { data: [u8; 32], } impl fmt::Display for Struct { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.data) } } fn main() { // -------------------------------- println!("loge"); ::std::env::set_var("RUST_LOG", "trace"); ::std::env::set_var("LOGE_FORMAT", "target"); loge::init(); // -------------------------------- // $> Set-Item -Path Env:RUST_LOG -Value "trace" // println!("env_logger"); // env_logger::init(); // $> Set-Item -Path Env:RUST_LOG // -------------------------------- let mut structs = Vec::new(); for i in 0..100 { structs.push(Struct { data: [i as u8; 32] }); } { // With format let start = Instant::now(); for s in &structs { log::info!("{}", format!("{}", s)); } eprintln!("with format: {:?}", start.elapsed()); } { // Plain logger let start = Instant::now(); for s in &structs { log::info!("{}", s); } eprintln!("plain: {:?}", start.elapsed()); } }
23.653061
58
0.431406
67819497a3442a9575dc7e586b3d86027af3a047
2,969
use crate::{error::BaoError, matching::BaoSymbol}; use goblin::pe::PE; use std::ops::Deref; pub struct BaoPE<'a>(PE<'a>); impl<'a> From<PE<'a>> for BaoPE<'a> { fn from(pe: PE<'a>) -> Self { BaoPE(pe) } } pub(crate) struct SearchResult { pub(crate) offset: u32, pub(crate) name: String, pub(crate) index: u16, } impl<'a> BaoPE<'a> { pub fn get_section_data(&self, offset: usize, va: bool) -> Option<(u32, u16)> { self.0 .sections .iter() .enumerate() .find(|&(_, section)| { if va { offset >= section.virtual_address as usize && offset < (section.virtual_address + section.virtual_size) as usize } else { offset >= section.pointer_to_raw_data as usize && offset < (section.pointer_to_raw_data + section.size_of_raw_data) as usize } }) .map(|(i, section)| { ( (offset - (if va { section.virtual_address } else { section.pointer_to_raw_data }) as usize) as u32, (i + 1) as u16, ) }) } pub(crate) fn find_symbols( &self, symbols: Vec<BaoSymbol>, data: &[u8], warnings: &mut Vec<BaoError>, ) -> Vec<SearchResult> { let mut found_symbols = vec![]; found_symbols.reserve(symbols.len()); for symbol in symbols { let name = &symbol.name; let (offset, va) = match symbol.find(data, self.image_base) { Err(e) => { warnings.insert(0, e); continue; } Ok(result) => result, }; let (offset, index) = match self.get_section_data(offset, va) { None => { warnings.insert( 0, BaoError::BadPattern { pattern: format!( "{:?} ({:?}) could not be translated. Please check relative and \ rip_relative!", name, symbol.pattern ), }, ); continue; } Some(result) => result, }; found_symbols.insert( 0, SearchResult { offset, name: name.clone(), index, }, ) } found_symbols } } impl<'a> Deref for BaoPE<'a> { type Target = PE<'a>; fn deref(&self) -> &Self::Target { &self.0 } }
28.27619
97
0.396093
ac419d4e7dd727dea9a15deec9082820461e8107
3,024
use crate::readers::{FieldDef, Section, DEFAULT_STYLE, ENUM_STYLE}; // use ansi_term::Color::{Blue, Green, Red, White}; use ansi_term::Style; use num_enum::TryFromPrimitive; use std::convert::TryFrom; use std::error::Error; use std::fmt::Write; use std::io::Cursor; #[derive(Debug, TryFromPrimitive)] #[repr(u64)] enum Compression { RGB = 0, RLE8 = 1, RLE4 = 2, BITFIELDS = 3, JPEG = 4, PNG = 5, ALPHABITFIELDS = 6, CMYK = 11, CMYKRLE8 = 12, CMYKRLE4 = 13, } fn dump_mask(value: u64) -> String { let mut mask = String::with_capacity(8); for b in &value.to_le_bytes()[0..4] { let _ = match b { 0 => Ok(mask.push_str("--")), _ => write!(mask, "{:>2x}", b), }; } mask } static MSKR_STYLE: Style = Style { foreground: Some(Red), ..DEFAULT_STYLE }; static MSKG_STYLE: Style = Style { foreground: Some(Green), ..DEFAULT_STYLE }; static MSKB_STYLE: Style = Style { foreground: Some(Blue), ..DEFAULT_STYLE }; static MSKA_STYLE: Style = Style { foreground: Some(White), is_dimmed: true, ..DEFAULT_STYLE }; pub fn read(bytes: &Vec<u8>) -> Result<(usize, usize), Box<dyn Error>> { let mut cursor = Cursor::new(bytes); let file_section = Section::from_bytes( &mut cursor, "BITMAPFILEHEADER", vec![ FieldDef::chars("Magic", 2), FieldDef::u32("Size"), FieldDef::u16("Reserved1"), FieldDef::u16("Reserved2"), FieldDef::u32("OffsetToBits"), ], ); println!("{}", file_section); let info_section = Section::from_bytes( &mut cursor, "BITMAPINFOHEADER", vec![ FieldDef::u32("Size"), FieldDef::i32("Width"), FieldDef::i32("Height"), FieldDef::u16("Planes"), FieldDef::u16("BitCount"), FieldDef::new("Compression", 4, &ENUM_STYLE, |v| { format!("{:?}", Compression::try_from(v).unwrap()) }), FieldDef::u32("SizeImage"), FieldDef::i32("XPelsPerMeter"), FieldDef::i32("YPelsPerMeter"), FieldDef::u32("ClrUsed"), FieldDef::u32("ClrImportant"), ], ); println!("{}", info_section); let comp = info_section.get("Compression").unwrap(); if comp.value == Compression::BITFIELDS as u64 { let bitfields_section = Section::from_bytes( &mut cursor, "BITFIELDS", vec![ FieldDef::new("RedMask", 4, &MSKR_STYLE, dump_mask), FieldDef::new("GreenMask", 4, &MSKG_STYLE, dump_mask), FieldDef::new("BlueMask", 4, &MSKB_STYLE, dump_mask), FieldDef::new("AlphaMask", 4, &MSKA_STYLE, dump_mask), ], ); println!("{}", bitfields_section); } else { println!("Skipping bitfields since the BITFIELDS flag wasn't set"); } return Ok((0, bytes.len())); }
26.068966
75
0.547288
280730e423d786d81bec519ed2183512d0d0d0ac
587
// Copyright 2020 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::io; use base::{Event, RawDescriptor}; /// Abstraction over serial-like devices that can be created given an event and optional input and /// output streams. pub trait SerialDevice { fn new( protected_vm: bool, interrupt_evt: Event, input: Option<Box<dyn io::Read + Send>>, output: Option<Box<dyn io::Write + Send>>, keep_rds: Vec<RawDescriptor>, ) -> Self; }
29.35
98
0.672913
d68eb73494adbc5b3012e059891cd680d236b72f
12,386
pub use polar_core::polar::{Polar, Query}; use polar_core::{error, terms}; use std::cell::RefCell; use std::ffi::{CStr, CString}; use std::os::raw::c_char; use std::panic::{catch_unwind, AssertUnwindSafe}; use std::ptr::{null, null_mut}; /// Get a reference to an object from a pointer macro_rules! ffi_ref { ($name:ident) => {{ assert!(!$name.is_null()); &mut *$name }}; } /// Get a `Cow<str>` back from a C-style string macro_rules! ffi_string { ($name:ident) => {{ assert!(!$name.is_null()); CStr::from_ptr($name).to_string_lossy() }}; } /// Returns a raw pointer from an object macro_rules! box_ptr { ($x:expr) => { Box::into_raw(Box::new($x)) }; } /// We use the convention of zero as an error term, /// since we also use `null_ptr()` to indicate an error. /// So for consistency, a zero term is an error in both cases. pub const POLAR_FAILURE: i32 = 0; pub const POLAR_SUCCESS: i32 = 1; /// Unwrap the result term and return a zero/null pointer in the failure case macro_rules! ffi_try { ($body:block) => { if let Ok(res) = catch_unwind(AssertUnwindSafe(|| $body)) { res } else { set_error(error::OperationalError::Unknown.into()); // return as an int or a pointer POLAR_FAILURE as _ } }; } thread_local! { static LAST_ERROR: RefCell<Option<Box<error::PolarError>>> = RefCell::new(None); } fn set_error(e: error::PolarError) { LAST_ERROR.with(|prev| *prev.borrow_mut() = Some(Box::new(e))) } #[no_mangle] pub extern "C" fn polar_get_error() -> *const c_char { ffi_try!({ let err = LAST_ERROR.with(|prev| prev.borrow_mut().take()); if let Some(e) = err { let error_json = serde_json::to_string(&e).unwrap(); CString::new(error_json) .expect("JSON should not contain any 0 bytes") .into_raw() } else { null() } }) } #[no_mangle] pub extern "C" fn polar_new() -> *mut Polar { ffi_try!({ box_ptr!(Polar::new()) }) } #[no_mangle] pub extern "C" fn polar_load( polar_ptr: *mut Polar, src: *const c_char, filename: *const c_char, ) -> i32 { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; let src = unsafe { ffi_string!(src) }; let filename = unsafe { filename .as_ref() .map(|ptr| CStr::from_ptr(ptr).to_string_lossy().to_string()) }; match polar.load(&src, filename) { Err(err) => { set_error(err); POLAR_FAILURE } Ok(_) => POLAR_SUCCESS, } }) } #[no_mangle] pub extern "C" fn polar_clear_rules(polar_ptr: *mut Polar) -> i32 { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; polar.clear_rules(); POLAR_SUCCESS }) } #[no_mangle] pub extern "C" fn polar_register_constant( polar_ptr: *mut Polar, name: *const c_char, value: *const c_char, ) -> i32 { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; let name = unsafe { ffi_string!(name) }; let value = unsafe { ffi_string!(value) }; let value = serde_json::from_str(&value); match value { Ok(value) => { polar.register_constant(terms::Symbol::new(name.as_ref()), value); POLAR_SUCCESS } Err(e) => { set_error(error::RuntimeError::Serialization { msg: e.to_string() }.into()); POLAR_FAILURE } } }) } // @Note(steve): trace is treated as a bool. 0 for false, anything else for true. // If we get more than one flag on these ffi methods, consider renaming it flags and making it a bitflags field. // Then we wont have to update the ffi to add new optional things like logging or tracing or whatever. #[no_mangle] pub extern "C" fn polar_next_inline_query(polar_ptr: *mut Polar, trace: u32) -> *mut Query { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; let trace = trace != 0; match polar.next_inline_query(trace) { Some(query) => box_ptr!(query), None => null_mut(), } }) } #[no_mangle] pub extern "C" fn polar_new_query_from_term( polar_ptr: *mut Polar, query_term: *const c_char, trace: u32, ) -> *mut Query { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; let s = unsafe { ffi_string!(query_term) }; let term = serde_json::from_str(&s); let trace = trace != 0; match term { Ok(term) => box_ptr!(polar.new_query_from_term(term, trace)), Err(e) => { set_error(error::RuntimeError::Serialization { msg: e.to_string() }.into()); null_mut() } } }) } #[no_mangle] pub extern "C" fn polar_new_query( polar_ptr: *mut Polar, query_str: *const c_char, trace: u32, ) -> *mut Query { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; let s = unsafe { ffi_string!(query_str) }; let trace = trace != 0; let q = polar.new_query(&s, trace); match q { Ok(q) => box_ptr!(q), Err(e) => { set_error(e); null_mut() } } }) } #[no_mangle] pub extern "C" fn polar_next_polar_message(polar_ptr: *mut Polar) -> *const c_char { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; if let Some(msg) = polar.next_message() { let msg_json = serde_json::to_string(&msg).unwrap(); CString::new(msg_json) .expect("JSON should not contain any 0 bytes") .into_raw() } else { null() } }) } #[no_mangle] pub extern "C" fn polar_next_query_event(query_ptr: *mut Query) -> *const c_char { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; let event = query.next_event(); match event { Ok(event) => { let event_json = serde_json::to_string(&event).unwrap(); CString::new(event_json) .expect("JSON should not contain any 0 bytes") .into_raw() } Err(e) => { set_error(e); null() } } }) } /// Execute one debugger command for the given query. /// /// ## Returns /// - `0` on error. /// - `1` on success. /// /// ## Errors /// - Provided value is NULL. /// - Provided value contains malformed JSON. /// - Provided value cannot be parsed to a Term wrapping a Value::String. /// - Query.debug_command returns an error. /// - Anything panics during the parsing/execution of the provided command. #[no_mangle] pub extern "C" fn polar_debug_command(query_ptr: *mut Query, value: *const c_char) -> i32 { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; if !value.is_null() { let s = unsafe { ffi_string!(value) }; let t = serde_json::from_str(&s); match t.as_ref().map(terms::Term::value) { Ok(terms::Value::String(command)) => match query.debug_command(command) { Ok(_) => POLAR_SUCCESS, Err(e) => { set_error(e); POLAR_FAILURE } }, Ok(_) => { set_error( error::RuntimeError::Serialization { msg: "received bad command".to_string(), } .into(), ); POLAR_FAILURE } Err(e) => { set_error(error::RuntimeError::Serialization { msg: e.to_string() }.into()); POLAR_FAILURE } } } else { POLAR_FAILURE } }) } #[no_mangle] pub extern "C" fn polar_call_result( query_ptr: *mut Query, call_id: u64, value: *const c_char, ) -> i32 { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; let mut term = None; if !value.is_null() { let s = unsafe { ffi_string!(value) }; let t = serde_json::from_str(&s); match t { Ok(t) => term = Some(t), Err(e) => { set_error(error::RuntimeError::Serialization { msg: e.to_string() }.into()); return POLAR_FAILURE; } } } match query.call_result(call_id, term) { Ok(_) => POLAR_SUCCESS, Err(e) => { set_error(e); POLAR_FAILURE } } }) } #[no_mangle] pub extern "C" fn polar_question_result(query_ptr: *mut Query, call_id: u64, result: i32) -> i32 { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; let result = result != POLAR_FAILURE; match query.question_result(call_id, result) { Ok(_) => POLAR_SUCCESS, Err(e) => { set_error(e); POLAR_FAILURE } } }) } #[no_mangle] pub extern "C" fn polar_application_error(query_ptr: *mut Query, message: *mut c_char) -> i32 { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; let s = if !message.is_null() { unsafe { ffi_string!(message) }.to_string() } else { "".to_owned() }; match query.application_error(s) { Ok(_) => POLAR_SUCCESS, Err(e) => { set_error(e); POLAR_FAILURE } } }) } #[no_mangle] pub extern "C" fn polar_next_query_message(query_ptr: *mut Query) -> *const c_char { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; if let Some(msg) = query.next_message() { let msg_json = serde_json::to_string(&msg).unwrap(); CString::new(msg_json) .expect("JSON should not contain any 0 bytes") .into_raw() } else { null() } }) } #[no_mangle] pub extern "C" fn polar_query_source_info(query_ptr: *mut Query) -> *const c_char { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; CString::new(query.source_info()) .expect("No null bytes") .into_raw() }) } #[no_mangle] pub extern "C" fn polar_bind( query_ptr: *mut Query, name: *const c_char, value: *const c_char, ) -> i32 { ffi_try!({ let query = unsafe { ffi_ref!(query_ptr) }; let name = unsafe { ffi_string!(name) }; let value = unsafe { ffi_string!(value) }; let value = serde_json::from_str(&value); match value { Ok(value) => match query.bind(terms::Symbol::new(name.as_ref()), value) { Ok(_) => POLAR_SUCCESS, Err(e) => { set_error(e); POLAR_FAILURE } }, Err(e) => { set_error(error::RuntimeError::Serialization { msg: e.to_string() }.into()); POLAR_FAILURE } } }) } #[no_mangle] pub extern "C" fn polar_get_external_id(polar_ptr: *mut Polar) -> u64 { ffi_try!({ let polar = unsafe { ffi_ref!(polar_ptr) }; polar.get_external_id() }) } /// Required to free strings properly #[no_mangle] pub extern "C" fn string_free(s: *mut c_char) -> i32 { ffi_try!({ if s.is_null() { return POLAR_FAILURE; } unsafe { CString::from_raw(s) }; POLAR_SUCCESS }) } /// Recovers the original boxed version of `polar` so that /// it can be properly freed #[no_mangle] pub extern "C" fn polar_free(polar: *mut Polar) -> i32 { ffi_try!({ std::mem::drop(unsafe { Box::from_raw(polar) }); POLAR_SUCCESS }) } /// Recovers the original boxed version of `query` so that /// it can be properly freed #[no_mangle] pub extern "C" fn query_free(query: *mut Query) -> i32 { ffi_try!({ std::mem::drop(unsafe { Box::from_raw(query) }); POLAR_SUCCESS }) }
28.605081
112
0.525674
088db92253acfb857d0abcc725bd6eaf69668e13
15,209
//! Client-side types. use super::*; macro_rules! define_handles { ( 'owned: $($oty:ident,)* 'interned: $($ity:ident,)* ) => { #[repr(C)] #[allow(non_snake_case)] pub struct HandleCounters { $($oty: AtomicUsize,)* $($ity: AtomicUsize,)* } impl HandleCounters { // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of // a wrapper `fn` pointer, once `const fn` can reference `static`s. extern "C" fn get() -> &'static Self { static COUNTERS: HandleCounters = HandleCounters { $($oty: AtomicUsize::new(1),)* $($ity: AtomicUsize::new(1),)* }; &COUNTERS } } // FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`. #[repr(C)] #[allow(non_snake_case)] pub(super) struct HandleStore<S: server::Types> { $($oty: handle::OwnedStore<S::$oty>,)* $($ity: handle::InternedStore<S::$ity>,)* } impl<S: server::Types> HandleStore<S> { pub(super) fn new(handle_counters: &'static HandleCounters) -> Self { HandleStore { $($oty: handle::OwnedStore::new(&handle_counters.$oty),)* $($ity: handle::InternedStore::new(&handle_counters.$ity),)* } } } $( #[repr(C)] pub(crate) struct $oty(handle::Handle); impl !Send for $oty {} impl !Sync for $oty {} // Forward `Drop::drop` to the inherent `drop` method. impl Drop for $oty { fn drop(&mut self) { $oty(self.0).drop(); } } impl<S> Encode<S> for $oty { fn encode(self, w: &mut Writer, s: &mut S) { let handle = self.0; mem::forget(self); handle.encode(w, s); } } impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>> for Marked<S::$oty, $oty> { fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self { s.$oty.take(handle::Handle::decode(r, &mut ())) } } impl<S> Encode<S> for &$oty { fn encode(self, w: &mut Writer, s: &mut S) { self.0.encode(w, s); } } impl<S: server::Types> Decode<'_, 's, HandleStore<server::MarkedTypes<S>>> for &'s Marked<S::$oty, $oty> { fn decode(r: &mut Reader<'_>, s: &'s HandleStore<server::MarkedTypes<S>>) -> Self { &s.$oty[handle::Handle::decode(r, &mut ())] } } impl<S> Encode<S> for &mut $oty { fn encode(self, w: &mut Writer, s: &mut S) { self.0.encode(w, s); } } impl<S: server::Types> DecodeMut<'_, 's, HandleStore<server::MarkedTypes<S>>> for &'s mut Marked<S::$oty, $oty> { fn decode( r: &mut Reader<'_>, s: &'s mut HandleStore<server::MarkedTypes<S>> ) -> Self { &mut s.$oty[handle::Handle::decode(r, &mut ())] } } impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>> for Marked<S::$oty, $oty> { fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) { s.$oty.alloc(self).encode(w, s); } } impl<S> DecodeMut<'_, '_, S> for $oty { fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { $oty(handle::Handle::decode(r, s)) } } )* $( #[repr(C)] #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub(crate) struct $ity(handle::Handle); impl !Send for $ity {} impl !Sync for $ity {} impl<S> Encode<S> for $ity { fn encode(self, w: &mut Writer, s: &mut S) { self.0.encode(w, s); } } impl<S: server::Types> DecodeMut<'_, '_, HandleStore<server::MarkedTypes<S>>> for Marked<S::$ity, $ity> { fn decode(r: &mut Reader<'_>, s: &mut HandleStore<server::MarkedTypes<S>>) -> Self { s.$ity.copy(handle::Handle::decode(r, &mut ())) } } impl<S: server::Types> Encode<HandleStore<server::MarkedTypes<S>>> for Marked<S::$ity, $ity> { fn encode(self, w: &mut Writer, s: &mut HandleStore<server::MarkedTypes<S>>) { s.$ity.alloc(self).encode(w, s); } } impl<S> DecodeMut<'_, '_, S> for $ity { fn decode(r: &mut Reader<'_>, s: &mut S) -> Self { $ity(handle::Handle::decode(r, s)) } } )* } } define_handles! { 'owned: TokenStream, TokenStreamBuilder, TokenStreamIter, Group, Literal, SourceFile, MultiSpan, Diagnostic, 'interned: Punct, Ident, Span, } // FIXME(eddyb) generate these impls by pattern-matching on the // names of methods - also could use the presence of `fn drop` // to distinguish between 'owned and 'interned, above. // Alternatively, special 'modes" could be listed of types in with_api // instead of pattern matching on methods, here and in server decl. impl Clone for TokenStream { fn clone(&self) -> Self { self.clone() } } impl Clone for TokenStreamIter { fn clone(&self) -> Self { self.clone() } } impl Clone for Group { fn clone(&self) -> Self { self.clone() } } impl Clone for Literal { fn clone(&self) -> Self { self.clone() } } // FIXME(eddyb) `Literal` should not expose internal `Debug` impls. impl fmt::Debug for Literal { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.debug()) } } impl Clone for SourceFile { fn clone(&self) -> Self { self.clone() } } impl fmt::Debug for Span { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.debug()) } } macro_rules! define_client_side { ($($name:ident { $(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)*;)* }),* $(,)?) => { $(impl $name { $(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* { Bridge::with(|bridge| { let mut b = bridge.cached_buffer.take(); b.clear(); api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ()); reverse_encode!(b; $($arg),*); b = bridge.dispatch.call(b); let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ()); bridge.cached_buffer = b; r.unwrap_or_else(|e| panic::resume_unwind(e.into())) }) })* })* } } with_api!(self, self, define_client_side); enum BridgeState<'a> { /// No server is currently connected to this client. NotConnected, /// A server is connected and available for requests. Connected(Bridge<'a>), /// Access to the bridge is being exclusively acquired /// (e.g., during `BridgeState::with`). InUse, } enum BridgeStateL {} impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL { type Out = BridgeState<'a>; } thread_local! { static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> = scoped_cell::ScopedCell::new(BridgeState::NotConnected); } impl BridgeState<'_> { /// Take exclusive control of the thread-local /// `BridgeState`, and pass it to `f`, mutably. /// The state will be restored after `f` exits, even /// by panic, including modifications made to it by `f`. /// /// N.B., while `f` is running, the thread-local state /// is `BridgeState::InUse`. fn with<R>(f: impl FnOnce(&mut BridgeState<'_>) -> R) -> R { BRIDGE_STATE.with(|state| { state.replace(BridgeState::InUse, |mut state| { // FIXME(#52812) pass `f` directly to `replace` when `RefMutL` is gone f(&mut *state) }) }) } } impl Bridge<'_> { fn enter<R>(self, f: impl FnOnce() -> R) -> R { // Hide the default panic output within `proc_macro` expansions. // NB. the server can't do this because it may use a different libstd. static HIDE_PANICS_DURING_EXPANSION: Once = Once::new(); HIDE_PANICS_DURING_EXPANSION.call_once(|| { let prev = panic::take_hook(); panic::set_hook(Box::new(move |info| { let hide = BridgeState::with(|state| match state { BridgeState::NotConnected => false, BridgeState::Connected(_) | BridgeState::InUse => true, }); if !hide { prev(info) } })); }); BRIDGE_STATE.with(|state| state.set(BridgeState::Connected(self), f)) } fn with<R>(f: impl FnOnce(&mut Bridge<'_>) -> R) -> R { BridgeState::with(|state| match state { BridgeState::NotConnected => { panic!("procedural macro API is used outside of a procedural macro"); } BridgeState::InUse => { panic!("procedural macro API is used while it's already in use"); } BridgeState::Connected(bridge) => f(bridge), }) } } /// A client-side "global object" (usually a function pointer), /// which may be using a different `proc_macro` from the one /// used by the server, but can be interacted with compatibly. /// /// N.B., `F` must have FFI-friendly memory layout (e.g., a pointer). /// The call ABI of function pointers used for `F` doesn't /// need to match between server and client, since it's only /// passed between them and (eventually) called by the client. #[repr(C)] #[derive(Copy, Clone)] pub struct Client<F> { // FIXME(eddyb) use a reference to the `static COUNTERS`, instead of // a wrapper `fn` pointer, once `const fn` can reference `static`s. pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters, pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>, pub(super) f: F, } /// Client-side helper for handling client panics, entering the bridge, /// deserializing input and serializing output. // FIXME(eddyb) maybe replace `Bridge::enter` with this? fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>( mut bridge: Bridge<'_>, f: impl FnOnce(A) -> R, ) -> Buffer<u8> { // The initial `cached_buffer` contains the input. let mut b = bridge.cached_buffer.take(); panic::catch_unwind(panic::AssertUnwindSafe(|| { bridge.enter(|| { let reader = &mut &b[..]; let input = A::decode(reader, &mut ()); // Put the `cached_buffer` back in the `Bridge`, for requests. Bridge::with(|bridge| bridge.cached_buffer = b.take()); let output = f(input); // Take the `cached_buffer` back out, for the output value. b = Bridge::with(|bridge| bridge.cached_buffer.take()); // HACK(eddyb) Separate encoding a success value (`Ok(output)`) // from encoding a panic (`Err(e: PanicMessage)`) to avoid // having handles outside the `bridge.enter(|| ...)` scope, and // to catch panics that could happen while encoding the success. // // Note that panics should be impossible beyond this point, but // this is defensively trying to avoid any accidental panicking // reaching the `extern "C"` (which should `abort` but may not // at the moment, so this is also potentially preventing UB). b.clear(); Ok::<_, ()>(output).encode(&mut b, &mut ()); }) })) .map_err(PanicMessage::from) .unwrap_or_else(|e| { b.clear(); Err::<(), _>(e).encode(&mut b, &mut ()); }); b } impl Client<fn(crate::TokenStream) -> crate::TokenStream> { pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self { extern "C" fn run( bridge: Bridge<'_>, f: impl FnOnce(crate::TokenStream) -> crate::TokenStream, ) -> Buffer<u8> { run_client(bridge, |input| f(crate::TokenStream(input)).0) } Client { get_handle_counters: HandleCounters::get, run, f } } } impl Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> { pub const fn expand2( f: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, ) -> Self { extern "C" fn run( bridge: Bridge<'_>, f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, ) -> Buffer<u8> { run_client(bridge, |(input, input2)| { f(crate::TokenStream(input), crate::TokenStream(input2)).0 }) } Client { get_handle_counters: HandleCounters::get, run, f } } } #[repr(C)] #[derive(Copy, Clone)] pub enum ProcMacro { CustomDerive { trait_name: &'static str, attributes: &'static [&'static str], client: Client<fn(crate::TokenStream) -> crate::TokenStream>, }, Attr { name: &'static str, client: Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream>, }, Bang { name: &'static str, client: Client<fn(crate::TokenStream) -> crate::TokenStream>, }, } impl ProcMacro { pub fn name(&self) -> &'static str { match self { ProcMacro::CustomDerive { trait_name, .. } => trait_name, ProcMacro::Attr { name, .. } => name, ProcMacro::Bang { name, .. } => name, } } pub const fn custom_derive( trait_name: &'static str, attributes: &'static [&'static str], expand: fn(crate::TokenStream) -> crate::TokenStream, ) -> Self { ProcMacro::CustomDerive { trait_name, attributes, client: Client::expand1(expand) } } pub const fn attr( name: &'static str, expand: fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream, ) -> Self { ProcMacro::Attr { name, client: Client::expand2(expand) } } pub const fn bang( name: &'static str, expand: fn(crate::TokenStream) -> crate::TokenStream, ) -> Self { ProcMacro::Bang { name, client: Client::expand1(expand) } } }
32.567452
100
0.516997
48abf97c92f205a215eae5a459851e0eb681250e
39,509
//! The type system. We currently use this to infer types for completion, hover //! information and various assists. macro_rules! impl_froms { ($e:ident: $($v:ident $(($($sv:ident),*))?),*) => { $( impl From<$v> for $e { fn from(it: $v) -> $e { $e::$v(it) } } $($( impl From<$sv> for $e { fn from(it: $sv) -> $e { $e::$v($v::$sv(it)) } } )*)? )* } } mod autoderef; pub mod primitive; pub mod traits; pub mod method_resolution; mod op; mod lower; mod infer; pub mod display; pub(crate) mod utils; pub mod db; pub mod diagnostics; pub mod expr; #[cfg(test)] mod tests; #[cfg(test)] mod test_db; mod marks; use std::ops::Deref; use std::sync::Arc; use std::{fmt, iter, mem}; use hir_def::{ expr::ExprId, type_ref::Mutability, AdtId, AssocContainerId, DefWithBodyId, GenericDefId, HasModule, Lookup, TraitId, TypeAliasId, }; use hir_expand::name::Name; use ra_db::{impl_intern_key, salsa, CrateId}; use crate::{ db::HirDatabase, primitive::{FloatTy, IntTy, Uncertain}, utils::{generics, make_mut_slice, Generics}, }; use display::{HirDisplay, HirFormatter}; pub use autoderef::autoderef; pub use infer::{infer_query, InferTy, InferenceResult}; pub use lower::CallableDef; pub use lower::{callable_item_sig, TyDefId, ValueTyDefId}; pub use traits::{InEnvironment, Obligation, ProjectionPredicate, TraitEnvironment}; /// A type constructor or type name: this might be something like the primitive /// type `bool`, a struct like `Vec`, or things like function pointers or /// tuples. #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)] pub enum TypeCtor { /// The primitive boolean type. Written as `bool`. Bool, /// The primitive character type; holds a Unicode scalar value /// (a non-surrogate code point). Written as `char`. Char, /// A primitive integer type. For example, `i32`. Int(Uncertain<IntTy>), /// A primitive floating-point type. For example, `f64`. Float(Uncertain<FloatTy>), /// Structures, enumerations and unions. Adt(AdtId), /// The pointee of a string slice. Written as `str`. Str, /// The pointee of an array slice. Written as `[T]`. Slice, /// An array with the given length. Written as `[T; n]`. Array, /// A raw pointer. Written as `*mut T` or `*const T` RawPtr(Mutability), /// A reference; a pointer with an associated lifetime. Written as /// `&'a mut T` or `&'a T`. Ref(Mutability), /// The anonymous type of a function declaration/definition. Each /// function has a unique type, which is output (for a function /// named `foo` returning an `i32`) as `fn() -> i32 {foo}`. /// /// This includes tuple struct / enum variant constructors as well. /// /// For example the type of `bar` here: /// /// ``` /// fn foo() -> i32 { 1 } /// let bar = foo; // bar: fn() -> i32 {foo} /// ``` FnDef(CallableDef), /// A pointer to a function. Written as `fn() -> i32`. /// /// For example the type of `bar` here: /// /// ``` /// fn foo() -> i32 { 1 } /// let bar: fn() -> i32 = foo; /// ``` FnPtr { num_args: u16 }, /// The never type `!`. Never, /// A tuple type. For example, `(i32, bool)`. Tuple { cardinality: u16 }, /// Represents an associated item like `Iterator::Item`. This is used /// when we have tried to normalize a projection like `T::Item` but /// couldn't find a better representation. In that case, we generate /// an **application type** like `(Iterator::Item)<T>`. AssociatedType(TypeAliasId), /// The type of a specific closure. /// /// The closure signature is stored in a `FnPtr` type in the first type /// parameter. Closure { def: DefWithBodyId, expr: ExprId }, } /// This exists just for Chalk, because Chalk just has a single `StructId` where /// we have different kinds of ADTs, primitive types and special type /// constructors like tuples and function pointers. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct TypeCtorId(salsa::InternId); impl_intern_key!(TypeCtorId); impl TypeCtor { pub fn num_ty_params(self, db: &impl HirDatabase) -> usize { match self { TypeCtor::Bool | TypeCtor::Char | TypeCtor::Int(_) | TypeCtor::Float(_) | TypeCtor::Str | TypeCtor::Never => 0, TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) | TypeCtor::Closure { .. } // 1 param representing the signature of the closure => 1, TypeCtor::Adt(adt) => { let generic_params = generics(db, AdtId::from(adt).into()); generic_params.len() } TypeCtor::FnDef(callable) => { let generic_params = generics(db, callable.into()); generic_params.len() } TypeCtor::AssociatedType(type_alias) => { let generic_params = generics(db, type_alias.into()); generic_params.len() } TypeCtor::FnPtr { num_args } => num_args as usize + 1, TypeCtor::Tuple { cardinality } => cardinality as usize, } } pub fn krate(self, db: &impl HirDatabase) -> Option<CrateId> { match self { TypeCtor::Bool | TypeCtor::Char | TypeCtor::Int(_) | TypeCtor::Float(_) | TypeCtor::Str | TypeCtor::Never | TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) | TypeCtor::FnPtr { .. } | TypeCtor::Tuple { .. } => None, // Closure's krate is irrelevant for coherence I would think? TypeCtor::Closure { .. } => None, TypeCtor::Adt(adt) => Some(adt.module(db).krate), TypeCtor::FnDef(callable) => Some(callable.krate(db)), TypeCtor::AssociatedType(type_alias) => Some(type_alias.lookup(db).module(db).krate), } } pub fn as_generic_def(self) -> Option<GenericDefId> { match self { TypeCtor::Bool | TypeCtor::Char | TypeCtor::Int(_) | TypeCtor::Float(_) | TypeCtor::Str | TypeCtor::Never | TypeCtor::Slice | TypeCtor::Array | TypeCtor::RawPtr(_) | TypeCtor::Ref(_) | TypeCtor::FnPtr { .. } | TypeCtor::Tuple { .. } | TypeCtor::Closure { .. } => None, TypeCtor::Adt(adt) => Some(adt.into()), TypeCtor::FnDef(callable) => Some(callable.into()), TypeCtor::AssociatedType(type_alias) => Some(type_alias.into()), } } } /// A nominal type with (maybe 0) type parameters. This might be a primitive /// type like `bool`, a struct, tuple, function pointer, reference or /// several other things. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct ApplicationTy { pub ctor: TypeCtor, pub parameters: Substs, } /// A "projection" type corresponds to an (unnormalized) /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the /// trait and all its parameters are fully known. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct ProjectionTy { pub associated_ty: TypeAliasId, pub parameters: Substs, } impl ProjectionTy { pub fn trait_ref(&self, db: &impl HirDatabase) -> TraitRef { TraitRef { trait_: self.trait_(db).into(), substs: self.parameters.clone() } } fn trait_(&self, db: &impl HirDatabase) -> TraitId { match self.associated_ty.lookup(db).container { AssocContainerId::TraitId(it) => it, _ => panic!("projection ty without parent trait"), } } } impl TypeWalk for ProjectionTy { fn walk(&self, f: &mut impl FnMut(&Ty)) { self.parameters.walk(f); } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { self.parameters.walk_mut_binders(f, binders); } } /// A type. /// /// See also the `TyKind` enum in rustc (librustc/ty/sty.rs), which represents /// the same thing (but in a different way). /// /// This should be cheap to clone. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub enum Ty { /// A nominal type with (maybe 0) type parameters. This might be a primitive /// type like `bool`, a struct, tuple, function pointer, reference or /// several other things. Apply(ApplicationTy), /// A "projection" type corresponds to an (unnormalized) /// projection like `<P0 as Trait<P1..Pn>>::Foo`. Note that the /// trait and all its parameters are fully known. Projection(ProjectionTy), /// A type parameter; for example, `T` in `fn f<T>(x: T) {} Param { /// The index of the parameter (starting with parameters from the /// surrounding impl, then the current function). idx: u32, /// The name of the parameter, for displaying. // FIXME get rid of this name: Name, }, /// A bound type variable. Used during trait resolution to represent Chalk /// variables, and in `Dyn` and `Opaque` bounds to represent the `Self` type. Bound(u32), /// A type variable used during type checking. Not to be confused with a /// type parameter. Infer(InferTy), /// A trait object (`dyn Trait` or bare `Trait` in pre-2018 Rust). /// /// The predicates are quantified over the `Self` type, i.e. `Ty::Bound(0)` /// represents the `Self` type inside the bounds. This is currently /// implicit; Chalk has the `Binders` struct to make it explicit, but it /// didn't seem worth the overhead yet. Dyn(Arc<[GenericPredicate]>), /// An opaque type (`impl Trait`). /// /// The predicates are quantified over the `Self` type; see `Ty::Dyn` for /// more. Opaque(Arc<[GenericPredicate]>), /// A placeholder for a type which could not be computed; this is propagated /// to avoid useless error messages. Doubles as a placeholder where type /// variables are inserted before type checking, since we want to try to /// infer a better type here anyway -- for the IDE use case, we want to try /// to infer as much as possible even in the presence of type errors. Unknown, } /// A list of substitutions for generic parameters. #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct Substs(Arc<[Ty]>); impl TypeWalk for Substs { fn walk(&self, f: &mut impl FnMut(&Ty)) { for t in self.0.iter() { t.walk(f); } } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { for t in make_mut_slice(&mut self.0) { t.walk_mut_binders(f, binders); } } } impl Substs { pub fn empty() -> Substs { Substs(Arc::new([])) } pub fn single(ty: Ty) -> Substs { Substs(Arc::new([ty])) } pub fn prefix(&self, n: usize) -> Substs { Substs(self.0[..std::cmp::min(self.0.len(), n)].into()) } pub fn as_single(&self) -> &Ty { if self.0.len() != 1 { panic!("expected substs of len 1, got {:?}", self); } &self.0[0] } /// Return Substs that replace each parameter by itself (i.e. `Ty::Param`). pub(crate) fn identity(generic_params: &Generics) -> Substs { Substs( generic_params.iter().map(|(idx, p)| Ty::Param { idx, name: p.name.clone() }).collect(), ) } /// Return Substs that replace each parameter by a bound variable. pub(crate) fn bound_vars(generic_params: &Generics) -> Substs { Substs(generic_params.iter().map(|(idx, _p)| Ty::Bound(idx)).collect()) } pub fn build_for_def(db: &impl HirDatabase, def: impl Into<GenericDefId>) -> SubstsBuilder { let def = def.into(); let params = generics(db, def); let param_count = params.len(); Substs::builder(param_count) } pub(crate) fn build_for_generics(generic_params: &Generics) -> SubstsBuilder { Substs::builder(generic_params.len()) } pub fn build_for_type_ctor(db: &impl HirDatabase, type_ctor: TypeCtor) -> SubstsBuilder { Substs::builder(type_ctor.num_ty_params(db)) } fn builder(param_count: usize) -> SubstsBuilder { SubstsBuilder { vec: Vec::with_capacity(param_count), param_count } } } #[derive(Debug, Clone)] pub struct SubstsBuilder { vec: Vec<Ty>, param_count: usize, } impl SubstsBuilder { pub fn build(self) -> Substs { assert_eq!(self.vec.len(), self.param_count); Substs(self.vec.into()) } pub fn push(mut self, ty: Ty) -> Self { self.vec.push(ty); self } fn remaining(&self) -> usize { self.param_count - self.vec.len() } pub fn fill_with_bound_vars(self, starting_from: u32) -> Self { self.fill((starting_from..).map(Ty::Bound)) } pub fn fill_with_params(self) -> Self { let start = self.vec.len() as u32; self.fill((start..).map(|idx| Ty::Param { idx, name: Name::missing() })) } pub fn fill_with_unknown(self) -> Self { self.fill(iter::repeat(Ty::Unknown)) } pub fn fill(mut self, filler: impl Iterator<Item = Ty>) -> Self { self.vec.extend(filler.take(self.remaining())); assert_eq!(self.remaining(), 0); self } pub fn use_parent_substs(mut self, parent_substs: &Substs) -> Self { assert!(self.vec.is_empty()); assert!(parent_substs.len() <= self.param_count); self.vec.extend(parent_substs.iter().cloned()); self } } impl Deref for Substs { type Target = [Ty]; fn deref(&self) -> &[Ty] { &self.0 } } /// A trait with type parameters. This includes the `Self`, so this represents a concrete type implementing the trait. /// Name to be bikeshedded: TraitBound? TraitImplements? #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct TraitRef { /// FIXME name? pub trait_: TraitId, pub substs: Substs, } impl TraitRef { pub fn self_ty(&self) -> &Ty { &self.substs[0] } } impl TypeWalk for TraitRef { fn walk(&self, f: &mut impl FnMut(&Ty)) { self.substs.walk(f); } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { self.substs.walk_mut_binders(f, binders); } } /// Like `generics::WherePredicate`, but with resolved types: A condition on the /// parameters of a generic item. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum GenericPredicate { /// The given trait needs to be implemented for its type parameters. Implemented(TraitRef), /// An associated type bindings like in `Iterator<Item = T>`. Projection(ProjectionPredicate), /// We couldn't resolve the trait reference. (If some type parameters can't /// be resolved, they will just be Unknown). Error, } impl GenericPredicate { pub fn is_error(&self) -> bool { match self { GenericPredicate::Error => true, _ => false, } } pub fn is_implemented(&self) -> bool { match self { GenericPredicate::Implemented(_) => true, _ => false, } } pub fn trait_ref(&self, db: &impl HirDatabase) -> Option<TraitRef> { match self { GenericPredicate::Implemented(tr) => Some(tr.clone()), GenericPredicate::Projection(proj) => Some(proj.projection_ty.trait_ref(db)), GenericPredicate::Error => None, } } } impl TypeWalk for GenericPredicate { fn walk(&self, f: &mut impl FnMut(&Ty)) { match self { GenericPredicate::Implemented(trait_ref) => trait_ref.walk(f), GenericPredicate::Projection(projection_pred) => projection_pred.walk(f), GenericPredicate::Error => {} } } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { match self { GenericPredicate::Implemented(trait_ref) => trait_ref.walk_mut_binders(f, binders), GenericPredicate::Projection(projection_pred) => { projection_pred.walk_mut_binders(f, binders) } GenericPredicate::Error => {} } } } /// Basically a claim (currently not validated / checked) that the contained /// type / trait ref contains no inference variables; any inference variables it /// contained have been replaced by bound variables, and `num_vars` tells us how /// many there are. This is used to erase irrelevant differences between types /// before using them in queries. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Canonical<T> { pub value: T, pub num_vars: usize, } /// A function signature as seen by type inference: Several parameter types and /// one return type. #[derive(Clone, PartialEq, Eq, Debug)] pub struct FnSig { params_and_return: Arc<[Ty]>, } impl FnSig { pub fn from_params_and_return(mut params: Vec<Ty>, ret: Ty) -> FnSig { params.push(ret); FnSig { params_and_return: params.into() } } pub fn from_fn_ptr_substs(substs: &Substs) -> FnSig { FnSig { params_and_return: Arc::clone(&substs.0) } } pub fn params(&self) -> &[Ty] { &self.params_and_return[0..self.params_and_return.len() - 1] } pub fn ret(&self) -> &Ty { &self.params_and_return[self.params_and_return.len() - 1] } } impl TypeWalk for FnSig { fn walk(&self, f: &mut impl FnMut(&Ty)) { for t in self.params_and_return.iter() { t.walk(f); } } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { for t in make_mut_slice(&mut self.params_and_return) { t.walk_mut_binders(f, binders); } } } impl Ty { pub fn simple(ctor: TypeCtor) -> Ty { Ty::Apply(ApplicationTy { ctor, parameters: Substs::empty() }) } pub fn apply_one(ctor: TypeCtor, param: Ty) -> Ty { Ty::Apply(ApplicationTy { ctor, parameters: Substs::single(param) }) } pub fn apply(ctor: TypeCtor, parameters: Substs) -> Ty { Ty::Apply(ApplicationTy { ctor, parameters }) } pub fn unit() -> Self { Ty::apply(TypeCtor::Tuple { cardinality: 0 }, Substs::empty()) } pub fn as_reference(&self) -> Option<(&Ty, Mutability)> { match self { Ty::Apply(ApplicationTy { ctor: TypeCtor::Ref(mutability), parameters }) => { Some((parameters.as_single(), *mutability)) } _ => None, } } pub fn as_adt(&self) -> Option<(AdtId, &Substs)> { match self { Ty::Apply(ApplicationTy { ctor: TypeCtor::Adt(adt_def), parameters }) => { Some((*adt_def, parameters)) } _ => None, } } pub fn as_tuple(&self) -> Option<&Substs> { match self { Ty::Apply(ApplicationTy { ctor: TypeCtor::Tuple { .. }, parameters }) => { Some(parameters) } _ => None, } } pub fn as_callable(&self) -> Option<(CallableDef, &Substs)> { match self { Ty::Apply(ApplicationTy { ctor: TypeCtor::FnDef(callable_def), parameters }) => { Some((*callable_def, parameters)) } _ => None, } } fn builtin_deref(&self) -> Option<Ty> { match self { Ty::Apply(a_ty) => match a_ty.ctor { TypeCtor::Ref(..) => Some(Ty::clone(a_ty.parameters.as_single())), TypeCtor::RawPtr(..) => Some(Ty::clone(a_ty.parameters.as_single())), _ => None, }, _ => None, } } fn callable_sig(&self, db: &impl HirDatabase) -> Option<FnSig> { match self { Ty::Apply(a_ty) => match a_ty.ctor { TypeCtor::FnPtr { .. } => Some(FnSig::from_fn_ptr_substs(&a_ty.parameters)), TypeCtor::FnDef(def) => { let sig = db.callable_item_signature(def); Some(sig.subst(&a_ty.parameters)) } TypeCtor::Closure { .. } => { let sig_param = &a_ty.parameters[0]; sig_param.callable_sig(db) } _ => None, }, _ => None, } } /// If this is a type with type parameters (an ADT or function), replaces /// the `Substs` for these type parameters with the given ones. (So e.g. if /// `self` is `Option<_>` and the substs contain `u32`, we'll have /// `Option<u32>` afterwards.) pub fn apply_substs(self, substs: Substs) -> Ty { match self { Ty::Apply(ApplicationTy { ctor, parameters: previous_substs }) => { assert_eq!(previous_substs.len(), substs.len()); Ty::Apply(ApplicationTy { ctor, parameters: substs }) } _ => self, } } /// Returns the type parameters of this type if it has some (i.e. is an ADT /// or function); so if `self` is `Option<u32>`, this returns the `u32`. pub fn substs(&self) -> Option<Substs> { match self { Ty::Apply(ApplicationTy { parameters, .. }) => Some(parameters.clone()), _ => None, } } /// If this is an `impl Trait` or `dyn Trait`, returns that trait. pub fn inherent_trait(&self) -> Option<TraitId> { match self { Ty::Dyn(predicates) | Ty::Opaque(predicates) => { predicates.iter().find_map(|pred| match pred { GenericPredicate::Implemented(tr) => Some(tr.trait_), _ => None, }) } _ => None, } } } /// This allows walking structures that contain types to do something with those /// types, similar to Chalk's `Fold` trait. pub trait TypeWalk { fn walk(&self, f: &mut impl FnMut(&Ty)); fn walk_mut(&mut self, f: &mut impl FnMut(&mut Ty)) { self.walk_mut_binders(&mut |ty, _binders| f(ty), 0); } /// Walk the type, counting entered binders. /// /// `Ty::Bound` variables use DeBruijn indexing, which means that 0 refers /// to the innermost binder, 1 to the next, etc.. So when we want to /// substitute a certain bound variable, we can't just walk the whole type /// and blindly replace each instance of a certain index; when we 'enter' /// things that introduce new bound variables, we have to keep track of /// that. Currently, the only thing that introduces bound variables on our /// side are `Ty::Dyn` and `Ty::Opaque`, which each introduce a bound /// variable for the self type. fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize); fn fold(mut self, f: &mut impl FnMut(Ty) -> Ty) -> Self where Self: Sized, { self.walk_mut(&mut |ty_mut| { let ty = mem::replace(ty_mut, Ty::Unknown); *ty_mut = f(ty); }); self } /// Replaces type parameters in this type using the given `Substs`. (So e.g. /// if `self` is `&[T]`, where type parameter T has index 0, and the /// `Substs` contain `u32` at index 0, we'll have `&[u32]` afterwards.) fn subst(self, substs: &Substs) -> Self where Self: Sized, { self.fold(&mut |ty| match ty { Ty::Param { idx, name } => { substs.get(idx as usize).cloned().unwrap_or(Ty::Param { idx, name }) } ty => ty, }) } /// Substitutes `Ty::Bound` vars (as opposed to type parameters). fn subst_bound_vars(mut self, substs: &Substs) -> Self where Self: Sized, { self.walk_mut_binders( &mut |ty, binders| match ty { &mut Ty::Bound(idx) => { if idx as usize >= binders && (idx as usize - binders) < substs.len() { *ty = substs.0[idx as usize - binders].clone(); } } _ => {} }, 0, ); self } /// Shifts up `Ty::Bound` vars by `n`. fn shift_bound_vars(self, n: i32) -> Self where Self: Sized, { self.fold(&mut |ty| match ty { Ty::Bound(idx) => { assert!(idx as i32 >= -n); Ty::Bound((idx as i32 + n) as u32) } ty => ty, }) } } impl TypeWalk for Ty { fn walk(&self, f: &mut impl FnMut(&Ty)) { match self { Ty::Apply(a_ty) => { for t in a_ty.parameters.iter() { t.walk(f); } } Ty::Projection(p_ty) => { for t in p_ty.parameters.iter() { t.walk(f); } } Ty::Dyn(predicates) | Ty::Opaque(predicates) => { for p in predicates.iter() { p.walk(f); } } Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} } f(self); } fn walk_mut_binders(&mut self, f: &mut impl FnMut(&mut Ty, usize), binders: usize) { match self { Ty::Apply(a_ty) => { a_ty.parameters.walk_mut_binders(f, binders); } Ty::Projection(p_ty) => { p_ty.parameters.walk_mut_binders(f, binders); } Ty::Dyn(predicates) | Ty::Opaque(predicates) => { for p in make_mut_slice(predicates) { p.walk_mut_binders(f, binders + 1); } } Ty::Param { .. } | Ty::Bound(_) | Ty::Infer(_) | Ty::Unknown => {} } f(self, binders); } } impl HirDisplay for &Ty { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { HirDisplay::hir_fmt(*self, f) } } impl HirDisplay for ApplicationTy { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { if f.should_truncate() { return write!(f, "…"); } match self.ctor { TypeCtor::Bool => write!(f, "bool")?, TypeCtor::Char => write!(f, "char")?, TypeCtor::Int(t) => write!(f, "{}", t)?, TypeCtor::Float(t) => write!(f, "{}", t)?, TypeCtor::Str => write!(f, "str")?, TypeCtor::Slice => { let t = self.parameters.as_single(); write!(f, "[{}]", t.display(f.db))?; } TypeCtor::Array => { let t = self.parameters.as_single(); write!(f, "[{};_]", t.display(f.db))?; } TypeCtor::RawPtr(m) => { let t = self.parameters.as_single(); write!(f, "*{}{}", m.as_keyword_for_ptr(), t.display(f.db))?; } TypeCtor::Ref(m) => { let t = self.parameters.as_single(); write!(f, "&{}{}", m.as_keyword_for_ref(), t.display(f.db))?; } TypeCtor::Never => write!(f, "!")?, TypeCtor::Tuple { .. } => { let ts = &self.parameters; if ts.len() == 1 { write!(f, "({},)", ts[0].display(f.db))?; } else { write!(f, "(")?; f.write_joined(&*ts.0, ", ")?; write!(f, ")")?; } } TypeCtor::FnPtr { .. } => { let sig = FnSig::from_fn_ptr_substs(&self.parameters); write!(f, "fn(")?; f.write_joined(sig.params(), ", ")?; write!(f, ") -> {}", sig.ret().display(f.db))?; } TypeCtor::FnDef(def) => { let sig = f.db.callable_item_signature(def); let name = match def { CallableDef::FunctionId(ff) => f.db.function_data(ff).name.clone(), CallableDef::StructId(s) => f.db.struct_data(s).name.clone(), CallableDef::EnumVariantId(e) => { let enum_data = f.db.enum_data(e.parent); enum_data.variants[e.local_id].name.clone() } }; match def { CallableDef::FunctionId(_) => write!(f, "fn {}", name)?, CallableDef::StructId(_) | CallableDef::EnumVariantId(_) => { write!(f, "{}", name)? } } if self.parameters.len() > 0 { write!(f, "<")?; f.write_joined(&*self.parameters.0, ", ")?; write!(f, ">")?; } write!(f, "(")?; f.write_joined(sig.params(), ", ")?; write!(f, ") -> {}", sig.ret().display(f.db))?; } TypeCtor::Adt(def_id) => { let name = match def_id { AdtId::StructId(it) => f.db.struct_data(it).name.clone(), AdtId::UnionId(it) => f.db.union_data(it).name.clone(), AdtId::EnumId(it) => f.db.enum_data(it).name.clone(), }; write!(f, "{}", name)?; if self.parameters.len() > 0 { write!(f, "<")?; let mut non_default_parameters = Vec::with_capacity(self.parameters.len()); let parameters_to_write = if f.should_display_default_types() { self.parameters.0.as_ref() } else { match self .ctor .as_generic_def() .map(|generic_def_id| f.db.generic_defaults(generic_def_id)) .filter(|defaults| !defaults.is_empty()) { Option::None => self.parameters.0.as_ref(), Option::Some(default_parameters) => { for (i, parameter) in self.parameters.iter().enumerate() { match (parameter, default_parameters.get(i)) { (&Ty::Unknown, _) | (_, None) => { non_default_parameters.push(parameter.clone()) } (_, Some(default_parameter)) if parameter != default_parameter => { non_default_parameters.push(parameter.clone()) } _ => (), } } &non_default_parameters } } }; f.write_joined(parameters_to_write, ", ")?; write!(f, ">")?; } } TypeCtor::AssociatedType(type_alias) => { let trait_ = match type_alias.lookup(f.db).container { AssocContainerId::TraitId(it) => it, _ => panic!("not an associated type"), }; let trait_name = f.db.trait_data(trait_).name.clone(); let name = f.db.type_alias_data(type_alias).name.clone(); write!(f, "{}::{}", trait_name, name)?; if self.parameters.len() > 0 { write!(f, "<")?; f.write_joined(&*self.parameters.0, ", ")?; write!(f, ">")?; } } TypeCtor::Closure { .. } => { let sig = self.parameters[0] .callable_sig(f.db) .expect("first closure parameter should contain signature"); write!(f, "|")?; f.write_joined(sig.params(), ", ")?; write!(f, "| -> {}", sig.ret().display(f.db))?; } } Ok(()) } } impl HirDisplay for ProjectionTy { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { if f.should_truncate() { return write!(f, "…"); } let trait_name = f.db.trait_data(self.trait_(f.db)).name.clone(); write!(f, "<{} as {}", self.parameters[0].display(f.db), trait_name,)?; if self.parameters.len() > 1 { write!(f, "<")?; f.write_joined(&self.parameters[1..], ", ")?; write!(f, ">")?; } write!(f, ">::{}", f.db.type_alias_data(self.associated_ty).name)?; Ok(()) } } impl HirDisplay for Ty { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { if f.should_truncate() { return write!(f, "…"); } match self { Ty::Apply(a_ty) => a_ty.hir_fmt(f)?, Ty::Projection(p_ty) => p_ty.hir_fmt(f)?, Ty::Param { name, .. } => write!(f, "{}", name)?, Ty::Bound(idx) => write!(f, "?{}", idx)?, Ty::Dyn(predicates) | Ty::Opaque(predicates) => { match self { Ty::Dyn(_) => write!(f, "dyn ")?, Ty::Opaque(_) => write!(f, "impl ")?, _ => unreachable!(), }; // Note: This code is written to produce nice results (i.e. // corresponding to surface Rust) for types that can occur in // actual Rust. It will have weird results if the predicates // aren't as expected (i.e. self types = $0, projection // predicates for a certain trait come after the Implemented // predicate for that trait). let mut first = true; let mut angle_open = false; for p in predicates.iter() { match p { GenericPredicate::Implemented(trait_ref) => { if angle_open { write!(f, ">")?; } if !first { write!(f, " + ")?; } // We assume that the self type is $0 (i.e. the // existential) here, which is the only thing that's // possible in actual Rust, and hence don't print it write!(f, "{}", f.db.trait_data(trait_ref.trait_).name.clone())?; if trait_ref.substs.len() > 1 { write!(f, "<")?; f.write_joined(&trait_ref.substs[1..], ", ")?; // there might be assoc type bindings, so we leave the angle brackets open angle_open = true; } } GenericPredicate::Projection(projection_pred) => { // in types in actual Rust, these will always come // after the corresponding Implemented predicate if angle_open { write!(f, ", ")?; } else { write!(f, "<")?; angle_open = true; } let name = f.db.type_alias_data(projection_pred.projection_ty.associated_ty) .name .clone(); write!(f, "{} = ", name)?; projection_pred.ty.hir_fmt(f)?; } GenericPredicate::Error => { if angle_open { // impl Trait<X, {error}> write!(f, ", ")?; } else if !first { // impl Trait + {error} write!(f, " + ")?; } p.hir_fmt(f)?; } } first = false; } if angle_open { write!(f, ">")?; } } Ty::Unknown => write!(f, "{{unknown}}")?, Ty::Infer(..) => write!(f, "_")?, } Ok(()) } } impl TraitRef { fn hir_fmt_ext(&self, f: &mut HirFormatter<impl HirDatabase>, use_as: bool) -> fmt::Result { if f.should_truncate() { return write!(f, "…"); } self.substs[0].hir_fmt(f)?; if use_as { write!(f, " as ")?; } else { write!(f, ": ")?; } write!(f, "{}", f.db.trait_data(self.trait_).name.clone())?; if self.substs.len() > 1 { write!(f, "<")?; f.write_joined(&self.substs[1..], ", ")?; write!(f, ">")?; } Ok(()) } } impl HirDisplay for TraitRef { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { self.hir_fmt_ext(f, false) } } impl HirDisplay for &GenericPredicate { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { HirDisplay::hir_fmt(*self, f) } } impl HirDisplay for GenericPredicate { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { if f.should_truncate() { return write!(f, "…"); } match self { GenericPredicate::Implemented(trait_ref) => trait_ref.hir_fmt(f)?, GenericPredicate::Projection(projection_pred) => { write!(f, "<")?; projection_pred.projection_ty.trait_ref(f.db).hir_fmt_ext(f, true)?; write!( f, ">::{} = {}", f.db.type_alias_data(projection_pred.projection_ty.associated_ty).name, projection_pred.ty.display(f.db) )?; } GenericPredicate::Error => write!(f, "{{error}}")?, } Ok(()) } } impl HirDisplay for Obligation { fn hir_fmt(&self, f: &mut HirFormatter<impl HirDatabase>) -> fmt::Result { match self { Obligation::Trait(tr) => write!(f, "Implements({})", tr.display(f.db)), Obligation::Projection(proj) => write!( f, "Normalize({} => {})", proj.projection_ty.display(f.db), proj.ty.display(f.db) ), } } }
34.505677
118
0.507429
7633c669cbbdd14f2b4256561d827bbe451c2b0a
7,902
use syn::{ visit::{self, Visit}, Error, Result, }; #[derive(Clone, Debug)] pub struct RpcMethodAttribute { pub attr: syn::Attribute, pub name: String, pub aliases: Vec<String>, pub kind: AttributeKind, pub raw_params: bool, } #[derive(Clone, Debug)] pub enum AttributeKind { Rpc { has_metadata: bool, returns: Option<String>, is_notification: bool, }, PubSub { subscription_name: String, kind: PubSubMethodKind, }, } #[derive(Clone, Debug)] pub enum PubSubMethodKind { Subscribe, Unsubscribe, } const RPC_ATTR_NAME: &str = "rpc"; const RPC_NAME_KEY: &str = "name"; const SUBSCRIPTION_NAME_KEY: &str = "subscription"; const ALIASES_KEY: &str = "alias"; const PUB_SUB_ATTR_NAME: &str = "pubsub"; const METADATA_META_WORD: &str = "meta"; const RAW_PARAMS_META_WORD: &str = "raw_params"; const SUBSCRIBE_META_WORD: &str = "subscribe"; const UNSUBSCRIBE_META_WORD: &str = "unsubscribe"; const RETURNS_META_WORD: &str = "returns"; const MULTIPLE_RPC_ATTRIBUTES_ERR: &str = "Expected only a single rpc attribute per method"; const INVALID_ATTR_PARAM_NAMES_ERR: &str = "Invalid attribute parameter(s):"; const MISSING_NAME_ERR: &str = "rpc attribute should have a name e.g. `name = \"method_name\"`"; const MISSING_SUB_NAME_ERR: &str = "pubsub attribute should have a subscription name"; const BOTH_SUB_AND_UNSUB_ERR: &str = "pubsub attribute annotated with both subscribe and unsubscribe"; const NEITHER_SUB_OR_UNSUB_ERR: &str = "pubsub attribute not annotated with either subscribe or unsubscribe"; impl RpcMethodAttribute { pub fn parse_attr(method: &syn::TraitItemMethod) -> Result<Option<RpcMethodAttribute>> { let output = &method.sig.decl.output; let attrs = method .attrs .iter() .filter_map(|attr| Self::parse_meta(attr, &output)) .collect::<Result<Vec<_>>>()?; if attrs.len() <= 1 { Ok(attrs.first().cloned()) } else { Err(Error::new_spanned(method, MULTIPLE_RPC_ATTRIBUTES_ERR)) } } fn parse_meta(attr: &syn::Attribute, output: &syn::ReturnType) -> Option<Result<RpcMethodAttribute>> { match attr.parse_meta().and_then(validate_attribute_meta) { Ok(ref meta) => { let attr_kind = match meta.name().to_string().as_ref() { RPC_ATTR_NAME => Some(Self::parse_rpc(meta, output)), PUB_SUB_ATTR_NAME => Some(Self::parse_pubsub(meta)), _ => None, }; attr_kind.map(|kind| { kind.and_then(|kind| { get_meta_list(meta) .and_then(|ml| get_name_value(RPC_NAME_KEY, ml)) .map_or(Err(Error::new_spanned(attr, MISSING_NAME_ERR)), |name| { let aliases = get_meta_list(&meta).map_or(Vec::new(), |ml| get_aliases(ml)); let raw_params = get_meta_list(meta).map_or(false, |ml| has_meta_word(RAW_PARAMS_META_WORD, ml)); Ok(RpcMethodAttribute { attr: attr.clone(), name, aliases, kind, raw_params, }) }) }) }) } Err(err) => Some(Err(err)), } } fn parse_rpc(meta: &syn::Meta, output: &syn::ReturnType) -> Result<AttributeKind> { let has_metadata = get_meta_list(meta).map_or(false, |ml| has_meta_word(METADATA_META_WORD, ml)); let returns = get_meta_list(meta).map_or(None, |ml| get_name_value(RETURNS_META_WORD, ml)); let is_notification = match output { syn::ReturnType::Default => true, syn::ReturnType::Type(_, ret) => match **ret { syn::Type::Tuple(ref tup) if tup.elems.empty_or_trailing() => true, _ => false, }, }; if is_notification && returns.is_some() { return Err(syn::Error::new_spanned(output, &"Notifications must return ()")); } Ok(AttributeKind::Rpc { has_metadata, returns, is_notification, }) } fn parse_pubsub(meta: &syn::Meta) -> Result<AttributeKind> { let name_and_list = get_meta_list(meta).and_then(|ml| get_name_value(SUBSCRIPTION_NAME_KEY, ml).map(|name| (name, ml))); name_and_list.map_or(Err(Error::new_spanned(meta, MISSING_SUB_NAME_ERR)), |(sub_name, ml)| { let is_subscribe = has_meta_word(SUBSCRIBE_META_WORD, ml); let is_unsubscribe = has_meta_word(UNSUBSCRIBE_META_WORD, ml); let kind = match (is_subscribe, is_unsubscribe) { (true, false) => Ok(PubSubMethodKind::Subscribe), (false, true) => Ok(PubSubMethodKind::Unsubscribe), (true, true) => Err(Error::new_spanned(meta, BOTH_SUB_AND_UNSUB_ERR)), (false, false) => Err(Error::new_spanned(meta, NEITHER_SUB_OR_UNSUB_ERR)), }; kind.map(|kind| AttributeKind::PubSub { subscription_name: sub_name, kind, }) }) } pub fn is_pubsub(&self) -> bool { match self.kind { AttributeKind::PubSub { .. } => true, AttributeKind::Rpc { .. } => false, } } pub fn is_notification(&self) -> bool { match self.kind { AttributeKind::Rpc { is_notification, .. } => is_notification, AttributeKind::PubSub { .. } => false, } } } fn validate_attribute_meta(meta: syn::Meta) -> Result<syn::Meta> { #[derive(Default)] struct Visitor { meta_words: Vec<String>, name_value_names: Vec<String>, meta_list_names: Vec<String>, } impl<'a> Visit<'a> for Visitor { fn visit_meta(&mut self, meta: &syn::Meta) { match meta { syn::Meta::List(list) => self.meta_list_names.push(list.ident.to_string()), syn::Meta::Word(ident) => self.meta_words.push(ident.to_string()), syn::Meta::NameValue(nv) => self.name_value_names.push(nv.ident.to_string()), } } } let mut visitor = Visitor::default(); visit::visit_meta(&mut visitor, &meta); match meta.name().to_string().as_ref() { RPC_ATTR_NAME => { validate_idents(&meta, &visitor.meta_words, &[METADATA_META_WORD, RAW_PARAMS_META_WORD])?; validate_idents(&meta, &visitor.name_value_names, &[RPC_NAME_KEY, RETURNS_META_WORD])?; validate_idents(&meta, &visitor.meta_list_names, &[ALIASES_KEY]) } PUB_SUB_ATTR_NAME => { validate_idents( &meta, &visitor.meta_words, &[SUBSCRIBE_META_WORD, UNSUBSCRIBE_META_WORD, RAW_PARAMS_META_WORD], )?; validate_idents(&meta, &visitor.name_value_names, &[SUBSCRIPTION_NAME_KEY, RPC_NAME_KEY])?; validate_idents(&meta, &visitor.meta_list_names, &[ALIASES_KEY]) } _ => Ok(meta), // ignore other attributes - compiler will catch unknown ones } } fn validate_idents(meta: &syn::Meta, attr_idents: &[String], valid: &[&str]) -> Result<syn::Meta> { let invalid_meta_words: Vec<_> = attr_idents .iter() .filter(|w| !valid.iter().any(|v| v == w)) .cloned() .collect(); if invalid_meta_words.is_empty() { Ok(meta.clone()) } else { let expected = format!("Expected '{}'", valid.join(", ")); let msg = format!( "{} '{}'. {}", INVALID_ATTR_PARAM_NAMES_ERR, invalid_meta_words.join(", "), expected ); Err(Error::new_spanned(meta, msg)) } } fn get_meta_list(meta: &syn::Meta) -> Option<&syn::MetaList> { if let syn::Meta::List(ml) = meta { Some(ml) } else { None } } fn get_name_value(key: &str, ml: &syn::MetaList) -> Option<String> { ml.nested.iter().find_map(|nested| { if let syn::NestedMeta::Meta(syn::Meta::NameValue(mnv)) = nested { if mnv.ident == key { if let syn::Lit::Str(ref lit) = mnv.lit { Some(lit.value()) } else { None } } else { None } } else { None } }) } fn has_meta_word(word: &str, ml: &syn::MetaList) -> bool { ml.nested.iter().any(|nested| { if let syn::NestedMeta::Meta(syn::Meta::Word(w)) = nested { w == word } else { false } }) } fn get_aliases(ml: &syn::MetaList) -> Vec<String> { ml.nested .iter() .find_map(|nested| { if let syn::NestedMeta::Meta(syn::Meta::List(list)) = nested { if list.ident == ALIASES_KEY { Some(list) } else { None } } else { None } }) .map_or(Vec::new(), |list| { list.nested .iter() .filter_map(|nm| { if let syn::NestedMeta::Literal(syn::Lit::Str(alias)) = nm { Some(alias.value()) } else { None } }) .collect() }) }
28.42446
109
0.659074
b903c33de3bc149aafb673608b75505e40bf13de
2,367
use std::collections::VecDeque; use std::io; use super::proto::ws::Message; use util::{awrite, IOR}; // TODO: Consider how to handle larger streamed messages(maybe) // may be better to just offer an http interface for chunked DL anyways pub struct Writer { queue: VecDeque<Message>, state: State, } enum State { Idle, Writing { pos: usize, buf: Vec<u8> }, } enum WR { Incomplete, Complete, Blocked, } impl Writer { pub fn new() -> Writer { Writer { queue: VecDeque::new(), state: State::Idle, } } pub fn write<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> { loop { match self.do_write(w)? { WR::Complete => { self.next_msg(); if self.state.idle() { return Ok(()); } } WR::Incomplete => {} WR::Blocked => return Ok(()), } } } fn do_write<W: io::Write>(&mut self, w: &mut W) -> io::Result<WR> { match self.state { State::Idle => Ok(WR::Complete), State::Writing { ref mut pos, ref buf, } => match awrite(&buf[*pos..], w) { IOR::Complete => Ok(WR::Complete), IOR::Incomplete(a) => { *pos += a; Ok(WR::Incomplete) } IOR::Blocked => Ok(WR::Blocked), IOR::EOF => Err(io::ErrorKind::UnexpectedEof.into()), IOR::Err(e) => Err(e), }, } } fn next_msg(&mut self) { match self.queue.pop_front() { Some(m) => { self.state = State::Writing { pos: 0, buf: m.serialize(), } } None => self.state = State::Idle, } } pub fn enqueue(&mut self, msg: Message) { if self.state.idle() { self.state = State::Writing { pos: 0, buf: msg.serialize(), } } else { self.queue.push_back(msg); } } } impl State { fn idle(&self) -> bool { match *self { State::Idle => true, _ => false, } } }
24.153061
72
0.419096
72f440aa7c0e60dae38a41caef221268f0447d17
61,564
#[cfg(test)] mod tests { use crate::contract::{handle, init, query}; use crate::mock_querier::mock_dependencies; use cosmwasm_std::testing::{mock_env, MOCK_CONTRACT_ADDR}; use cosmwasm_std::{ from_binary, log, to_binary, BankMsg, BlockInfo, Coin, CosmosMsg, Decimal, Env, HumanAddr, StdError, Uint128, WasmMsg, }; use cw20::{Cw20HandleMsg, Cw20ReceiveMsg}; use mirror_protocol::common::OrderBy; use mirror_protocol::mint::{ Cw20HookMsg, HandleMsg, InitMsg, PositionResponse, PositionsResponse, QueryMsg, }; use terraswap::asset::{Asset, AssetInfo}; static TOKEN_CODE_ID: u64 = 10u64; fn mock_env_with_block_time<U: Into<HumanAddr>>(sender: U, sent: &[Coin], time: u64) -> Env { let env = mock_env(sender, sent); // register time return Env { block: BlockInfo { height: 1, time, chain_id: "columbus".to_string(), }, ..env }; } #[test] fn open_position() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::percent(50), &Decimal::percent(200), // 2 collateral_multiplier &false, )]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open position with unknown collateral let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset9999"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset9999", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap_err(); // expect error // must fail; collateral ratio is too low let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(140), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let res = handle(&mut deps, env.clone(), msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!( msg, "Can not open a position with low collateral ratio than minimum" ), _ => panic!("DO NOT ENTER ERROR"), } // successful attempt let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let res = handle(&mut deps, env.clone(), msg).unwrap(); assert_eq!( res.log, vec![ log("action", "open_position"), log("position_idx", "1"), log("mint_amount", "666666asset0000"), log("collateral_amount", "1000000uusd"), log("is_short", "false"), ] ); assert_eq!( res.messages, vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), send: vec![], msg: to_binary(&Cw20HandleMsg::Mint { recipient: HumanAddr::from("addr0000"), amount: Uint128(666666u128), }) .unwrap(), })] ); let res = query( &deps, QueryMsg::Position { position_idx: Uint128(1u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128(1u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, is_short: false, } ); // can query positions let res = query( &deps, QueryMsg::Positions { owner_addr: Some(HumanAddr::from("addr0000")), asset_token: None, limit: None, start_after: None, order_by: Some(OrderBy::Asc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![PositionResponse { idx: Uint128(1u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, is_short: false, }], } ); // Cannot directly deposit token let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::Unauthorized { .. } => (), _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(300), // 150 * 2 (multiplier) short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.log, vec![ log("action", "open_position"), log("position_idx", "2"), log("mint_amount", "166666asset0000"), // 1000000 * 0.5 (price to asset) * 0.5 multiplier / 1.5 (mcr) log("collateral_amount", "1000000asset0001"), log("is_short", "false"), ] ); assert_eq!( res.messages, vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), send: vec![], msg: to_binary(&Cw20HandleMsg::Mint { recipient: HumanAddr::from("addr0000"), amount: Uint128(166666u128), }) .unwrap(), })] ); let res = query( &deps, QueryMsg::Position { position_idx: Uint128(2u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128(2u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(166666u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(1000000u128), }, is_short: false, } ); // can query positions let res = query( &deps, QueryMsg::Positions { owner_addr: Some(HumanAddr::from("addr0000")), asset_token: None, limit: None, start_after: None, order_by: Some(OrderBy::Desc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![ PositionResponse { idx: Uint128(2u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(166666u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(1000000u128), }, is_short: false, }, PositionResponse { idx: Uint128(1u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, is_short: false, } ], } ); let res = query( &deps, QueryMsg::Positions { owner_addr: Some(HumanAddr::from("addr0000")), asset_token: None, limit: None, start_after: Some(Uint128(2u128)), order_by: Some(OrderBy::Desc), }, ) .unwrap(); let positions: PositionsResponse = from_binary(&res).unwrap(); assert_eq!( positions, PositionsResponse { positions: vec![PositionResponse { idx: Uint128(1u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, is_short: false, }], } ); } #[test] fn deposit() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(100)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::percent(50), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open uusd-asset0000 position let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let _res = handle(&mut deps, env.clone(), msg).unwrap(); // open asset0001-asset0000 position let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::Deposit { position_idx: Uint128(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, }; let env = mock_env( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], ); let _res = handle(&mut deps, env, msg).unwrap(); let res = query( &deps, QueryMsg::Position { position_idx: Uint128(1u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128(1u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(666666u128), }, collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(2000000u128), }, is_short: false, } ); // unauthorized failed; must be executed from token contract let msg = HandleMsg::Deposit { position_idx: Uint128(2u128), collateral: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(1000000u128), }, }; let env = mock_env("addr0000", &[]); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::Unauthorized { .. } => {} _ => panic!("Must return unauthorized error"), } // deposit other token asset let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), msg: Some( to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env("asset0001", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let res = query( &deps, QueryMsg::Position { position_idx: Uint128(2u128), }, ) .unwrap(); let position: PositionResponse = from_binary(&res).unwrap(); assert_eq!( position, PositionResponse { idx: Uint128(2u128), owner: HumanAddr::from("addr0000"), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(333333u128), }, collateral: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(2000000u128), }, is_short: false, } ); } #[test] fn mint() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open uusd-asset0000 position let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let _res = handle(&mut deps, env.clone(), msg).unwrap(); // open asset0001-asset0000 position let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::Deposit { position_idx: Uint128(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, }; let env = mock_env( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], ); let _res = handle(&mut deps, env, msg).unwrap(); // deposit other token asset let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), msg: Some( to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env("asset0001", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // failed to mint; due to min_collateral_ratio // price 100, collateral 1000000, min_collateral_ratio 150% // x * price * min_collateral_ratio < collateral // x < collateral/(price*min_collateral_ratio) = 10000 / 1.5 let msg = HandleMsg::Mint { position_idx: Uint128(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(6668u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot mint asset over than min collateral ratio") } _ => panic!("DO NOT ENTER HERE"), } // successfully mint within the min_collateral_ratio let msg = HandleMsg::Mint { position_idx: Uint128(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(6667u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.messages, vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Mint { amount: Uint128(6667u128), recipient: HumanAddr::from("addr0000"), }) .unwrap(), send: vec![], })] ); assert_eq!( res.log, vec![ log("action", "mint"), log("position_idx", "1"), log("mint_amount", "6667asset0000") ] ); // mint with other token; failed due to min collateral ratio let msg = HandleMsg::Mint { position_idx: Uint128(2u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(333334u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot mint asset over than min collateral ratio") } _ => panic!("DO NOT ENTER HERE"), } // mint with other token; let msg = HandleMsg::Mint { position_idx: Uint128(2u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(333333u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.messages, vec![CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Mint { amount: Uint128(333333u128), recipient: HumanAddr::from("addr0000"), }) .unwrap(), send: vec![], })] ); assert_eq!( res.log, vec![ log("action", "mint"), log("position_idx", "2"), log("mint_amount", "333333asset0000") ] ); } #[test] fn burn() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open uusd-asset0000 position let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let _res = handle(&mut deps, env.clone(), msg).unwrap(); // open asset0001-asset0000 position let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::Deposit { position_idx: Uint128(1u128), collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, }; let env = mock_env( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], ); let _res = handle(&mut deps, env, msg).unwrap(); // deposit other token asset let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), msg: Some( to_binary(&Cw20HookMsg::Deposit { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env("asset0001", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::Mint { position_idx: Uint128(1u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(6667u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let _res = handle(&mut deps, env, msg).unwrap(); // failed to burn more than the position amount let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(13334u128), msg: Some( to_binary(&Cw20HookMsg::Burn { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env("asset0000", &[]); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot burn asset more than you mint") } _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(13333u128), msg: Some( to_binary(&Cw20HookMsg::Burn { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.log, vec![ log("action", "burn"), log("position_idx", "1"), log("burn_amount", "13333asset0000"), log("protocol_fee", "13333uusd") // 13333 * 100 (price) * 0.01 (protocol_fee) ] ); assert_eq!( res.messages, vec![ CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Burn { amount: Uint128(13333u128), }) .unwrap(), send: vec![], }), CosmosMsg::Bank(BankMsg::Send { from_address: HumanAddr::from(MOCK_CONTRACT_ADDR), to_address: HumanAddr::from("collector0000"), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128(13333u128) }], }), ] ); // mint other asset let msg = HandleMsg::Mint { position_idx: Uint128(2u128), asset: Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, amount: Uint128(333333u128), }, short_params: None, }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let _res = handle(&mut deps, env, msg).unwrap(); // failed to burn more than the position amount let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(666667u128), msg: Some( to_binary(&Cw20HookMsg::Burn { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env("asset0000", &[]); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot burn asset more than you mint") } _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0000"), amount: Uint128(666666u128), msg: Some( to_binary(&Cw20HookMsg::Burn { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.log, vec![ log("action", "burn"), log("position_idx", "2"), log("burn_amount", "666666asset0000"), log("protocol_fee", "13333asset0001"), // 666666 * 100 * 0.01 / 50 ] ); assert_eq!( res.messages, vec![ CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Burn { amount: Uint128(666666u128), }) .unwrap(), send: vec![], }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0001"), msg: to_binary(&Cw20HandleMsg::Transfer { recipient: HumanAddr::from("collector0000"), amount: Uint128(13333u128) }) .unwrap(), send: vec![], }) ] ); } #[test] fn withdraw() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_tax( Decimal::percent(1), &[(&"uusd".to_string(), &Uint128(1000000u128))], ); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, )]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open uusd-asset0000 position let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let _res = handle(&mut deps, env.clone(), msg).unwrap(); // open asset0001-asset0000 position let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap(); // cannot withdraw more than (100 collateral token == 1 token) // due to min collateral ratio let msg = HandleMsg::Withdraw { position_idx: Uint128(1u128), collateral: Some(Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(101u128), }), }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!( msg, "Cannot withdraw collateral over than minimum collateral ratio" ), _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Withdraw { position_idx: Uint128(1u128), collateral: Some(Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(100u128), }), }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.log, vec![ log("action", "withdraw"), log("position_idx", "1"), log("withdraw_amount", "100uusd"), log("tax_amount", "1uusd"), ] ); // cannot withdraw more than (2 collateral token == 1 token) // due to min collateral ratio let msg = HandleMsg::Withdraw { position_idx: Uint128(2u128), collateral: Some(Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(2u128), }), }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => assert_eq!( msg, "Cannot withdraw collateral over than minimum collateral ratio" ), _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Withdraw { position_idx: Uint128(2u128), collateral: Some(Asset { info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0001"), }, amount: Uint128(1u128), }), }; let env = mock_env_with_block_time("addr0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.log, vec![ log("action", "withdraw"), log("position_idx", "2"), log("withdraw_amount", "1asset0001"), log("tax_amount", "0asset0001"), ] ); } #[test] fn auction() { let mut deps = mock_dependencies(20, &[]); deps.querier.with_tax( Decimal::percent(5u64), &[(&"uusd".to_string(), &Uint128(1000000u128))], ); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[ ( &"asset0000".to_string(), &Decimal::from_ratio(100u128, 1u128), &Decimal::one(), &false, ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, ), ]); let base_denom = "uusd".to_string(); let msg = InitMsg { owner: HumanAddr::from("owner0000"), oracle: HumanAddr::from("oracle0000"), collector: HumanAddr::from("collector0000"), collateral_oracle: HumanAddr::from("collateraloracle0000"), staking: HumanAddr::from("staking0000"), terraswap_factory: HumanAddr::from("terraswap_factory"), lock: HumanAddr::from("lock0000"), base_denom: base_denom.clone(), token_code_id: TOKEN_CODE_ID, protocol_fee_rate: Decimal::percent(1), }; let env = mock_env("addr0000", &[]); let _res = init(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0000"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(130), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); let msg = HandleMsg::RegisterAsset { asset_token: HumanAddr::from("asset0001"), auction_discount: Decimal::percent(20), min_collateral_ratio: Decimal::percent(150), ipo_params: None, }; let env = mock_env("owner0000", &[]); let _res = handle(&mut deps, env, msg).unwrap(); // open uusd-asset0000 position let msg = HandleMsg::OpenPosition { collateral: Asset { info: AssetInfo::NativeToken { denom: "uusd".to_string(), }, amount: Uint128(1000000u128), }, asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }; let env = mock_env_with_block_time( "addr0000", &[Coin { denom: "uusd".to_string(), amount: Uint128(1000000u128), }], 1000, ); let _res = handle(&mut deps, env.clone(), msg).unwrap(); // open asset0001-asset0000 position let msg = HandleMsg::Receive(Cw20ReceiveMsg { msg: Some( to_binary(&Cw20HookMsg::OpenPosition { asset_info: AssetInfo::Token { contract_addr: HumanAddr::from("asset0000"), }, collateral_ratio: Decimal::percent(150), short_params: None, }) .unwrap(), ), sender: HumanAddr::from("addr0000"), amount: Uint128(1000000u128), }); let env = mock_env_with_block_time("asset0001", &[], 1000); let _res = handle(&mut deps, env, msg).unwrap(); deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(115u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(1u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot liquidate a safely collateralized position") } _ => panic!("DO NOT ENTER HERE"), } let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(1u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot liquidate a safely collateralized position") } _ => panic!("DO NOT ENTER HERE"), } deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), ( &"asset0000".to_string(), &Decimal::from_ratio(116u128, 1u128), ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), ), ]); deps.querier.with_collateral_infos(&[ ( &"asset0000".to_string(), &Decimal::from_ratio(116u128, 1u128), &Decimal::one(), &false, ), ( &"asset0001".to_string(), &Decimal::from_ratio(50u128, 1u128), &Decimal::one(), &false, ), ]); // auction failed; liquidation amount is bigger than position amount let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(6667u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot liquidate more than the position amount") } _ => panic!("DO NOT ENTER HERE"), } // auction failed; liquidation amount is bigger than position amount let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(333334u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap_err(); match res { StdError::GenericErr { msg, .. } => { assert_eq!(msg, "Cannot liquidate more than the position amount") } _ => panic!("DO NOT ENTER HERE"), } // auction success let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(6666u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(1u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); assert_eq!( res.messages, vec![ CosmosMsg::Bank(BankMsg::Send { from_address: HumanAddr::from(MOCK_CONTRACT_ADDR), to_address: HumanAddr::from("addr0000"), amount: vec![Coin { denom: "uusd".to_string(), amount: Uint128(31838u128) // Tax (5%) 33430 * 1 / 1.05 -> 31838 }], }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Burn { amount: Uint128(6666u128), // asset value in collateral = 6666 * 116 = 773256 -- protocol fee = 7732 }) .unwrap(), send: vec![], }), CosmosMsg::Bank(BankMsg::Send { from_address: HumanAddr::from(MOCK_CONTRACT_ADDR), to_address: HumanAddr::from("addr0001"), amount: vec![Coin { denom: "uusd".to_string(), // Origin: 966,570 // ProtocolFee(1%): -7,732 // Tax(5%): -45,659 amount: Uint128(913179u128) }], }), CosmosMsg::Bank(BankMsg::Send { from_address: HumanAddr::from(MOCK_CONTRACT_ADDR), to_address: HumanAddr::from("collector0000"), amount: vec![Coin { denom: "uusd".to_string(), // Origin: 7732 // Tax(5%): -369 amount: Uint128(7363u128) }] }) ], ); assert_eq!( res.log, vec![ log("action", "auction"), log("position_idx", "1"), log("owner", "addr0000"), log("return_collateral_amount", "958838uusd"), log("liquidated_amount", "6666asset0000"), log("tax_amount", "45659uusd"), log("protocol_fee", "7732uusd"), ] ); // If the price goes too high, the return collateral amount // must be capped to position's collateral amount deps.querier.with_oracle_price(&[ (&"uusd".to_string(), &Decimal::one()), (&"asset0000".to_string(), &Decimal::percent(200)), (&"asset0001".to_string(), &Decimal::percent(50)), ]); deps.querier.with_collateral_infos(&[ ( &"asset0000".to_string(), &Decimal::percent(200), &Decimal::one(), &false, ), ( &"asset0001".to_string(), &Decimal::percent(50), &Decimal::one(), &false, ), ]); let msg = HandleMsg::Receive(Cw20ReceiveMsg { sender: HumanAddr::from("addr0001"), amount: Uint128(210000u128), msg: Some( to_binary(&Cw20HookMsg::Auction { position_idx: Uint128(2u128), }) .unwrap(), ), }); let env = mock_env_with_block_time("asset0000", &[], 1000u64); let res = handle(&mut deps, env, msg).unwrap(); // cap to collateral amount // required_asset_amount = 1000000 * 50 * 0.8 / 200 = 200000 // refund_asset_amount = 10000 assert_eq!( res.messages, vec![ CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Transfer { recipient: HumanAddr::from("addr0001"), amount: Uint128(10000u128), }) .unwrap(), send: vec![], }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0000"), msg: to_binary(&Cw20HandleMsg::Burn { amount: Uint128(200000u128), // asset value in collateral = 200000 * 200 / 50 = 800000 -- protocol fee = 8000 }) .unwrap(), send: vec![], }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0001"), msg: to_binary(&Cw20HandleMsg::Transfer { recipient: HumanAddr::from("addr0001"), amount: Uint128(992000u128), // protocol fee = 200000 * 0.01 = 2000 }) .unwrap(), send: vec![], }), CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: HumanAddr::from("asset0001"), msg: to_binary(&Cw20HandleMsg::Transfer { recipient: HumanAddr::from("collector0000"), amount: Uint128(8000u128), }) .unwrap(), send: vec![], }) ], ); assert_eq!( res.log, vec![ log("action", "auction"), log("position_idx", "2"), log("owner", "addr0000"), log("return_collateral_amount", "992000asset0001"), log("liquidated_amount", "200000asset0000"), log("tax_amount", "0asset0001"), log("protocol_fee", "8000asset0001"), ] ); } }
35.340987
133
0.462462
e803b96b21cfa63ef9001d8f03fd5b5cb8f9465e
5,028
// 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. use abi::call::{ArgAttribute, FnType, PassMode, Reg, RegKind}; use abi::{self, HasDataLayout, LayoutOf, TyLayout, TyLayoutMethods}; use spec::HasTargetSpec; #[derive(PartialEq)] pub enum Flavor { General, Fastcall } fn is_single_fp_element<'a, Ty, C>(cx: C, layout: TyLayout<'a, Ty>) -> bool where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout { match layout.abi { abi::Abi::Scalar(ref scalar) => { match scalar.value { abi::F32 | abi::F64 => true, _ => false } } abi::Abi::Aggregate { .. } => { if layout.fields.count() == 1 && layout.fields.offset(0).bytes() == 0 { is_single_fp_element(cx, layout.field(cx, 0)) } else { false } } _ => false } } pub fn compute_abi_info<'a, Ty, C>(cx: C, fty: &mut FnType<'a, Ty>, flavor: Flavor) where Ty: TyLayoutMethods<'a, C> + Copy, C: LayoutOf<Ty = Ty, TyLayout = TyLayout<'a, Ty>> + HasDataLayout + HasTargetSpec { if !fty.ret.is_ignore() { if fty.ret.layout.is_aggregate() { // Returning a structure. Most often, this will use // a hidden first argument. On some platforms, though, // small structs are returned as integers. // // Some links: // http://www.angelcode.com/dev/callconv/callconv.html // Clang's ABI handling is in lib/CodeGen/TargetInfo.cpp let t = cx.target_spec(); if t.options.abi_return_struct_as_int { // According to Clang, everyone but MSVC returns single-element // float aggregates directly in a floating-point register. if !t.options.is_like_msvc && is_single_fp_element(cx, fty.ret.layout) { match fty.ret.layout.size.bytes() { 4 => fty.ret.cast_to(Reg::f32()), 8 => fty.ret.cast_to(Reg::f64()), _ => fty.ret.make_indirect() } } else { match fty.ret.layout.size.bytes() { 1 => fty.ret.cast_to(Reg::i8()), 2 => fty.ret.cast_to(Reg::i16()), 4 => fty.ret.cast_to(Reg::i32()), 8 => fty.ret.cast_to(Reg::i64()), _ => fty.ret.make_indirect() } } } else { fty.ret.make_indirect(); } } else { fty.ret.extend_integer_width_to(32); } } for arg in &mut fty.args { if arg.is_ignore() { continue; } if arg.layout.is_aggregate() { arg.make_indirect_byval(); } else { arg.extend_integer_width_to(32); } } if flavor == Flavor::Fastcall { // Mark arguments as InReg like clang does it, // so our fastcall is compatible with C/C++ fastcall. // Clang reference: lib/CodeGen/TargetInfo.cpp // See X86_32ABIInfo::shouldPrimitiveUseInReg(), X86_32ABIInfo::updateFreeRegs() // IsSoftFloatABI is only set to true on ARM platforms, // which in turn can't be x86? let mut free_regs = 2; for arg in &mut fty.args { let attrs = match arg.mode { PassMode::Ignore | PassMode::Indirect(_) => continue, PassMode::Direct(ref mut attrs) => attrs, PassMode::Pair(..) | PassMode::Cast(_) => { unreachable!("x86 shouldn't be passing arguments by {:?}", arg.mode) } }; // At this point we know this must be a primitive of sorts. let unit = arg.layout.homogeneous_aggregate(cx).unwrap(); assert_eq!(unit.size, arg.layout.size); if unit.kind == RegKind::Float { continue; } let size_in_regs = (arg.layout.size.bits() + 31) / 32; if size_in_regs == 0 { continue; } if size_in_regs > free_regs { break; } free_regs -= size_in_regs; if arg.layout.size.bits() <= 32 && unit.kind == RegKind::Integer { attrs.set(ArgAttribute::InReg); } if free_regs == 0 { break; } } } }
34.916667
91
0.518298
dee736fd39ac858498e91b00494741f498336c30
955
#![doc(alias = "mod")] //! Helix endpoints regarding moderation use crate::{ helix::{self, Request}, types, }; use serde::{Deserialize, Serialize}; pub mod check_automod_status; pub mod get_banned_events; pub mod get_banned_users; pub mod get_moderator_events; pub mod get_moderators; pub mod manage_held_automod_messages; #[doc(inline)] pub use check_automod_status::{ CheckAutoModStatus, CheckAutoModStatusBody, CheckAutoModStatusRequest, }; #[doc(inline)] pub use get_banned_events::{BannedEvent, GetBannedEventsRequest}; #[doc(inline)] pub use get_banned_users::{BannedUser, GetBannedUsersRequest}; #[doc(inline)] pub use get_moderator_events::{GetModeratorEventsRequest, ModeratorEvent}; #[doc(inline)] pub use get_moderators::{GetModeratorsRequest, Moderator}; #[doc(inline)] pub use manage_held_automod_messages::{ AutoModAction, ManageHeldAutoModMessages, ManageHeldAutoModMessagesBody, ManageHeldAutoModMessagesRequest, };
28.088235
76
0.788482
214bbb89fe5f28e11c67619ff562ef290c704dc9
7,327
mod commands; mod db; mod detection; mod logging; mod parameters; mod settings_db; mod utils; mod webhook; use teloxide::{prelude::*, utils::command::BotCommand}; use teloxide::requests::RequestWithFile; use teloxide::types::InputFile; #[macro_use] extern crate anyhow; #[tokio::main] async fn main() { run().await; } async fn run() { logging::init_logger(); log::info!("Starting slowpoke bot"); let parameters = std::sync::Arc::new(parameters::Parameters::new()); let settings_db = std::sync::Arc::new(tokio::sync::Mutex::new( settings_db::SettingsDb::new(parameters.settings_database_path.as_path()) .expect("Cannot open settings database"), )); let pool_factory = std::sync::Arc::new(tokio::sync::Mutex::new(db::SqliteDatabasePoolFactory::new( parameters.chat_database_root_path.clone(), parameters.max_database_connections_count, ))); let bot = Bot::from_env(); let bot_parameters = parameters.clone(); let bot_dispatcher = Dispatcher::new(bot.clone()).messages_handler(move |rx: DispatcherHandlerRx<Message>| { rx.for_each(move |message| { let bot_name = bot_parameters.bot_name.clone(); let settings_db = settings_db.clone(); let owner_id = bot_parameters.owner_id; let pool_factory = pool_factory.clone(); async move { if let Some(message_text) = message.update.text() { // Handle commands. If command cannot be parsed - continue processing match commands::Command::parse(message_text, bot_name) { Ok(command) => { commands::command_answer(&message, command, owner_id, settings_db) .await .log_on_error() .await; return; } Err(_) => (), }; } log::info!("Handler is triggered"); // Check for forwarded messages if let Some(forwarded_message_id) = message.update.forward_from_message_id() { let mut pool_factory = pool_factory.lock().await; match pool_factory.create(message.update.chat_id()).await { Ok(client) => { match client.check_forward_message(forwarded_message_id).await { Ok(val) => { if val { match settings_db .lock() .await .get_setting("image_file_id") { Ok(value) => { log::info!("{}", value); if let Err(e) = message .answer_photo(InputFile::FileId(value)) .send() .await { log::info!( "Cannot send a response: {:?}", e ); } } Err(e) => { log::info!("Cannot get a setting: {:?}", e) } } } else { if let Err(e) = client .add_forwarded_message(forwarded_message_id) .await { log::warn!( "Cannot add a message to the database: {:?}", e ); } } } Err(e) => log::warn!("Database error: {:?}", e), } } Err(e) => log::warn!("Cannot create a db client: {}", e), } // 1) Check in a database. If exists - send a slowpoke and update timestamp // 2) If doesn't exist - push to a database [primary_id; current_timestamp; forwarded_message_id] } // For now we check whole message for being an URL. // We are not trying to find sub-URLs in a message, since it can lead to too high // false positives rate /*if detection::is_url(message_text) { // TODO: Check in a corresponding database and send slowpoke message, if such // link was earlier :) }*/ } }) }); if parameters.is_webhook_mode_enabled { log::info!("Webhook mode activated"); let rx = webhook::webhook(bot); bot_dispatcher .dispatch_with_listener( rx.await, LoggingErrorHandler::with_custom_text("An error from the update listener"), ) .await; } else { log::info!("Long polling mode activated"); bot.delete_webhook() .send() .await .expect("Cannot delete a webhook"); bot_dispatcher.dispatch().await; } } // Message types for check // 1) Images. For checks perceptual hash can be used. // 2) Forwards from the same channels. forward flag + original message id from source channel/user can be used // 3) Messages with links. Extract links from messages and store them // 4) Forwarding the same content from different channels - ? With images we can use perceptual hash. Video - possibly first frame + perceptual hash // Set time threshold for slowpoke bot - check only messages for a several days (configurable), since most duplicates appear at the same day. // Also it will reduce false positive count // Reply image configuration: after bot start owner fill set an image in private dialogue with bot. Bot will get file_id from it and save in persistent storage (yet another own database). // If storage will be missed - bot will ask again about the image (or file_id, if image is still exists)
45.509317
187
0.427051
1e942a4de54b5a619069da8b7915950421bb8dfa
544
use crate::{Endpoint, IntoResponse, Request, Response}; /// Endpoint for the [`map_to_response`](super::EndpointExt::map_to_response) /// method. pub struct MapToResponse<E> { inner: E, } impl<E> MapToResponse<E> { #[inline] pub(crate) fn new(inner: E) -> MapToResponse<E> { Self { inner } } } #[async_trait::async_trait] impl<E: Endpoint> Endpoint for MapToResponse<E> { type Output = Response; async fn call(&self, req: Request) -> Self::Output { self.inner.call(req).await.into_response() } }
22.666667
77
0.647059
1c5b5f24796e51513d4b00101503ed5864897901
43
aima.test.core.unit.search.SearchTestSuite
21.5
42
0.860465
3abb2b41f04d325fbaa599646a1bfd9e025f0fa8
2,009
//! `transfer` subcommand #![allow(clippy::never_loop)] use crate::{entrypoint, submit_tx::{TxError, maybe_submit, tx_params_wrapper}}; use abscissa_core::{Command, Options, Runnable}; use diem_json_rpc_types::views::TransactionView; use diem_transaction_builder::stdlib as transaction_builder; use diem_types::{account_address::AccountAddress}; use ol_types::config::TxType; use std::{path::PathBuf, process::exit}; /// `CreateAccount` subcommand #[derive(Command, Debug, Default, Options)] pub struct TransferCmd { #[options(short = "a", help = "the new user's address")] destination_account: String, #[options(short = "c", help = "the amount of coins to send to new user")] coins: u64, } impl Runnable for TransferCmd { fn run(&self) { let entry_args = entrypoint::get_args(); let destination = match self.destination_account.parse::<AccountAddress>(){ Ok(a) => a, Err(e) => { println!("ERROR: could not parse this account address: {}, message: {}", self.destination_account, &e.to_string()); exit(1); }, }; match balance_transfer(destination, self.coins, entry_args.save_path) { Ok(_) => println!("Success: Balance transfer posted: {}", self.destination_account), Err(e) => { println!("ERROR: execute balance transfer message: {:?}", &e); exit(1); }, } } } /// create an account by sending coin to it pub fn balance_transfer(destination: AccountAddress, coins: u64, save_path: Option<PathBuf>) -> Result<TransactionView, TxError>{ let tx_params = tx_params_wrapper(TxType::Mgmt).unwrap(); // NOTE: coins here do not have the scaling factor. Rescaling is the responsibility of the Move script. See the script in ol_accounts.move for detail. let script = transaction_builder::encode_balance_transfer_script_function( destination, coins, ); maybe_submit(script, &tx_params, save_path) }
37.203704
152
0.664012
c1b6c598b782e4d258b480bea623a7ad7d492005
3,112
#[doc = "Reader of register MB5_64B_ID"] pub type R = crate::R<u32, super::MB5_64B_ID>; #[doc = "Writer for register MB5_64B_ID"] pub type W = crate::W<u32, super::MB5_64B_ID>; #[doc = "Register MB5_64B_ID `reset()`'s with value 0"] impl crate::ResetValue for super::MB5_64B_ID { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `EXT`"] pub type EXT_R = crate::R<u32, u32>; #[doc = "Write proxy for field `EXT`"] pub struct EXT_W<'a> { w: &'a mut W, } impl<'a> EXT_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0x0003_ffff) | ((value as u32) & 0x0003_ffff); self.w } } #[doc = "Reader of field `STD`"] pub type STD_R = crate::R<u16, u16>; #[doc = "Write proxy for field `STD`"] pub struct STD_W<'a> { w: &'a mut W, } impl<'a> STD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07ff << 18)) | (((value as u32) & 0x07ff) << 18); self.w } } #[doc = "Reader of field `PRIO`"] pub type PRIO_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PRIO`"] pub struct PRIO_W<'a> { w: &'a mut W, } impl<'a> PRIO_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 << 29)) | (((value as u32) & 0x07) << 29); self.w } } impl R { #[doc = "Bits 0:17 - Contains extended (LOW word) identifier of message buffer."] #[inline(always)] pub fn ext(&self) -> EXT_R { EXT_R::new((self.bits & 0x0003_ffff) as u32) } #[doc = "Bits 18:28 - Contains standard/extended (HIGH word) identifier of message buffer."] #[inline(always)] pub fn std(&self) -> STD_R { STD_R::new(((self.bits >> 18) & 0x07ff) as u16) } #[doc = "Bits 29:31 - Local priority. This 3-bit fieldis only used when LPRIO_EN bit is set in MCR and it only makes sense for Tx buffers. These bits are not transmitted. They are appended to the regular ID to define the transmission priority."] #[inline(always)] pub fn prio(&self) -> PRIO_R { PRIO_R::new(((self.bits >> 29) & 0x07) as u8) } } impl W { #[doc = "Bits 0:17 - Contains extended (LOW word) identifier of message buffer."] #[inline(always)] pub fn ext(&mut self) -> EXT_W { EXT_W { w: self } } #[doc = "Bits 18:28 - Contains standard/extended (HIGH word) identifier of message buffer."] #[inline(always)] pub fn std(&mut self) -> STD_W { STD_W { w: self } } #[doc = "Bits 29:31 - Local priority. This 3-bit fieldis only used when LPRIO_EN bit is set in MCR and it only makes sense for Tx buffers. These bits are not transmitted. They are appended to the regular ID to define the transmission priority."] #[inline(always)] pub fn prio(&mut self) -> PRIO_W { PRIO_W { w: self } } }
34.966292
249
0.594152
08b04e20843605e000925ee95e6a0c723d60dc6d
23,733
#[macro_use] extern crate log; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_json; #[cfg(feature = "casting_errors")] extern crate zmq; pub type IndyHandle = i32; #[repr(transparent)] #[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)] pub struct WalletHandle(pub i32); pub const INVALID_WALLET_HANDLE : WalletHandle = WalletHandle(0); pub type CallbackHandle = i32; pub type PoolHandle = i32; pub const INVALID_POOL_HANDLE : PoolHandle = 0; pub type CommandHandle = i32; pub const INVALID_COMMAND_HANDLE : CommandHandle = 0; pub type StorageHandle = i32; pub type VdrHandle = i32; pub const INVALID_VDR_HANDLE : VdrHandle = 0; #[repr(transparent)] #[derive(Debug, Hash, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)] pub struct SearchHandle(pub i32); pub const INVALID_SEARCH_HANDLE : SearchHandle = SearchHandle(0); /* pub type SearchHandle = i32; pub const INVALID_SEARCH_HANDLE : SearchHandle = 0; */ pub mod domain; pub mod errors; pub use errors::IndyError; pub mod validation; #[derive(Debug, PartialEq, Eq, Copy, Clone)] #[repr(i32)] pub enum ErrorCode { Success = 0, // Common errors // Caller passed invalid value as param 1 (null, invalid json and etc..) CommonInvalidParam1 = 100, // Caller passed invalid value as param 2 (null, invalid json and etc..) CommonInvalidParam2 = 101, // Caller passed invalid value as param 3 (null, invalid json and etc..) CommonInvalidParam3 = 102, // Caller passed invalid value as param 4 (null, invalid json and etc..) CommonInvalidParam4 = 103, // Caller passed invalid value as param 5 (null, invalid json and etc..) CommonInvalidParam5 = 104, // Caller passed invalid value as param 6 (null, invalid json and etc..) CommonInvalidParam6 = 105, // Caller passed invalid value as param 7 (null, invalid json and etc..) CommonInvalidParam7 = 106, // Caller passed invalid value as param 8 (null, invalid json and etc..) CommonInvalidParam8 = 107, // Caller passed invalid value as param 9 (null, invalid json and etc..) CommonInvalidParam9 = 108, // Caller passed invalid value as param 10 (null, invalid json and etc..) CommonInvalidParam10 = 109, // Caller passed invalid value as param 11 (null, invalid json and etc..) CommonInvalidParam11 = 110, // Caller passed invalid value as param 12 (null, invalid json and etc..) CommonInvalidParam12 = 111, // Invalid library state was detected in runtime. It signals library bug CommonInvalidState = 112, // Object (json, config, key, credential and etc...) passed by library caller has invalid structure CommonInvalidStructure = 113, // IO Error CommonIOError = 114, // Caller passed invalid value as param 13 (null, invalid json and etc..) CommonInvalidParam13 = 115, // Caller passed invalid value as param 14 (null, invalid json and etc..) CommonInvalidParam14 = 116, // Caller passed invalid value as param 15 (null, invalid json and etc..) CommonInvalidParam15 = 117, // Caller passed invalid value as param 16 (null, invalid json and etc..) CommonInvalidParam16 = 118, // Caller passed invalid value as param 17 (null, invalid json and etc..) CommonInvalidParam17 = 119, // Caller passed invalid value as param 18 (null, invalid json and etc..) CommonInvalidParam18 = 120, // Caller passed invalid value as param 19 (null, invalid json and etc..) CommonInvalidParam19 = 121, // Caller passed invalid value as param 20 (null, invalid json and etc..) CommonInvalidParam20 = 122, // Caller passed invalid value as param 21 (null, invalid json and etc..) CommonInvalidParam21 = 123, // Caller passed invalid value as param 22 (null, invalid json and etc..) CommonInvalidParam22 = 124, // Caller passed invalid value as param 23 (null, invalid json and etc..) CommonInvalidParam23 = 125, // Caller passed invalid value as param 24 (null, invalid json and etc..) CommonInvalidParam24 = 126, // Caller passed invalid value as param 25 (null, invalid json and etc..) CommonInvalidParam25 = 127, // Caller passed invalid value as param 26 (null, invalid json and etc..) CommonInvalidParam26 = 128, // Caller passed invalid value as param 27 (null, invalid json and etc..) CommonInvalidParam27 = 129, // Wallet errors // Caller passed invalid wallet handle WalletInvalidHandle = 200, // Unknown type of wallet was passed on create_wallet WalletUnknownTypeError = 201, // Attempt to register already existing wallet type WalletTypeAlreadyRegisteredError = 202, // Attempt to create wallet with name used for another exists wallet WalletAlreadyExistsError = 203, // Requested entity id isn't present in wallet WalletNotFoundError = 204, // Trying to use wallet with pool that has different name WalletIncompatiblePoolError = 205, // Trying to open wallet that was opened already WalletAlreadyOpenedError = 206, // Attempt to open encrypted wallet with invalid credentials WalletAccessFailed = 207, // Input provided to wallet operations is considered not valid WalletInputError = 208, // Decoding of wallet data during input/output failed WalletDecodingError = 209, // Storage error occurred during wallet operation WalletStorageError = 210, // Error during encryption-related operations WalletEncryptionError = 211, // Requested wallet item not found WalletItemNotFound = 212, // Returned if wallet's add_record operation is used with record name that already exists WalletItemAlreadyExists = 213, // Returned if provided wallet query is invalid WalletQueryError = 214, // Ledger errors // Trying to open pool ledger that wasn't created before PoolLedgerNotCreatedError = 300, // Caller passed invalid pool ledger handle PoolLedgerInvalidPoolHandle = 301, // Pool ledger terminated PoolLedgerTerminated = 302, // No consensus during ledger operation LedgerNoConsensusError = 303, // Attempt to parse invalid transaction response LedgerInvalidTransaction = 304, // Attempt to send transaction without the necessary privileges LedgerSecurityError = 305, // Attempt to create pool ledger config with name used for another existing pool PoolLedgerConfigAlreadyExistsError = 306, // Timeout for action PoolLedgerTimeout = 307, // Attempt to open Pool for witch Genesis Transactions are not compatible with set Protocol version. // Call pool.indy_set_protocol_version to set correct Protocol version. PoolIncompatibleProtocolVersion = 308, // Item not found on ledger. LedgerNotFound = 309, // Revocation registry is full and creation of new registry is necessary AnoncredsRevocationRegistryFullError = 400, AnoncredsInvalidUserRevocId = 401, // Attempt to generate master secret with duplicated name AnoncredsMasterSecretDuplicateNameError = 404, AnoncredsProofRejected = 405, AnoncredsCredentialRevoked = 406, // Attempt to create credential definition with duplicated id AnoncredsCredDefAlreadyExistsError = 407, // Crypto errors // Unknown format of DID entity keys UnknownCryptoTypeError = 500, // Attempt to create duplicate did DidAlreadyExistsError = 600, // Unknown payment method was given PaymentUnknownMethodError = 700, //No method were scraped from inputs/outputs or more than one were scraped PaymentIncompatibleMethodsError = 701, // Insufficient funds on inputs PaymentInsufficientFundsError = 702, // No such source on a ledger PaymentSourceDoesNotExistError = 703, // Operation is not supported for payment method PaymentOperationNotSupportedError = 704, // Extra funds on inputs PaymentExtraFundsError = 705, // The transaction is not allowed to a requester TransactionNotAllowedError = 706, // Query Account does not exist in the pool QueryAccountDoesNotexistError = 808, } pub mod wallet { use super::*; use libc::c_char; /// Create the wallet storage (For example, database creation) /// /// #Params /// name: wallet storage name (the same as wallet name) /// config: wallet storage config (For example, database config) /// credentials_json: wallet storage credentials (For example, database credentials) /// metadata: wallet metadata (For example encrypted keys). pub type WalletCreate = extern fn(name: *const c_char, config: *const c_char, credentials_json: *const c_char, metadata: *const c_char) -> ErrorCode; /// Open the wallet storage (For example, opening database connection) /// /// #Params /// name: wallet storage name (the same as wallet name) /// config: wallet storage config (For example, database config) /// credentials_json: wallet storage credentials (For example, database credentials) /// storage_handle_p: pointer to store opened storage handle pub type WalletOpen = extern fn(name: *const c_char, config: *const c_char, credentials_json: *const c_char, storage_handle_p: *mut IndyHandle) -> ErrorCode; /// Close the opened walled storage (For example, closing database connection) /// /// #Params /// storage_handle: opened storage handle (See open handler) pub type WalletClose = extern fn(storage_handle: StorageHandle) -> ErrorCode; /// Delete the wallet storage (For example, database deletion) /// /// #Params /// name: wallet storage name (the same as wallet name) /// config: wallet storage config (For example, database config) /// credentials_json: wallet storage credentials (For example, database credentials) pub type WalletDelete = extern fn(name: *const c_char, config: *const c_char, credentials_json: *const c_char) -> ErrorCode; /// Create a new record in the wallet storage /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// value: the value of record (pointer to buffer) /// value_len: the value of record (buffer size) /// tags_json: the record tags used for search and storing meta information as json: /// { /// "tagName1": "tag value 1", // string value /// "tagName2": 123, // numeric value /// } /// Note that null means no tags pub type WalletAddRecord = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, value: *const u8, value_len: usize, tags_json: *const c_char) -> ErrorCode; /// Update a record value /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// value: the value of record (pointer to buffer) /// value_len: the value of record (buffer size) pub type WalletUpdateRecordValue = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, value: *const u8, value_len: usize, ) -> ErrorCode; /// Update a record tags /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// tags_json: the new record tags used for search and storing meta information as json: /// { /// "tagName1": "tag value 1", // string value /// "tagName2": 123, // numeric value /// } /// Note that null means no tags pub type WalletUpdateRecordTags = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, tags_json: *const c_char) -> ErrorCode; /// Add new tags to the record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// tags_json: the additional record tags as json: /// { /// "tagName1": "tag value 1", // string value /// "tagName2": 123, // numeric value, /// ... /// } /// Note that null means no tags /// Note if some from provided tags already assigned to the record than /// corresponding tags values will be replaced pub type WalletAddRecordTags = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, tags_json: *const c_char) -> ErrorCode; /// Delete tags from the record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// tag_names_json: the list of tag names to remove from the record as json array: /// ["tagName1", "tagName2", ...] /// Note that null means no tag names pub type WalletDeleteRecordTags = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, tag_names_json: *const c_char) -> ErrorCode; /// Delete an existing record in the wallet storage /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: record type /// id: the id of record pub type WalletDeleteRecord = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char) -> ErrorCode; /// Get an wallet storage record by id /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// id: the id of record /// options_json: //TODO: FIXME: Think about replacing by bitmask /// { /// retrieveType: (optional, false by default) Retrieve record type, /// retrieveValue: (optional, true by default) Retrieve record value, /// retrieveTags: (optional, false by default) Retrieve record tags /// } /// record_handle_p: pointer to store retrieved record handle pub type WalletGetRecord = extern fn(storage_handle: StorageHandle, type_: *const c_char, id: *const c_char, options_json: *const c_char, record_handle_p: *mut IndyHandle) -> ErrorCode; /// Get an id for retrieved wallet storage record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// record_handle: retrieved record handle (See get_record handler) /// /// returns: record id /// Note that pointer lifetime the same as retrieved record lifetime /// (until record_free called) pub type WalletGetRecordId = extern fn(storage_handle: StorageHandle, record_handle: IndyHandle, record_id_p: *mut *const c_char) -> ErrorCode; /// Get an type for retrieved wallet storage record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// record_handle: retrieved record handle (See get_record handler) /// /// returns: record type /// Note that pointer lifetime the same as retrieved record lifetime /// (until record_free called) pub type WalletGetRecordType = extern fn(storage_handle: StorageHandle, record_handle: IndyHandle, record_type_p: *mut *const c_char) -> ErrorCode; /// Get an value for retrieved wallet storage record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// record_handle: retrieved record handle (See get_record handler) /// /// returns: record value /// Note that pointer lifetime the same as retrieved record lifetime /// (until record_free called) /// Note that null be returned if no value retrieved pub type WalletGetRecordValue = extern fn(storage_handle: StorageHandle, record_handle: IndyHandle, record_value_p: *mut *const u8, record_value_len_p: *mut usize) -> ErrorCode; /// Get an tags for retrieved wallet record /// /// #Params /// storage_handle: opened storage handle (See open handler) /// record_handle: retrieved record handle (See get_record handler) /// /// returns: record tags as json /// Note that pointer lifetime the same as retrieved record lifetime /// (until record_free called) /// Note that null be returned if no tags retrieved pub type WalletGetRecordTags = extern fn(storage_handle: StorageHandle, record_handle: IndyHandle, record_tags_p: *mut *const c_char) -> ErrorCode; /// Free retrieved wallet record (make retrieved record handle invalid) /// /// #Params /// storage_handle: opened storage handle (See open_wallet_storage) /// record_handle: retrieved record handle (See wallet_storage_get_wallet_record) pub type WalletFreeRecord = extern fn(storage_handle: StorageHandle, record_handle: IndyHandle) -> ErrorCode; /// Get storage metadata /// /// #Params /// storage_handle: opened storage handle (See open handler) /// /// returns: metadata as base64 value /// Note that pointer lifetime is static pub type WalletGetStorageMetadata = extern fn(storage_handle: StorageHandle, metadata_p: *mut *const c_char, metadata_handle: *mut IndyHandle) -> ErrorCode; /// Set storage metadata /// /// #Params /// storage_handle: opened storage handle (See open handler) /// metadata_p: base64 value of metadata /// /// Note if storage already have metadata record it will be overwritten. pub type WalletSetStorageMetadata = extern fn(storage_handle: StorageHandle, metadata_p: *const c_char) -> ErrorCode; /// Free retrieved storage metadata record (make retrieved storage metadata handle invalid) /// /// #Params /// storage_handle: opened storage handle (See open_wallet_storage) /// metadata_handle: retrieved record handle (See wallet_storage_get_storage_metadata) pub type WalletFreeStorageMetadata = extern fn(storage_handle: StorageHandle, metadata_handle: IndyHandle) -> ErrorCode; /// Search for wallet storage records /// /// #Params /// storage_handle: opened storage handle (See open handler) /// type_: allows to separate different record types collections /// query_json: MongoDB style query to wallet record tags: /// { /// "tagName": "tagValue", /// $or: { /// "tagName2": { $regex: 'pattern' }, /// "tagName3": { $gte: 123 }, /// }, /// } /// options_json: //TODO: FIXME: Think about replacing by bitmask /// { /// retrieveRecords: (optional, true by default) If false only "counts" will be calculated, /// retrieveTotalCount: (optional, false by default) Calculate total count, /// retrieveType: (optional, false by default) Retrieve record type, /// retrieveValue: (optional, true by default) Retrieve record value, /// retrieveTags: (optional, false by default) Retrieve record tags, /// } /// search_handle_p: pointer to store wallet search handle pub type WalletSearchRecords = extern fn(storage_handle: StorageHandle, type_: *const c_char, query_json: *const c_char, options_json: *const c_char, search_handle_p: *mut i32) -> ErrorCode; /// Search for all wallet storage records /// /// #Params /// storage_handle: opened storage handle (See open handler) /// search_handle_p: pointer to store wallet search handle pub type WalletSearchAllRecords = extern fn(storage_handle: StorageHandle, search_handle_p: *mut i32) -> ErrorCode; /// Get total count of records that corresponds to wallet storage search query /// /// #Params /// storage_handle: opened storage handle (See open handler) /// search_handle: wallet search handle (See search_records handler) /// /// returns: total count of records that corresponds to wallet storage search query /// Note -1 will be returned if retrieveTotalCount set to false for search_records pub type WalletGetSearchTotalCount = extern fn(storage_handle: StorageHandle, search_handle: i32, total_count_p: *mut usize) -> ErrorCode; /// Get the next wallet storage record handle retrieved by this wallet search. /// /// #Params /// storage_handle: opened storage handle (See open handler) /// search_handle: wallet search handle (See search_records handler) /// /// returns: record handle (the same as for get_record handler) /// Note if no more records WalletNoRecords error will be returned pub type WalletFetchSearchNextRecord = extern fn(storage_handle: StorageHandle, search_handle: i32, record_handle_p: *mut IndyHandle) -> ErrorCode; /// Free wallet search (make search handle invalid) /// /// #Params /// storage_handle: opened storage handle (See open handler) /// search_handle: wallet search handle (See search_records handler) pub type WalletFreeSearch = extern fn(storage_handle: StorageHandle, search_handle: i32) -> ErrorCode; }
39.887395
104
0.619644
2670bef0d897f6147ad45a68b976bf3739e843a1
170
use rocket::local::Client; use rocket::http::Status; use crate::create_rocket; #[test] fn workspaces_routes() { let client = Client::new(create_rocket()).unwrap(); }
21.25
55
0.705882
8710957c5cf3e4fcdc73dc775fe752f52d78cb4f
1,443
use super::Storage; use core::convert::Infallible; use ockam_core::async_trait; use ockam_core::compat::collections::BTreeMap; use ockam_core::compat::sync::{Arc, RwLock}; type Attributes = BTreeMap<String, Vec<u8>>; #[derive(Clone, Default)] pub struct Store { map: Arc<RwLock<BTreeMap<String, Attributes>>>, } impl Store { pub fn new() -> Self { Store { map: Arc::new(RwLock::new(BTreeMap::new())), } } } #[async_trait] impl Storage for Store { type Error = Infallible; async fn get(&self, id: &str, key: &str) -> Result<Option<Vec<u8>>, Self::Error> { let m = self.map.read().unwrap(); if let Some(a) = m.get(id) { return Ok(a.get(key).cloned()); } Ok(None) } async fn set(&self, id: &str, key: String, val: Vec<u8>) -> Result<(), Self::Error> { let mut m = self.map.write().unwrap(); match m.get_mut(id) { Some(a) => { a.insert(key, val); } None => { m.insert(id.to_string(), BTreeMap::from([(key, val)])); } } Ok(()) } async fn del(&self, id: &str, key: &str) -> Result<(), Self::Error> { let mut m = self.map.write().unwrap(); if let Some(a) = m.get_mut(id) { a.remove(key); if a.is_empty() { m.remove(id); } } Ok(()) } }
24.87931
89
0.499653
fb6e074fe0706bf81beb4ec7c4f40ede47d43e88
24
pub mod dfs_serializer;
12
23
0.833333
d7c1b586e7d4b37c7f558fec32a7106acb302fd6
1,703
// 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. // All files in the project carrying such notice may not be copied, modified, or distributed // except according to those terms. use ctypes::{c_double, c_float, c_int, c_schar, c_short, c_uchar, c_uint, c_ushort, c_void}; //48 pub type GLenum = c_uint; pub type GLboolean = c_uchar; pub type GLbitfield = c_uint; pub type GLbyte = c_schar; pub type GLshort = c_short; pub type GLint = c_int; pub type GLsizei = c_int; pub type GLubyte = c_uchar; pub type GLushort = c_ushort; pub type GLuint = c_uint; pub type GLfloat = c_float; pub type GLclampf = c_float; pub type GLdouble = c_double; pub type GLclampd = c_double; pub type GLvoid = c_void; //63 //68 //AccumOp pub const GL_ACCUM: GLenum = 0x0100; pub const GL_LOAD: GLenum = 0x0101; pub const GL_RETURN: GLenum = 0x0102; pub const GL_MULT: GLenum = 0x0103; pub const GL_ADD: GLenum = 0x0104; //AlphaFunction pub const GL_NEVER: GLenum = 0x0200; pub const GL_LESS: GLenum = 0x0201; pub const GL_EQUAL: GLenum = 0x0202; pub const GL_LEQUAL: GLenum = 0x0203; pub const GL_GREATER: GLenum = 0x0204; pub const GL_NOTEQUAL: GLenum = 0x0205; pub const GL_GEQUAL: GLenum = 0x0206; pub const GL_ALWAYS: GLenum = 0x0207; // TODO: we're missing about 1500 lines of defines and methods // until that time, you can use the excellent GL crate // https://github.com/brendanzab/gl-rs extern "system" { pub fn glAccum( op: GLenum, value: GLfloat, ); pub fn glAlphaFunc( func: GLenum, reference: GLclampf, ); }
32.132075
92
0.724604
16cd729e9c0bf774096bf4d79d3f7a2dffd3f428
1,026
use crate::database::{Database, HasArguments, HasStatement, HasStatementCache, HasValueRef}; use crate::mssql::{ MssqlArguments, MssqlColumn, MssqlConnection, MssqlQueryResult, MssqlRow, MssqlStatement, MssqlTransactionManager, MssqlTypeInfo, MssqlValue, MssqlValueRef, }; /// MSSQL database driver. #[derive(Debug)] pub struct Mssql; impl Database for Mssql { type Connection = MssqlConnection; type TransactionManager = MssqlTransactionManager; type Row = MssqlRow; type QueryResult = MssqlQueryResult; type Column = MssqlColumn; type TypeInfo = MssqlTypeInfo; type Value = MssqlValue; } impl<'r> HasValueRef<'r> for Mssql { type Database = Mssql; type ValueRef = MssqlValueRef<'r>; } impl<'q> HasStatement<'q> for Mssql { type Database = Mssql; type Statement = MssqlStatement<'q>; } impl HasArguments<'_> for Mssql { type Database = Mssql; type Arguments = MssqlArguments; type ArgumentBuffer = Vec<u8>; } impl HasStatementCache for Mssql {}
21.375
93
0.716374
c1ccb9979d1faa23756e6ee60e05650d39c94b32
7,172
use crate::types::blockchain::{ Block, BlockIdentifier, SingleBlockQuery, SingleTransactionQuery, Transaction, }; use crate::{define_attribute_many_error, ManyError}; use many_macros::many_module; use minicbor::{Decode, Encode}; #[cfg(test)] use mockall::{automock, predicate::*}; define_attribute_many_error!( attribute 1 => { 1: pub fn height_out_of_bound(height, min, max) => "Height {height} is out of bound. Range: {min} - {max}.", 2: pub fn invalid_hash() => "Requested hash does not have the right format.", 3: pub fn unknown_block() => "Requested block query does not match any block.", 4: pub fn unknown_transaction() => "Requested transaction query does not match any transaction.", } ); #[derive(Clone, Encode, Decode)] #[cbor(map)] pub struct InfoReturns { #[n(0)] pub latest_block: BlockIdentifier, #[cbor(n(1), with = "minicbor::bytes")] pub app_hash: Option<Vec<u8>>, #[n(2)] pub retained_height: Option<u64>, } #[derive(Clone, Debug, Encode, Decode, PartialEq)] #[cbor(map)] pub struct BlockArgs { #[n(0)] pub query: SingleBlockQuery, } #[derive(Clone, Encode, Decode)] #[cbor(map)] pub struct BlockReturns { #[n(0)] pub block: Block, } #[derive(Clone, Debug, Encode, Decode, PartialEq)] #[cbor(map)] pub struct TransactionArgs { #[n(0)] pub query: SingleTransactionQuery, } #[derive(Clone, Encode, Decode)] #[cbor(map)] pub struct TransactionReturns { #[n(0)] pub txn: Transaction, } #[many_module(name = BlockchainModule, id = 1, namespace = blockchain, many_crate = crate)] #[cfg_attr(test, automock)] pub trait BlockchainModuleBackend: Send { fn info(&self) -> Result<InfoReturns, ManyError>; fn block(&self, args: BlockArgs) -> Result<BlockReturns, ManyError>; fn transaction(&self, args: TransactionArgs) -> Result<TransactionReturns, ManyError>; } #[cfg(test)] mod tests { use super::*; use crate::{ server::module::testutils::{call_module, call_module_cbor}, types::{blockchain::TransactionIdentifier, Timestamp}, }; use mockall::predicate; use std::sync::{Arc, Mutex}; #[test] fn info() { let mut mock = MockBlockchainModuleBackend::new(); mock.expect_info().times(1).return_const(Ok(InfoReturns { latest_block: { BlockIdentifier { hash: vec![0u8; 8], height: 0, } }, app_hash: Some(vec![2u8; 8]), retained_height: Some(2), })); let module = super::BlockchainModule::new(Arc::new(Mutex::new(mock))); let info_returns: InfoReturns = minicbor::decode(&call_module(1, &module, "blockchain.info", "null").unwrap()).unwrap(); assert_eq!( info_returns.latest_block, BlockIdentifier::new(vec![0u8; 8], 0) ); assert_eq!(info_returns.app_hash, Some(vec![2u8; 8])); assert_eq!(info_returns.retained_height, Some(2)); } #[test] fn block_hash() { let data = BlockArgs { query: SingleBlockQuery::Hash(vec![5u8; 8]), }; let mut mock = MockBlockchainModuleBackend::new(); mock.expect_block() .with(predicate::eq(data.clone())) .times(1) .returning(|args| match args.query { SingleBlockQuery::Hash(v) => Ok(BlockReturns { block: Block { id: BlockIdentifier::new(v, 1), parent: BlockIdentifier::genesis(), app_hash: Some(vec![4u8; 8]), timestamp: Timestamp::now(), txs_count: 1, txs: vec![Transaction { id: TransactionIdentifier { hash: vec![] }, content: None, }], }, }), _ => unimplemented!(), }); let module = super::BlockchainModule::new(Arc::new(Mutex::new(mock))); let block_returns: BlockReturns = minicbor::decode( &call_module_cbor( 1, &module, "blockchain.block", minicbor::to_vec(data).unwrap(), ) .unwrap(), ) .unwrap(); assert_eq!( block_returns.block.id, BlockIdentifier::new(vec![5u8; 8], 1) ); } #[test] fn block_height() { let data = BlockArgs { query: SingleBlockQuery::Height(3), }; let mut mock = MockBlockchainModuleBackend::new(); mock.expect_block() .with(predicate::eq(data.clone())) .times(1) .returning(|args| match args.query { SingleBlockQuery::Height(h) => Ok(BlockReturns { block: Block { id: BlockIdentifier::new(vec![3u8; 8], h), parent: BlockIdentifier::genesis(), app_hash: Some(vec![4u8; 8]), timestamp: Timestamp::now(), txs_count: 1, txs: vec![Transaction { id: TransactionIdentifier { hash: vec![] }, content: None, }], }, }), _ => unimplemented!(), }); let module = super::BlockchainModule::new(Arc::new(Mutex::new(mock))); let block_returns: BlockReturns = minicbor::decode( &call_module_cbor( 1, &module, "blockchain.block", minicbor::to_vec(data).unwrap(), ) .unwrap(), ) .unwrap(); assert_eq!( block_returns.block.id, BlockIdentifier::new(vec![3u8; 8], 3) ); } #[test] fn transaction() { let data = TransactionArgs { query: SingleTransactionQuery::Hash(vec![6u8; 8]), }; let mut mock = MockBlockchainModuleBackend::new(); mock.expect_transaction() .with(predicate::eq(data.clone())) .times(1) .returning(|args| match args.query { SingleTransactionQuery::Hash(v) => Ok(TransactionReturns { txn: Transaction { id: TransactionIdentifier { hash: v }, content: None, }, }), }); let module = super::BlockchainModule::new(Arc::new(Mutex::new(mock))); let transaction_returns: TransactionReturns = minicbor::decode( &call_module_cbor( 1, &module, "blockchain.transaction", minicbor::to_vec(data).unwrap(), ) .unwrap(), ) .unwrap(); assert_eq!(transaction_returns.txn.id.hash, vec![6u8; 8]); assert_eq!(transaction_returns.txn.content, None); } }
31.318777
100
0.516871
1cd213624a9ac7bfcd699c78a58d977660b9d147
3,917
use std::io::Write; use anyhow::Result; use git2::DiffFormat; use minimad::TextTemplate; use termimad::{Area, Event, FmtText, TextView}; use crate::{ context::AppContext, git::CommitInfo, keys::*, screen::Screen, state::{AppState, CommandResult}, }; /// Represents a line from the diff with its type struct Line(LineType, String); /// A type of line from a diff enum LineType { FileHeader, HunkHeader, Context, Insertion, Deletion, } pub struct CommitState { commit_info: CommitInfo, files_changed: usize, insertions: usize, deletions: usize, diff_lines: Vec<Line>, } impl CommitState { pub fn new(commit: CommitInfo, ctx: &AppContext) -> Result<Self> { let git_commit = ctx.repo.find_commit(commit.oid)?; let tree = git_commit.tree()?; let parent_tree = git_commit.parent(0)?.tree()?; let diff = ctx .repo .diff_tree_to_tree(Some(&parent_tree), Some(&tree), None)?; let stats = diff.stats()?; let mut diff_lines = Vec::new(); diff.print(DiffFormat::Patch, |_delta, _hunk, line| { let content = String::from_utf8_lossy(line.content()).to_string(); if line.origin() == 'F' { // File header: contains multiple lines so split them up let mut content_lines: Vec<_> = content .split('\n') .map(|line| Line(LineType::FileHeader, String::from(line))) .collect(); diff_lines.append(&mut content_lines); } else if line.origin() == 'H' { // Hunk header diff_lines.push(Line(LineType::HunkHeader, content)); } else { // diff lines let line_str = format!("{} {}", line.origin(), content); let line_type = match line.origin() { '+' => LineType::Insertion, '-' => LineType::Deletion, _ => LineType::Context, }; diff_lines.push(Line(line_type, line_str)); } true })?; Ok(Self { commit_info: commit, files_changed: stats.files_changed(), insertions: stats.insertions(), deletions: stats.deletions(), diff_lines, }) } } impl AppState for CommitState { fn handle_event(&mut self, event: Event, _ctx: &AppContext) -> CommandResult { match event { Q => CommandResult::PopState, _ => CommandResult::Keep, } } fn display(&mut self, mut w: &mut dyn Write, _ctx: &AppContext, screen: &Screen) -> Result<()> { let (width, height) = screen.dimensions; screen.clear(w)?; let area = Area::new(0, 1, width, height - 2); let template = TextTemplate::from(COMMIT_INFO); let mut expander = template.expander(); let oid = self.commit_info.oid.to_string(); let files_changed = self.files_changed.to_string(); let insertions = self.insertions.to_string(); let deletions = self.deletions.to_string(); expander .set("oid", &oid) .set("files_changed", &files_changed) .set("insertions", &insertions) .set("deletions", &deletions) .set("message", &self.commit_info.message); for Line(_line_type, line) in &self.diff_lines { expander.sub("diff").set("line", line); } let text = FmtText::from_text(&screen.skin.normal, expander.expand(), Some(width as usize)); let tv = TextView::from(&area, &text); tv.write_on(&mut w)?; Ok(()) } } const COMMIT_INFO: &str = r#" # Commit ${oid} ${message} --- ${files_changed} files changed, ${insertions} insertions(+), ${deletions} deletions(-) ${diff ${line} } "#;
30.130769
100
0.553995
76c1e97161909cb6518b31867b8d0159bce8466c
3,370
use ndarray::{array, Array, Array2, Axis}; use ndarray_rand::{rand::SeedableRng, rand_distr::Uniform, RandomExt}; use rand_pcg::Pcg64; use std::io::Write; use std::time::Instant; use std::fs::File; fn sigmoid(z: Array2<f64>) -> Array2<f64> { 1. / (1. + (-z).mapv(f64::exp)) } /// Structure of a Neural Network to learn the `XOR` function /// - 2 input features /// - 2 hidden neurons /// - 1 output neuron fn main() { // Generate dataset of `XOR` examples // We define the array as suggested by Andrew Ng: features are rows, examples are columns // This makes the computation of the linear combination match the math closer: W^T * X let x: Array2<f64> = array![[0., 0., 1., 1.], [0., 1., 0., 1.]]; let y: Array2<f64> = array![[0., 1., 1., 0.]]; let n = x.shape()[1] as f64; let seeds = vec![2, 10, 24, 45, 98, 120, 350, 600, 899, 1000]; let mut runtimes: Vec<u128> = vec![]; // Execute the training with each different seed and time them for seed in seeds { println!("Running with seed: {}", seed); let mut rng: Pcg64 = Pcg64::seed_from_u64(seed); let start = Instant::now(); // Initialize weights and biases // Remember: they have to be initialized to random values in order to break symmetry! // Input to hidden let mut w0: Array2<f64> = Array::random_using((2, 2), Uniform::new(0., 1.), &mut rng); let mut b0: Array2<f64> = Array::random_using((2, 1), Uniform::new(0., 1.), &mut rng); // Hidden to output let mut w1: Array2<f64> = Array::random_using((2, 1), Uniform::new(0., 1.), &mut rng); let mut b1: Array2<f64> = Array::random_using((1, 1), Uniform::new(0., 1.), &mut rng); // Train using gradient descent let epochs = 100000; let alpha = 0.5; for _ in 0..epochs { // Forward propagation let a1 = sigmoid(w0.t().dot(&x) + &b0); let y_hat = sigmoid(w1.t().dot(&a1) + &b1); // Loss (MSE) multiplied by a 1/2 term to make the derivative easier let _loss = (1. / (2. * n)) * ((&y_hat - &y).mapv(|a| a.powi(2))).sum(); // Backpropagation let dy_hat = (&y_hat - &y) / n; let dz2 = (&y_hat * (1. - &y_hat)) * &dy_hat; let dw1 = a1.dot(&dz2.t()); // `ndarray` doesn't provide a way to keep dimensions so we need to reshape let db1 = Array::from_shape_vec((1, 1), dz2.sum_axis(Axis(1)).to_vec()).unwrap(); let dz1 = (&a1 * (1. - &a1)) * (w1.dot(&(&dy_hat * (&y_hat * (1. - &y_hat))))); let dw0 = x.dot(&dz1.t()); let db0 = Array::from_shape_vec((2, 1), dz1.sum_axis(Axis(1)).to_vec()).unwrap(); // Weight and bias update // We average the gradients so that we can use a larger learning rate w0 = &w0 - alpha * (dw0 / n); w1 = &w1 - alpha * (dw1 / n); b0 = &b0 - alpha * (db0 / n); b1 = &b1 - alpha * (db1 / n); } // Record the time runtimes.push(start.elapsed().as_millis()); } // Save runtimes to a file for further processing println!("Saving runtimes to `rust.txt`"); let mut f = File::create("rust.txt").unwrap(); for t in &runtimes { writeln!(f, "{}", t).expect("Failed to write runtime"); } }
40.60241
94
0.551039
4b8073027542ae04e29bf5e4a7081a58e91734a5
823
//! The empty object use sdl2::render::Canvas; use sdl2::video::Window; use drawable::{DrawSettings, Drawable, Position, State}; /// An object that contains nothing and doesn't display anything. /// /// This is not very useful on it's own, but when used together with a [`WithSize`]-wrapper, it /// can act as a breaker in a [`Stack`]. /// /// [`WithSize`]: ../withsize/struct.WithSize.html /// [`Stack`]: ../layout/stack/struct.Stack.html pub struct Empty; impl Drawable for Empty { fn content(&self) -> Vec<&dyn Drawable> { vec![] } fn content_mut(&mut self) -> Vec<&mut dyn Drawable> { vec![] } fn step(&mut self) {} fn state(&self) -> State { State::Hidden } fn draw(&self, _canvas: &mut Canvas<Window>, _position: &Position, _settings: DrawSettings) {} }
24.939394
98
0.62819
ccbf9b61bcc838a76e85290fafad639be6d4db07
2,265
//! this file is part of the pointproofs. //! It defines some misc functions. use pairing::CurveAffine; use pairings::err::ERR_PARAM; use pairings::*; use std::collections::HashSet; use std::hash::Hash; /// checks if a slice/vector constains duplicated elements pub(crate) fn has_unique_elements<T>(iter: T) -> bool where T: IntoIterator, T::Item: Eq + Hash, { let mut uniq = HashSet::new(); iter.into_iter().all(move |x| uniq.insert(x)) } /// This helper computes the sum of product: /// \sum_{i=start}^{end-1} /// param.generator[i]^scarlar_u64[i] /// It tries to use pre-computed data when possible. /// It assumes end - start = n; and the lengths matches. /// It doesnot perform any sanity checks of those conditions. pub(crate) fn pp_sum_of_prod_helper( prover_params: &ProverParams, scalars_u64: &[&[u64; 4]], start: usize, end: usize, ) -> PointproofsG1 { // the second condition `n <= 1024` comes from benchmarking // pre-computation is faster only when the #basis is <1024 if prover_params.precomp.len() == 512 * prover_params.n && prover_params.n <= 1024 { PointproofsG1Affine::sum_of_products_precomp_256( &prover_params.generators[start..end], &scalars_u64, &prover_params.precomp[start * 256..end * 256], ) } else { PointproofsG1Affine::sum_of_products(&prover_params.generators[start..end], &scalars_u64) } } /// Computes prover_params.generator[index] ^ scalars /// Tries to use pre-computated data when possible. pub(crate) fn pp_single_exp_helper( prover_params: &ProverParams, scalar: Fr, index: usize, ) -> PointproofsG1 { if prover_params.precomp.len() == 3 * prover_params.generators.len() { prover_params.generators[index] .mul_precomp_3(scalar, &prover_params.precomp[index * 3..(index + 1) * 3]) } else if prover_params.precomp.len() == 256 * prover_params.generators.len() { prover_params.generators[index].mul_precomp_256( scalar, &prover_params.precomp[index * 256..(index + 1) * 256], ) } else { assert_eq!(prover_params.precomp.len(), 0, "{}", ERR_PARAM); prover_params.generators[index].mul(scalar) } }
34.846154
97
0.659161