text
stringlengths
8
4.13M
fn main() { let x: i32 = 123; // immutable by default let a = [1, 2, 3]; // a: [i32; 3] let b = [0; 20] // b: [i32; 20] let c: (i32, &str) = (1, "Hello"); // tuple println!("The value of x is: {}", x); print_number(x); add_one(2); } fn print_number(x: i32) { println!("x is: {}", x); } fn add_one(x: i32) -> i32 { x + 1 // No semicolon - expression not statement } fn diverges() -> ! { panic!("This function never returns"); } fn if_five(x: i32) { if x == 5 { println!("x equals 5!"); } else { println!("x doesn't equal five..."); } }
pub fn parse(input: &str) -> String { let mut list = (0..256).collect::<Vec<usize>>(); let mut current = 0usize; let mut skip_size = 0usize; let mut lengths: Vec<usize> = input.bytes().map(|value| value as usize).collect(); lengths.extend_from_slice(&[17, 31, 73, 47, 23]); for _ in 0..64 { for length in &lengths[..] { let local_current = current % list.len(); let (indexes, mut values): (Vec<_>, Vec<_>) = list.iter() .enumerate().cycle() .skip(local_current).take(*length) .map(|(idx, item)| (idx, *item)) .unzip(); values.reverse(); for (index, value) in indexes.iter().zip(values) { list[*index] = value; } current += length + skip_size; skip_size += 1; } } let res: Vec<String> = list.chunks(16) .map(|chunk| { let mut iterator = chunk.iter(); let first = *iterator.next().unwrap(); iterator.fold(first, |acc, value| { acc ^ *value }) }).map(|byte| { format!("{:02x}", byte) }).collect(); res.join("") } #[cfg(test)] mod tests { use super::parse; #[test] fn day10_part2_test1() { let input = ""; assert_eq!("a2582a3a0e66e6e86e3812dcb672a272".to_string(), parse(input)); } #[test] fn day10_part2_test2() { let input = "AoC 2017"; assert_eq!("33efeb34ea91902bb2f59c9920caa6cd".to_string(), parse(input)); } #[test] fn day10_part2_test3() { let input = "1,2,3"; assert_eq!("3efbe78a8d82f29979031a4aa0b16a9d".to_string(), parse(input)); } #[test] fn day10_part2_test4() { let input = "1,2,4"; assert_eq!("63960835bcdc130f0b66d7ff4f6a5a8e".to_string(), parse(input)); } }
use std::io; use std::string::String; use std::iter::Iterator; fn main() { println!("Hello, sailor! Give me some numbers."); // read input values println!("What's the base?"); let mut base = String::new(); io::stdin().read_line(&mut base).unwrap(); let base: u32 = base.trim().parse().unwrap(); println!("Okay, so then what's our starting number?"); let mut number = String::new(); io::stdin().read_line(&mut number).unwrap(); number = number.trim().to_string(); let mut cycle = Vec::new(); // A vector to hold all of the cycled numbers cycle.push(number); // Push in our starting value let mut index = 0; loop { let mut sum: u32 = 0; let n = cycle.last().unwrap().clone(); // The last number calculated in the cylce1 let numbers = n.chars(); // Converting the string to a vector of characters for n in numbers { sum += n.to_digit(10).unwrap().pow(base); // Raise each character (as a digit) to our base } if cycle.contains(&sum.to_string()) { // If the sum is already in our cycle, we've looped index = cycle.iter().position(|x| *x == *sum.to_string()).unwrap(); break; } cycle.push(sum.to_string()); // Otherwise, add the unique number to the cycle and keep counting. } let (null, pattern) = cycle.split_at(index); for x in 0..pattern.len() { if x == pattern.len() - 1 { println!("{0} ", pattern[x]); } else { print!("{0}, ", pattern[x]); } } }
use aes::*; use calc_cikey::*; fn main() { let round10_key_raw = [ 0x3f, 0x42, 0x33, 0x7d, 0x08, 0x39, 0x9e, 0xc2, 0x8a, 0x89, 0x96, 0xe5, 0x7c, 0xeb, 0x59, 0x17, ]; let round10_key = GF256::from_u8array(&round10_key_raw).unwrap(); let round_keys = inv_generate_round_keys(&round10_key); for (i, key) in round_keys.iter().enumerate() { let p = format!("round{} key", i); dump_array16(key, &p); } }
use std::collections::BTreeSet; use std::env; use std::fs; use std::io; static PART2: bool = true; fn main() { let input = read_input().unwrap(); let trace_0 = trace_wire(&input.0[..]); let trace_1 = trace_wire(&input.1[..]); if PART2 { let intersections: BTreeSet<Position> = find_intersections(&trace_0, &trace_1).into_iter().collect(); dbg!(trace_0.len()); dbg!(trace_1.len()); let mut best: i32 = 1000000; for (i0, p0) in trace_0.iter().enumerate() { if !intersections.contains(&p0) || i0 == 0 { continue } for (i1, p1) in trace_1.iter().enumerate() { if p0 == p1 { best = std::cmp::min((i0 + i1) as i32, best); } } } println!("Result: {}", best); } else { let mut intersections = find_intersections(&trace_0, &trace_1); intersections.sort_by(|p1, p2| p1.distance_from_origin().cmp(&p2.distance_from_origin())); intersections.remove(0); // always (0, 0) println!("Result: {}", intersections[0].distance_from_origin()); } } #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] struct Position { x: i32, y: i32, } impl Position { fn new(x: i32, y: i32) -> Position { Position { x, y } } fn distance_from_origin(&self) -> i32 { self.x.abs() + self.y.abs() } } #[derive(Clone, Debug, PartialEq)] enum Direction { Left, Right, Up, Down } #[derive(Clone, Debug, PartialEq)] struct Move { direction: Direction, length: i32 } impl Move { fn new(dir: Direction, len: i32) -> Move { Move { direction: dir, length: len } } } fn parse_move(data: &str) -> Result<Move, &'static str> { let dir = match data.chars().nth(0) { Some('L') => Direction::Left, Some('R') => Direction::Right, Some('U') => Direction::Up, Some('D') => Direction::Down, _ => Err("Failed to parse move")? }; let len = data[1..].parse::<i32>().map_err(|_| "Failed to parse int")?; Ok(Move::new(dir, len)) } #[test] fn test_parse_move() { assert_eq!(parse_move("L10").unwrap(), Move::new(Direction::Left, 10)); assert_eq!(parse_move("R10").unwrap(), Move::new(Direction::Right, 10)); assert_eq!(parse_move("U10").unwrap(), Move::new(Direction::Up, 10)); assert_eq!(parse_move("D10").unwrap(), Move::new(Direction::Down, 10)); } fn parse_line(data: &str) -> Result<Vec<Move>, &'static str> { data.split(",").map(parse_move).collect::<Result<Vec<Move>, &'static str>>() } #[test] fn test_parse_line() -> Result<(), &'static str> { let expected_result = vec!( Move::new(Direction::Left, 10), Move::new(Direction::Right, 5), Move::new(Direction::Up, 7), Move::new(Direction::Down, 111)); assert_eq!(expected_result, parse_line("L10,R5,U7,D111")?); Ok(()) } fn read_input() -> io::Result<(Vec<Move>, Vec<Move>)> { let input_path: &String = &env::args().nth(1).unwrap(); let input_data = fs::read_to_string(input_path)?; let input_lines = input_data.lines().map(parse_line).collect::<Result<Vec<Vec<Move>>, &'static str>>().unwrap(); Ok((input_lines[0].clone(), input_lines[1].clone())) } fn trace_wire(moves: &[Move]) -> Vec<Position> { let mut current_position = Position::new(0, 0); let mut result: Vec<Position> = Vec::new(); result.push(current_position.clone()); for m in moves.iter() { for _ in 0..m.length { match m.direction { Direction::Up => current_position.y = current_position.y + 1, Direction::Down => current_position.y = current_position.y - 1, Direction::Left => current_position.x = current_position.x - 1, Direction::Right => current_position.x = current_position.x + 1, }; result.push(current_position.clone()); } } result } #[test] fn test_trace_wire() { let input = vec!(Move::new(Direction::Right, 3)); let result = trace_wire(&input[..]); let mut expected_result = Vec::new(); expected_result.push(Position::new(0, 0)); expected_result.push(Position::new(1, 0)); expected_result.push(Position::new(2, 0)); expected_result.push(Position::new(3, 0)); assert_eq!(result, expected_result); let input = vec!(Move::new(Direction::Right, 3), Move::new(Direction::Up, 1)); let result = trace_wire(&input[..]); let mut expected_result = Vec::new(); expected_result.push(Position::new(0, 0)); expected_result.push(Position::new(1, 0)); expected_result.push(Position::new(2, 0)); expected_result.push(Position::new(3, 0)); expected_result.push(Position::new(3, 1)); assert_eq!(result, expected_result); } fn find_intersections(trace0: &Vec<Position>, trace1: &Vec<Position>) -> Vec<Position> { let trace0: BTreeSet<Position> = trace0.iter().cloned().collect(); let trace1: BTreeSet<Position> = trace1.iter().cloned().collect(); trace0.intersection(&trace1).cloned().collect() }
use std::clone::Clone; use crate::ast::expressions::operators; use crate::ast::lexer::tokens::Keyword; use crate::interpreter::{self, environment, types}; use crate::utils; impl interpreter::Eval for operators::Unop { // unop ::= β€˜-’ | not | β€˜#’ | β€˜~’ // Keyword::MINUS, Keyword::NOT, Keyword::HASH, Keyword::TILDA fn eval(&self, env: &mut utils::Shared<environment::Environment>) -> types::Type { let value = self.1.eval(env); // Keyword match self.0 { Keyword::MINUS => match_type!(&value, types::Type::Number(number) => types::Type::Number(-number), types::Type::Table { ref metatable, .. } => { if let Some(metamethod) = metatable.get("__unm") { metamethod.call(vec![&value]) } else { self.runtime_error(format!("{:?} metatable doesn't contain `__unm` function", value)) } }, _ => self.runtime_error(format!("Can't negate {:?} value", value)) ), Keyword::NOT => types::Type::Boolean(!value.as_bool()), Keyword::HASH => match_type!(&value, types::Type::String(string) => types::Type::Number(string.as_bytes().len() as f64), types::Type::Table { border, ref metatable, .. } => { if let Some(metamethod) = metatable.get("__len") { metamethod.call(vec![&value]) } else { types::Type::Number(*border as f64) } }, _ => { self.runtime_error(format!("Can't get length of {:?} value", value)); } ), Keyword::TILDA => match_type!(&value, types::Type::Number(number) => types::Type::Number(!(*number as i64) as f64), _ => self.runtime_error(format!("Can't apply bitwise not to {:?} value", value)) ), _ => panic!("Should never happen"), } } } fn eval_ariphmetic( exp: &dyn interpreter::Eval, op: &Keyword, left: types::Type, right: types::Type, ) -> types::Type { // Function to convert value for arithmetic operation let normalize = |value, op| -> f64 { match_type!(&value, types::Type::Number(number) => *number, types::Type::String(string) => { if let Ok(number) = string.parse::<f64>() { number } else { exp.runtime_error(format!("Can't convert string {:?} to apply {} operator", string, op)) } }, _ => exp.runtime_error(format!("Can't apply {} operator to {:?} value", op, value)) ) }; macro_rules! metatable_binop { ($mt_key: tt, $op: tt, $function: expr) => {{ // TODO: unref table if let types::Type::Table { ref metatable, .. } = left { if let Some(metamethod) = metatable.get($mt_key) { return metamethod.call(vec![&left, &right]); } } return types::Type::Number($function(normalize(left, $op), normalize(right, $op))); }}; } match op { Keyword::PLUS => metatable_binop!("__add", "+", |left, right| left + right), Keyword::MINUS => metatable_binop!("__sub", "-", |left, right| left - right), Keyword::MUL => metatable_binop!("__mul", "*", |left, right| left * right), Keyword::DIV => metatable_binop!("__div", "/", |left, right| left / right), Keyword::FLOORDIV => metatable_binop!("__idiv", "//", |left: f64, right: f64| (left / right) .floor()), Keyword::MOD => metatable_binop!("__mod", "%", |left: f64, right: f64| left % right), Keyword::POW => metatable_binop!("__pow", "^", |left: f64, right: f64| left.powf(right)), _ => panic!("Should never happen"), } } fn eval_equivalence( exp: &dyn interpreter::Eval, op: &Keyword, left: types::Type, right: types::Type, ) -> types::Type { fn not(value: types::Type) -> types::Type { types::Type::Boolean(!value.as_bool()) } match_type!((&left, &right), (types::Type::Number(leftnum), types::Type::Number(rightnum)) => { match op { Keyword::LESS => types::Type::Boolean(leftnum < rightnum), Keyword::LEQ => types::Type::Boolean(leftnum <= rightnum), Keyword::GREATER => types::Type::Boolean(leftnum > rightnum), Keyword::GEQ => types::Type::Boolean(leftnum >= rightnum), Keyword::EQ => types::Type::Boolean((leftnum - rightnum).abs() <= std::f64::EPSILON), Keyword::NEQ => types::Type::Boolean((leftnum - rightnum).abs() > std::f64::EPSILON), _ => panic!("Should never happen") } }, (types::Type::String(leftnum), types::Type::String(rightnum)) => { match op { Keyword::LESS => types::Type::Boolean(leftnum < rightnum), Keyword::LEQ => types::Type::Boolean(leftnum <= rightnum), Keyword::GREATER => types::Type::Boolean(leftnum > rightnum), Keyword::GEQ => types::Type::Boolean(leftnum >= rightnum), Keyword::EQ => types::Type::Boolean(leftnum == rightnum), Keyword::NEQ => types::Type::Boolean(leftnum != rightnum), _ => panic!("Should never happen") } }, (types::Type::Table { ref metatable, .. }, _) => { macro_rules! metatable_binop { ($mt_key: tt, $op: tt) => { if let Some(metamethod) = metatable.get($mt_key) { metamethod.call(vec![&left, &right]) } else { exp.runtime_error(format!("Can't compare values {:?} and {:?} with {} operator", &left, &right, $op)) } } } match op { Keyword::LESS => metatable_binop!("__lt", "<"), Keyword::LEQ => metatable_binop!("__le", "<="), Keyword::GREATER => not(metatable_binop!("__le", ">")), Keyword::GEQ => not(metatable_binop!("__lt", ">=")), Keyword::EQ => metatable_binop!("__eq", "=="), Keyword::NEQ => not(metatable_binop!("__eq", "~=")), _ => panic!("Should never happen") } }, // TODO: Function comparison not implemented _ => types::Type::Boolean(false) ) } fn eval_bitwise( exp: &dyn interpreter::Eval, op: &Keyword, left: types::Type, right: types::Type, ) -> types::Type { macro_rules! metatable_binop { ($mt_key: tt, $op: tt, $function: expr) => ({ match_type!(&left, types::Type::Table { ref metatable, .. } => { if let Some(metamethod) = metatable.get($mt_key) { return metamethod.call(vec![&left, &right]) } }, _ => () ); match_type!((&left, &right), (types::Type::Number(leftnum), types::Type::Number(rightnum)) => { return types::Type::Number($function(*leftnum as i64, *rightnum as i64) as f64) }, _ => exp.runtime_error(format!("Bitwise operator can be applied only to numbers. Got {:?} and {:?}", left, right)) ) }) } match op { Keyword::SOR => metatable_binop!("__bor", "+", |left, right| left | right), Keyword::SAND => metatable_binop!("__band", "-", |left, right| left & right), Keyword::TILDA => metatable_binop!("__bxor", "-", |left, right| left ^ right), Keyword::SHRIGHT => metatable_binop!("__bshr", "*", |left, right| left >> right), Keyword::SHLEFT => metatable_binop!("__bshl", "/", |left, right| left << right), _ => panic!("Should never happen"), } } // TODO. `or` Lazy evaluation fn eval_boolean( _exp: &operators::Binop, op: &Keyword, left: types::Type, right: types::Type, ) -> types::Type { types::Type::Boolean(match op { Keyword::OR => left.as_bool() || right.as_bool(), Keyword::AND => left.as_bool() && right.as_bool(), _ => panic!("Should never happen"), }) } fn eval_concat( exp: &dyn interpreter::Eval, _op: &Keyword, left: types::Type, right: types::Type, ) -> types::Type { fn to_string(value: &types::Type) -> Option<String> { match_type!(value, types::Type::Number(num) => Some(num.to_string()), types::Type::String(str) => Some(str.clone()), _ => None ) } if let (Some(mut leftstr), Some(rightstr)) = (to_string(&left), to_string(&right)) { leftstr.push_str(rightstr.as_str()); types::Type::String(leftstr) } else if let types::Type::Table { ref metatable, .. } = left { if let Some(metamethod) = metatable.get("__concat") { metamethod.call(vec![&left, &right]) } else { exp.runtime_error(format!( "{:?} metatable doesn't contain `__concat` function", left )) } } else { exp.runtime_error(format!( "Concat operator can be applied only to strings, numbers or table. Got {:?} and {:?}", left, right )) } } impl interpreter::Eval for operators::Binop { // β€˜+’ | β€˜-’ | β€˜*’ | β€˜/’ | β€˜//’ | β€˜^’ | β€˜%’ | // β€˜&’ | β€˜~’ | β€˜|’ | β€˜>>’ | β€˜<<’ | β€˜..’ | // β€˜<’ | β€˜<=’ | β€˜>’ | β€˜>=’ | β€˜==’ | β€˜~=’ | // and | or // [Keyword::OR], // [Keyword::AND], // [ // Keyword::LESS, // Keyword::LEQ, // Keyword::GREATER, // Keyword::GEQ, // Keyword::EQ, // Keyword::NEQ // ], // [Keyword::SOR], // [Keyword::TILDA], // [Keyword::SAND], // [Keyword::SHRIGHT, Keyword::SHLEFT], // [Keyword::DOT2], // [Keyword::PLUS, Keyword::MINUS], // [Keyword::MUL, Keyword::DIV, Keyword::FLOOR_DIV, Keyword::MOD], // [Keyword::POW] fn eval(&self, env: &mut utils::Shared<environment::Environment>) -> types::Type { let operators::Binop(op, left, right) = self; let left_value = left.eval(env); // TODO: Lazy evaluation!!! let right_value = right.eval(env); match op { Keyword::PLUS | Keyword::MINUS | Keyword::MUL | Keyword::DIV | Keyword::FLOORDIV | Keyword::MOD | Keyword::POW => eval_ariphmetic(self, op, left_value, right_value), Keyword::OR | Keyword::AND => eval_boolean(self, op, left_value, right_value), Keyword::LESS | Keyword::LEQ | Keyword::GREATER | Keyword::GEQ | Keyword::EQ | Keyword::NEQ => eval_equivalence(self, op, left_value, right_value), Keyword::SOR | Keyword::TILDA | Keyword::SAND | Keyword::SHRIGHT | Keyword::SHLEFT => { eval_bitwise(self, op, left_value, right_value) } Keyword::DOT2 => eval_concat(self, op, left_value, right_value), _ => panic!("Should never happen"), } } } impl interpreter::Eval for operators::Noop { fn eval(&self, _env: &mut utils::Shared<environment::Environment>) -> types::Type { types::Type::Nil } }
use rust_signpost::*; fn main() { declare_signpost(0x100); println!("declared signpost!"); std::thread::park_timeout(std::time::Duration::from_secs(10)); start_signpost(0x100); println!("started signpost!"); std::thread::park_timeout(std::time::Duration::from_secs(10)); end_signpost(0x100); println!("ended signpost!"); std::thread::park_timeout(std::time::Duration::from_secs(10)); println!("adios!"); }
extern crate nalgebra as na; use na::{Vector2, Point2}; use ncollide2d::pipeline::CollisionGroups; use ncollide2d::shape::{Cuboid, ShapeHandle}; use nphysics2d::force_generator::{DefaultForceGeneratorSet, ForceGenerator}; use nphysics2d::joint::DefaultJointConstraintSet; use nphysics2d::joint::{PrismaticConstraint, RevoluteConstraint}; use nphysics2d::math::{Force, ForceType, Velocity}; use nphysics2d::object::{Body, BodyPartHandle, BodyStatus, ColliderDesc, DefaultBodySet, DefaultColliderSet, Ground, RigidBodyDesc}; use nphysics2d::solver::IntegrationParameters; use nphysics2d::world::{DefaultMechanicalWorld, DefaultGeometricalWorld}; use nphysics_testbed2d::Testbed; pub fn init_world(testbed: &mut Testbed) { // World let mut mechanical_world = DefaultMechanicalWorld::new(Vector2::new(0.0, -9.81)); let mut geometrical_world = DefaultGeometricalWorld::new(); let mut bodies = DefaultBodySet::new(); let mut colliders = DefaultColliderSet::new(); let mut joint_constraints = DefaultJointConstraintSet::new(); let force_generators = DefaultForceGeneratorSet::new(); // Collision group for the cart and the pole const CART_GROUP_ID: usize = 0; const POLE_GROUP_ID: usize = 1; let mut cart_group = CollisionGroups::new(); cart_group.set_membership(&[CART_GROUP_ID]); cart_group.set_whitelist(&[CART_GROUP_ID]); let mut pole_group = CollisionGroups::new(); pole_group.set_membership(&[POLE_GROUP_ID]); pole_group.set_whitelist(&[POLE_GROUP_ID]); // Ground let ground_size = 25.0; let ground_shape = ShapeHandle::new(Cuboid::new(Vector2::new(ground_size, 1.0))); let ground_handle = bodies.insert(Ground::new()); let co = ColliderDesc::new(ground_shape) .collision_groups(cart_group) .translation(Vector2::y() * -2.0) .build(BodyPartHandle(ground_handle, 0)); colliders.insert(co); let geometry = ShapeHandle::new(Cuboid::new(Vector2::new(1.0, 0.5))); let collider_desc = ColliderDesc::new(geometry).density(1.0); let mut parent = BodyPartHandle(ground_handle, 0); let first_anchor = Point2::new(0.0, 1.0); let other_anchor = Point2::new(0.0, 2.0); let mut translation = first_anchor.coords; for j in 0usize..3 { let rb = RigidBodyDesc::new().translation(translation).build(); let rb_handle = bodies.insert(rb); let co = collider_desc.build(BodyPartHandle(rb_handle, 0)); colliders.insert(co); let mut prismatic_constraint = PrismaticConstraint::new( parent, BodyPartHandle(rb_handle, 0), if j == 0 { first_anchor } else { other_anchor }, Vector2::x_axis(), Point2::origin(), ); //prismatic_constraint.enable_min_offset(-rad * 0.2); joint_constraints.insert(prismatic_constraint); translation += other_anchor.coords; parent = BodyPartHandle(rb_handle, 0); } //testbed.add_callback(move |_, _, bodies, _, _, _| { // let force = Force::linear(Vector2::new(0.0, 10.0)); //}); // Run the simulation. testbed.set_ground_handle(Some(ground_handle)); testbed.set_world( mechanical_world, geometrical_world, bodies, colliders, joint_constraints, force_generators, ); testbed.look_at(Point2::new(0.0, 0.0), 50.0); } fn main() { let testbed = Testbed::from_builders(0, vec![("Kinematic body", init_world)]); testbed.run(); }
#[derive(Clone, PartialEq, ::prost::Message)] pub struct PidProto { #[prost(bytes, tag="1")] pub pid: std::vec::Vec<u8>, } /// List of created/deleted process ids #[derive(Clone, PartialEq, ::prost::Message)] pub struct ProcessList { #[prost(bytes, tag="2")] pub newids: std::vec::Vec<u8>, #[prost(bytes, tag="3")] pub delids: std::vec::Vec<u8>, } use quix::derive::*; use quix::derive::*; pub struct Update(pub ProcessList); pub trait UpdateAddr { fn update(&self, arg: ProcessList) -> BoxFuture<'static, ()>; } impl<A> UpdateAddr for Pid<A> where A: Handler<Update> + DynHandler { fn update(&self, arg: ProcessList) -> BoxFuture<'static, ()> { Box::pin(self.send(Update(arg)).map(|r| r.and_then(|r|r) )) } } impl UpdateAddr for PidRecipient<Update> { fn update(&self, arg: ProcessList) -> BoxFuture<'static, ()> { Box::pin(self.send(Update(arg)).map(|r| r.and_then(|r|r) )) } } impl UpdateAddr for NodeId { fn update(&self, arg: ProcessList) ->BoxFuture<'static, ()> { Box::pin(self.send(Update(arg))) } } impl actix::Message for Update { type Result = (); } impl quix::derive::RpcMethod for Update { const NAME: &'static str = "quix.process.Process.update"; const ID: u32 = 520454116; fn write(&self, b: &mut impl bytes::BufMut) -> Result<(), DispatchError> { prost::Message::encode(&self.0, b).map_err(|_| DispatchError::MessageFormat) } fn read(b: impl bytes::Buf) -> Result<Self, DispatchError> { Ok(Self(prost::Message::decode(b).map_err(|_| DispatchError::MessageFormat)?)) } fn read_result(b: impl bytes::Buf) -> Self::Result { () } fn write_result(res: &Self::Result, b: &mut impl bytes::BufMut) -> Result<(), DispatchError> { (); Ok(()) } } impl From<ProcessList> for Update { fn from(a: ProcessList) -> Self { Self(a) } } impl Into<ProcessList> for Update { fn into(self) -> ProcessList { self.0 } } impl ::core::ops::Deref for Update { type Target = ProcessList; fn deref(&self) -> &Self::Target { &self.0 } } impl ::core::ops::DerefMut for Update { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
mod containers; // TODO make these private. pub mod dependencies; pub mod importgraph; pub mod layers; use crate::dependencies::PackageDependency; use containers::check_containers_exist; use importgraph::ImportGraph; use layers::Level; use log::info; use pyo3::create_exception; use pyo3::prelude::*; use pyo3::types::{PyDict, PyFrozenSet, PySet, PyString, PyTuple}; use std::collections::HashSet; #[pymodule] fn _rustgrimp(_py: Python, m: &PyModule) -> PyResult<()> { pyo3_log::init(); m.add_function(wrap_pyfunction!(find_illegal_dependencies, m)?)?; m.add("NoSuchContainer", _py.get_type::<NoSuchContainer>())?; Ok(()) } create_exception!(_rustgrimp, NoSuchContainer, pyo3::exceptions::PyException); #[pyfunction] pub fn find_illegal_dependencies<'a>( py: Python<'a>, levels: &'a PyTuple, containers: &'a PySet, importeds_by_importer: &'a PyDict, ) -> PyResult<&'a PyTuple> { info!("Using Rust to find illegal dependencies."); let graph = ImportGraph::new(importeds_by_importer.extract()?); let levels_rust = rustify_levels(levels); let containers_rust: HashSet<&str> = containers.extract()?; if let Err(err) = check_containers_exist(&graph, &containers_rust) { return Err(NoSuchContainer::new_err(err)); } let dependencies = layers::find_illegal_dependencies(&graph, &levels_rust, &containers_rust); convert_dependencies_to_python(py, dependencies, &graph) } fn rustify_levels(levels_python: &PyTuple) -> Vec<Level> { let mut rust_levels: Vec<Level> = vec![]; for level_python in levels_python.into_iter() { let layers: HashSet<&str> = level_python.extract().unwrap(); rust_levels.push(Level { layers: layers.into_iter().collect(), }); } rust_levels } fn convert_dependencies_to_python<'a>( py: Python<'a>, dependencies: Vec<PackageDependency>, graph: &ImportGraph, ) -> PyResult<&'a PyTuple> { let mut python_dependencies: Vec<&PyDict> = vec![]; for rust_dependency in dependencies { let python_dependency = PyDict::new(py); python_dependency.set_item("imported", graph.names_by_id[&rust_dependency.imported])?; python_dependency.set_item("importer", graph.names_by_id[&rust_dependency.importer])?; let mut python_routes: Vec<&PyDict> = vec![]; for rust_route in rust_dependency.routes { let route = PyDict::new(py); let heads: Vec<&PyString> = rust_route .heads .iter() .map(|i| PyString::new(py, graph.names_by_id[&i])) .collect(); route.set_item("heads", PyFrozenSet::new(py, &heads)?)?; let middle: Vec<&PyString> = rust_route .middle .iter() .map(|i| PyString::new(py, graph.names_by_id[&i])) .collect(); route.set_item("middle", PyTuple::new(py, &middle))?; let tails: Vec<&PyString> = rust_route .tails .iter() .map(|i| PyString::new(py, graph.names_by_id[&i])) .collect(); route.set_item("tails", PyFrozenSet::new(py, &tails)?)?; python_routes.push(route); } python_dependency.set_item("routes", PyTuple::new(py, python_routes))?; python_dependencies.push(python_dependency) } Ok(PyTuple::new(py, python_dependencies)) } #[cfg(test)] mod tests { use super::*; use pyo3::types::{PySet, PyTuple}; #[test] fn test_rustify_levels_no_sibling_layers() { pyo3::prepare_freethreaded_python(); Python::with_gil(|py| -> PyResult<()> { let elements: Vec<&PySet> = vec![ PySet::new(py, &vec!["high"]).unwrap(), PySet::new(py, &vec!["medium"]).unwrap(), PySet::new(py, &vec!["low"]).unwrap(), ]; let python_levels: &PyTuple = PyTuple::new(py, elements); let result = rustify_levels(python_levels); assert_eq!( result, vec![ Level { layers: vec!["high"] }, Level { layers: vec!["medium"] }, Level { layers: vec!["low"] } ] ); Ok(()) }) .unwrap(); } #[test] fn test_rustify_levels_sibling_layers() { pyo3::prepare_freethreaded_python(); Python::with_gil(|py| -> PyResult<()> { let elements: Vec<&PySet> = vec![ PySet::new(py, &vec!["high"]).unwrap(), PySet::new(py, &vec!["blue", "green", "orange"]).unwrap(), PySet::new(py, &vec!["low"]).unwrap(), ]; let python_levels: &PyTuple = PyTuple::new(py, elements); let mut result = rustify_levels(python_levels); for level in &mut result { level.layers.sort(); } assert_eq!( result, vec![ Level { layers: vec!["high"] }, Level { layers: vec!["blue", "green", "orange"] }, Level { layers: vec!["low"] } ] ); Ok(()) }) .unwrap(); } }
use bevy::prelude::*; use bevy::render::texture::{Extent3d, TextureDimension, TextureFormat}; use rand::seq::SliceRandom; use rand::Rng; use std::cell::RefCell; use std::ops::DerefMut; static WINDOW_SIZE: f32 = 1000.0; static BOARD_SIZE: usize = 100; static BOARD_SIZE_F32: f32 = BOARD_SIZE as f32; thread_local! { // unstable library feature 'thread_id_value', tracking issue #67939 static RNG: RefCell<rand::rngs::SmallRng> = RefCell::new(rand::SeedableRng::seed_from_u64(0 /*std::thread::current().id().as_u64()*/ )); } fn main() { App::build() .insert_resource(WindowDescriptor { title: "Game".to_string(), width: WINDOW_SIZE, height: WINDOW_SIZE, vsync: true, resizable: false, ..Default::default() }) .add_plugins(DefaultPlugins) .add_plugin(PowderPlugin) .add_plugin(bevy::diagnostic::FrameTimeDiagnosticsPlugin::default()) .add_plugin(bevy::diagnostic::LogDiagnosticsPlugin::default()) .run(); } #[derive(Default)] pub struct PowderPlugin; #[derive(Clone, PartialEq, Eq)] pub enum Material { NONE, SAND, OXYGEN, } #[derive(Clone, PartialEq, Eq)] pub struct Particle { pub material: Material, pub index: usize, } #[derive(Clone)] pub struct PowderData { pub texture: Handle<Texture>, pub particles: Vec<Particle>, pub index_particle_id_map: Vec<Option<usize>>, } impl Default for PowderData { fn default() -> Self { let mut particles = Vec::new(); let mut index_particle_id_map = Vec::new(); for i in 0..BOARD_SIZE * BOARD_SIZE / 4 { if i % 7 == 0 { let index = index_particle_id_map.len(); index_particle_id_map.push(Some(particles.len())); particles.push(Particle { material: Material::OXYGEN, index, }); } else { index_particle_id_map.push(None); } } for _ in 0..BOARD_SIZE * BOARD_SIZE / 4 { let index = index_particle_id_map.len(); index_particle_id_map.push(Some(particles.len())); particles.push(Particle { material: Material::SAND, index, }); } for i in 0..BOARD_SIZE * BOARD_SIZE / 2 { if i % 7 == 0 { let index = index_particle_id_map.len(); index_particle_id_map.push(Some(particles.len())); particles.push(Particle { material: Material::OXYGEN, index, }); } else { index_particle_id_map.push(None); } } debug_assert_eq!(index_particle_id_map.len(), BOARD_SIZE * BOARD_SIZE); Self { particles, index_particle_id_map, texture: Default::default(), } } } fn simulate(mut powder_data: ResMut<PowderData>, mut textures: ResMut<Assets<Texture>>) { let len = powder_data.index_particle_id_map.len(); let mut order: Vec<_> = (0..powder_data.particles.len()).collect(); random_shuffle(&mut order); let order = order; // Update particles for &particle_id in &order { let particle = powder_data.particles[particle_id].clone(); let neighbor_index_above = if particle.index / BOARD_SIZE > 0 { Some(particle.index - BOARD_SIZE) } else { None }; let neighbor_index_below = if particle.index / BOARD_SIZE < BOARD_SIZE - 1 { Some(particle.index + BOARD_SIZE) } else { None }; let neighbor_index_left = if particle.index % BOARD_SIZE > 0 { Some(particle.index - 1) } else { None }; let neighbor_index_right = if particle.index % BOARD_SIZE < BOARD_SIZE - 1 { Some(particle.index + 1) } else { None }; let neighbor_index_left_below = if neighbor_index_left.is_some() && neighbor_index_below.is_some() { Some(particle.index - 1 + BOARD_SIZE) } else { None }; let neighbor_index_right_below = if neighbor_index_right.is_some() && neighbor_index_below.is_some() { Some(particle.index + 1 + BOARD_SIZE) } else { None }; let mut neighbor_indexes: Vec<usize> = Vec::new(); neighbor_indexes.extend(neighbor_index_above.iter()); neighbor_indexes.extend(neighbor_index_below.iter()); neighbor_indexes.extend(neighbor_index_left.iter()); neighbor_indexes.extend(neighbor_index_right.iter()); debug_assert!( neighbor_indexes.iter().all(|&neighbor| neighbor < len), "{:?}", neighbor_indexes ); let neighbor_indexes = neighbor_indexes; let mut slide_neighbor_indexes: Vec<usize> = Vec::new(); slide_neighbor_indexes.extend(neighbor_index_left_below.iter()); slide_neighbor_indexes.extend(neighbor_index_right_below.iter()); let slide_neighbor_indexes = slide_neighbor_indexes; if random_bool(particle.material.dissipation_probability()) { // Dissipation if let Some(&neighbor_index) = random_choice(&neighbor_indexes) { let neighbor_particle_id = powder_data.index_particle_id_map[neighbor_index]; if neighbor_particle_id .map(|id| powder_data.particles[id].material.is_gas()) .unwrap_or(true) { let PowderData { particles, index_particle_id_map, .. } = &mut *powder_data; swap_indices( particles, index_particle_id_map, particle.index, neighbor_index, ); } } } else if random_bool(particle.material.gravity_probability()) { // Gravity if let Some(&neighbor_index_below) = neighbor_index_below.as_ref() { let neighbor_particle_id = powder_data.index_particle_id_map[neighbor_index_below]; if neighbor_particle_id .map(|id| powder_data.particles[id].material.is_gas()) .unwrap_or(true) { let PowderData { particles, index_particle_id_map, .. } = &mut *powder_data; swap_indices( particles, index_particle_id_map, particle.index, neighbor_index_below, ); } } } else if random_bool(particle.material.slide_probability()) { // Slide if let Some(&slide_neighbor_index) = random_choice(&slide_neighbor_indexes) { let slide_neighbor_particle_id = powder_data.index_particle_id_map[slide_neighbor_index]; if slide_neighbor_particle_id.map(|id| powder_data.particles[id].material.is_gas()).unwrap_or(true) { let PowderData { particles, index_particle_id_map, .. } = &mut *powder_data; swap_indices( particles, index_particle_id_map, particle.index, slide_neighbor_index, ); } } } } #[cfg(debug)] powder_data.verify(); // Render let texture = textures.get_mut(powder_data.texture.clone()).unwrap(); for index in 0..len { set_pixel_color_index(texture, index, &Material::NONE.color()); } for particle in &powder_data.particles { set_pixel_color_index(texture, particle.index, &particle.material.color()); } } fn set_pixel_rgb_index(texture: &mut Texture, index: usize, r: u8, g: u8, b: u8) { debug_assert_eq!(texture.format, TextureFormat::Rgba8UnormSrgb); // let index = 4 * (x + y * texture.size.width as usize); let index = index * 4; texture.data[index] = r; texture.data[index + 1] = g; texture.data[index + 2] = b; } fn set_pixel_color_index(texture: &mut Texture, index: usize, color: &Color) { set_pixel_rgb_index(texture, index, color.r, color.g, color.b) } fn random_bool(probability: f64) -> bool { RNG.with(|rng| rng.borrow_mut().gen_bool(probability)) } fn random_choice<T>(slice: &[T]) -> Option<&T> { RNG.with(|rng| slice.choose(rng.borrow_mut().deref_mut())) } fn random_shuffle<T>(slice: &mut [T]) { RNG.with(|rng| slice.shuffle(rng.borrow_mut().deref_mut())) } fn swap_indices( particles: &mut Vec<Particle>, index_particle_id_map: &mut Vec<Option<usize>>, mut i: usize, mut j: usize, ) { debug_assert_ne!(i, j); if index_particle_id_map[i].is_some() && index_particle_id_map[j].is_some() { debug_assert_ne!(index_particle_id_map[i], index_particle_id_map[j]); index_particle_id_map.swap(i, j); let index_i = particles[index_particle_id_map[i].unwrap()].index; let index_j = particles[index_particle_id_map[j].unwrap()].index; particles[index_particle_id_map[i].unwrap()].index = index_j; particles[index_particle_id_map[j].unwrap()].index = index_i; } else if index_particle_id_map[i].is_some() || index_particle_id_map[j].is_some() { if index_particle_id_map[i].is_none() { std::mem::swap(&mut i, &mut j); } // now i is Some and j is None particles[index_particle_id_map[i].unwrap()].index = j; index_particle_id_map[j] = index_particle_id_map[i]; index_particle_id_map[i] = None; } } impl Material { fn color(&self) -> Color { match self { Material::NONE => Color::new(0, 0, 0), Material::SAND => Color::new(251, 252, 210), Material::OXYGEN => Color::new(232, 248, 255), } } fn gravity_probability(&self) -> f64 { match self { Material::NONE => 0.0, Material::SAND => 0.2, Material::OXYGEN => 1e-3, } } fn dissipation_probability(&self) -> f64 { match self { Material::NONE => 0.0, Material::SAND => 0.0, Material::OXYGEN => 0.9, } } fn slide_probability(&self) -> f64 { match self { Material::NONE => 0.0, Material::SAND => 0.2, Material::OXYGEN => 0.0, } } fn is_solid(&self) -> bool { match self { Material::NONE => false, Material::SAND => true, Material::OXYGEN => false, } } fn is_liquid(&self) -> bool { match self { Material::NONE => false, Material::SAND => false, Material::OXYGEN => false, } } fn is_gas(&self) -> bool { match self { Material::NONE => false, Material::SAND => false, Material::OXYGEN => true, } } } impl Plugin for PowderPlugin { fn build(&self, app: &mut AppBuilder) { app.insert_resource(PowderData::default()); app.add_startup_system(powder_plugin_setup.system()); app.add_system(simulate.system()); } } fn powder_plugin_setup( mut commands: Commands, mut textures: ResMut<Assets<Texture>>, mut powder_data: ResMut<PowderData>, mut materials: ResMut<Assets<ColorMaterial>>, ) { powder_data.texture = textures.add(Texture::new_fill( Extent3d::new(BOARD_SIZE as u32, BOARD_SIZE as u32, 1), TextureDimension::D2, &[0, 0, 0, 255], TextureFormat::Rgba8UnormSrgb, )); println!( "Texture data len is {}", textures .get(powder_data.texture.clone()) .unwrap() .data .len() ); commands.spawn_bundle(OrthographicCameraBundle::new_2d()); commands.spawn_bundle(SpriteBundle { material: materials.add(powder_data.texture.clone().into()), transform: Transform::from_scale(Vec3::new( WINDOW_SIZE / BOARD_SIZE_F32, WINDOW_SIZE / BOARD_SIZE_F32, 0.0, )), ..Default::default() }); } struct Color { pub r: u8, pub g: u8, pub b: u8, } impl Color { fn new(r: u8, g: u8, b: u8) -> Self { Self { r, g, b } } } impl PowderData { fn verify(&self) { for (index, id) in self.index_particle_id_map.iter().enumerate() { if let Some(&id) = id.as_ref() { debug_assert_eq!(index, self.particles[id].index); } } for (id, particle) in self.particles.iter().enumerate() { debug_assert_eq!(Some(id), self.index_particle_id_map[particle.index]); } } }
use crate::node; pub struct TextStyleBuilder(Vec<String>); impl TextStyleBuilder { pub fn from(content: String) -> Self { TextStyleBuilder(vec![content]) } } impl TextStyleBuilder { pub fn append(&mut self, content: String) { self.0.push(content); } pub fn build(self) -> node::TextStyle { unimplemented!() } }
#[doc = "Register `C2IMR2` reader"] pub type R = crate::R<C2IMR2_SPEC>; #[doc = "Register `C2IMR2` writer"] pub type W = crate::W<C2IMR2_SPEC>; #[doc = "Field `DMA1_CH1_IM` reader - Peripheral DMA1 CH1 interrupt mask to CPU2"] pub type DMA1_CH1_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH1_IM` writer - Peripheral DMA1 CH1 interrupt mask to CPU2"] pub type DMA1_CH1_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH2_IM` reader - Peripheral DMA1 CH2 interrupt mask to CPU2"] pub type DMA1_CH2_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH2_IM` writer - Peripheral DMA1 CH2 interrupt mask to CPU2"] pub type DMA1_CH2_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH3_IM` reader - Peripheral DMA1 CH3 interrupt mask to CPU2"] pub type DMA1_CH3_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH3_IM` writer - Peripheral DMA1 CH3 interrupt mask to CPU2"] pub type DMA1_CH3_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH4_IM` reader - Peripheral DMA1 CH4 interrupt mask to CPU2"] pub type DMA1_CH4_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH4_IM` writer - Peripheral DMA1 CH4 interrupt mask to CPU2"] pub type DMA1_CH4_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH5_IM` reader - Peripheral DMA1 CH5 interrupt mask to CPU2"] pub type DMA1_CH5_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH5_IM` writer - Peripheral DMA1 CH5 interrupt mask to CPU2"] pub type DMA1_CH5_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH6_IM` reader - Peripheral DMA1 CH6 interrupt mask to CPU2"] pub type DMA1_CH6_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH6_IM` writer - Peripheral DMA1 CH6 interrupt mask to CPU2"] pub type DMA1_CH6_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA1_CH7_IM` reader - Peripheral DMA1 CH7 interrupt mask to CPU2"] pub type DMA1_CH7_IM_R = crate::BitReader; #[doc = "Field `DMA1_CH7_IM` writer - Peripheral DMA1 CH7 interrupt mask to CPU2"] pub type DMA1_CH7_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH1_IM` reader - Peripheral DMA2 CH1 interrupt mask to CPU1"] pub type DMA2_CH1_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH1_IM` writer - Peripheral DMA2 CH1 interrupt mask to CPU1"] pub type DMA2_CH1_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH2_IM` reader - Peripheral DMA2 CH2 interrupt mask to CPU1"] pub type DMA2_CH2_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH2_IM` writer - Peripheral DMA2 CH2 interrupt mask to CPU1"] pub type DMA2_CH2_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH3_IM` reader - Peripheral DMA2 CH3 interrupt mask to CPU1"] pub type DMA2_CH3_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH3_IM` writer - Peripheral DMA2 CH3 interrupt mask to CPU1"] pub type DMA2_CH3_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH4_IM` reader - Peripheral DMA2 CH4 interrupt mask to CPU1"] pub type DMA2_CH4_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH4_IM` writer - Peripheral DMA2 CH4 interrupt mask to CPU1"] pub type DMA2_CH4_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH5_IM` reader - Peripheral DMA2 CH5 interrupt mask to CPU1"] pub type DMA2_CH5_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH5_IM` writer - Peripheral DMA2 CH5 interrupt mask to CPU1"] pub type DMA2_CH5_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH6_IM` reader - Peripheral DMA2 CH6 interrupt mask to CPU1"] pub type DMA2_CH6_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH6_IM` writer - Peripheral DMA2 CH6 interrupt mask to CPU1"] pub type DMA2_CH6_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMA2_CH7_IM` reader - Peripheral DMA2 CH7 interrupt mask to CPU1"] pub type DMA2_CH7_IM_R = crate::BitReader; #[doc = "Field `DMA2_CH7_IM` writer - Peripheral DMA2 CH7 interrupt mask to CPU1"] pub type DMA2_CH7_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMAM_UX1_IM` reader - Peripheral DMAM UX1 interrupt mask to CPU1"] pub type DMAM_UX1_IM_R = crate::BitReader; #[doc = "Field `DMAM_UX1_IM` writer - Peripheral DMAM UX1 interrupt mask to CPU1"] pub type DMAM_UX1_IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PVM1IM` reader - Peripheral PVM1IM interrupt mask to CPU1"] pub type PVM1IM_R = crate::BitReader; #[doc = "Field `PVM1IM` writer - Peripheral PVM1IM interrupt mask to CPU1"] pub type PVM1IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PVM3IM` reader - Peripheral PVM3IM interrupt mask to CPU1"] pub type PVM3IM_R = crate::BitReader; #[doc = "Field `PVM3IM` writer - Peripheral PVM3IM interrupt mask to CPU1"] pub type PVM3IM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PVDIM` reader - Peripheral PVDIM interrupt mask to CPU1"] pub type PVDIM_R = crate::BitReader; #[doc = "Field `PVDIM` writer - Peripheral PVDIM interrupt mask to CPU1"] pub type PVDIM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TSCIM` reader - Peripheral TSCIM interrupt mask to CPU1"] pub type TSCIM_R = crate::BitReader; #[doc = "Field `TSCIM` writer - Peripheral TSCIM interrupt mask to CPU1"] pub type TSCIM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `LCDIM` reader - Peripheral LCDIM interrupt mask to CPU1"] pub type LCDIM_R = crate::BitReader; #[doc = "Field `LCDIM` writer - Peripheral LCDIM interrupt mask to CPU1"] pub type LCDIM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Peripheral DMA1 CH1 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch1_im(&self) -> DMA1_CH1_IM_R { DMA1_CH1_IM_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Peripheral DMA1 CH2 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch2_im(&self) -> DMA1_CH2_IM_R { DMA1_CH2_IM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Peripheral DMA1 CH3 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch3_im(&self) -> DMA1_CH3_IM_R { DMA1_CH3_IM_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Peripheral DMA1 CH4 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch4_im(&self) -> DMA1_CH4_IM_R { DMA1_CH4_IM_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Peripheral DMA1 CH5 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch5_im(&self) -> DMA1_CH5_IM_R { DMA1_CH5_IM_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Peripheral DMA1 CH6 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch6_im(&self) -> DMA1_CH6_IM_R { DMA1_CH6_IM_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Peripheral DMA1 CH7 interrupt mask to CPU2"] #[inline(always)] pub fn dma1_ch7_im(&self) -> DMA1_CH7_IM_R { DMA1_CH7_IM_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 8 - Peripheral DMA2 CH1 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch1_im(&self) -> DMA2_CH1_IM_R { DMA2_CH1_IM_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Peripheral DMA2 CH2 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch2_im(&self) -> DMA2_CH2_IM_R { DMA2_CH2_IM_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Peripheral DMA2 CH3 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch3_im(&self) -> DMA2_CH3_IM_R { DMA2_CH3_IM_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Peripheral DMA2 CH4 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch4_im(&self) -> DMA2_CH4_IM_R { DMA2_CH4_IM_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Peripheral DMA2 CH5 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch5_im(&self) -> DMA2_CH5_IM_R { DMA2_CH5_IM_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Peripheral DMA2 CH6 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch6_im(&self) -> DMA2_CH6_IM_R { DMA2_CH6_IM_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Peripheral DMA2 CH7 interrupt mask to CPU1"] #[inline(always)] pub fn dma2_ch7_im(&self) -> DMA2_CH7_IM_R { DMA2_CH7_IM_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - Peripheral DMAM UX1 interrupt mask to CPU1"] #[inline(always)] pub fn dmam_ux1_im(&self) -> DMAM_UX1_IM_R { DMAM_UX1_IM_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - Peripheral PVM1IM interrupt mask to CPU1"] #[inline(always)] pub fn pvm1im(&self) -> PVM1IM_R { PVM1IM_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 18 - Peripheral PVM3IM interrupt mask to CPU1"] #[inline(always)] pub fn pvm3im(&self) -> PVM3IM_R { PVM3IM_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 20 - Peripheral PVDIM interrupt mask to CPU1"] #[inline(always)] pub fn pvdim(&self) -> PVDIM_R { PVDIM_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Peripheral TSCIM interrupt mask to CPU1"] #[inline(always)] pub fn tscim(&self) -> TSCIM_R { TSCIM_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - Peripheral LCDIM interrupt mask to CPU1"] #[inline(always)] pub fn lcdim(&self) -> LCDIM_R { LCDIM_R::new(((self.bits >> 22) & 1) != 0) } } impl W { #[doc = "Bit 0 - Peripheral DMA1 CH1 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch1_im(&mut self) -> DMA1_CH1_IM_W<C2IMR2_SPEC, 0> { DMA1_CH1_IM_W::new(self) } #[doc = "Bit 1 - Peripheral DMA1 CH2 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch2_im(&mut self) -> DMA1_CH2_IM_W<C2IMR2_SPEC, 1> { DMA1_CH2_IM_W::new(self) } #[doc = "Bit 2 - Peripheral DMA1 CH3 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch3_im(&mut self) -> DMA1_CH3_IM_W<C2IMR2_SPEC, 2> { DMA1_CH3_IM_W::new(self) } #[doc = "Bit 3 - Peripheral DMA1 CH4 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch4_im(&mut self) -> DMA1_CH4_IM_W<C2IMR2_SPEC, 3> { DMA1_CH4_IM_W::new(self) } #[doc = "Bit 4 - Peripheral DMA1 CH5 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch5_im(&mut self) -> DMA1_CH5_IM_W<C2IMR2_SPEC, 4> { DMA1_CH5_IM_W::new(self) } #[doc = "Bit 5 - Peripheral DMA1 CH6 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch6_im(&mut self) -> DMA1_CH6_IM_W<C2IMR2_SPEC, 5> { DMA1_CH6_IM_W::new(self) } #[doc = "Bit 6 - Peripheral DMA1 CH7 interrupt mask to CPU2"] #[inline(always)] #[must_use] pub fn dma1_ch7_im(&mut self) -> DMA1_CH7_IM_W<C2IMR2_SPEC, 6> { DMA1_CH7_IM_W::new(self) } #[doc = "Bit 8 - Peripheral DMA2 CH1 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch1_im(&mut self) -> DMA2_CH1_IM_W<C2IMR2_SPEC, 8> { DMA2_CH1_IM_W::new(self) } #[doc = "Bit 9 - Peripheral DMA2 CH2 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch2_im(&mut self) -> DMA2_CH2_IM_W<C2IMR2_SPEC, 9> { DMA2_CH2_IM_W::new(self) } #[doc = "Bit 10 - Peripheral DMA2 CH3 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch3_im(&mut self) -> DMA2_CH3_IM_W<C2IMR2_SPEC, 10> { DMA2_CH3_IM_W::new(self) } #[doc = "Bit 11 - Peripheral DMA2 CH4 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch4_im(&mut self) -> DMA2_CH4_IM_W<C2IMR2_SPEC, 11> { DMA2_CH4_IM_W::new(self) } #[doc = "Bit 12 - Peripheral DMA2 CH5 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch5_im(&mut self) -> DMA2_CH5_IM_W<C2IMR2_SPEC, 12> { DMA2_CH5_IM_W::new(self) } #[doc = "Bit 13 - Peripheral DMA2 CH6 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch6_im(&mut self) -> DMA2_CH6_IM_W<C2IMR2_SPEC, 13> { DMA2_CH6_IM_W::new(self) } #[doc = "Bit 14 - Peripheral DMA2 CH7 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dma2_ch7_im(&mut self) -> DMA2_CH7_IM_W<C2IMR2_SPEC, 14> { DMA2_CH7_IM_W::new(self) } #[doc = "Bit 15 - Peripheral DMAM UX1 interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn dmam_ux1_im(&mut self) -> DMAM_UX1_IM_W<C2IMR2_SPEC, 15> { DMAM_UX1_IM_W::new(self) } #[doc = "Bit 16 - Peripheral PVM1IM interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn pvm1im(&mut self) -> PVM1IM_W<C2IMR2_SPEC, 16> { PVM1IM_W::new(self) } #[doc = "Bit 18 - Peripheral PVM3IM interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn pvm3im(&mut self) -> PVM3IM_W<C2IMR2_SPEC, 18> { PVM3IM_W::new(self) } #[doc = "Bit 20 - Peripheral PVDIM interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn pvdim(&mut self) -> PVDIM_W<C2IMR2_SPEC, 20> { PVDIM_W::new(self) } #[doc = "Bit 21 - Peripheral TSCIM interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn tscim(&mut self) -> TSCIM_W<C2IMR2_SPEC, 21> { TSCIM_W::new(self) } #[doc = "Bit 22 - Peripheral LCDIM interrupt mask to CPU1"] #[inline(always)] #[must_use] pub fn lcdim(&mut self) -> LCDIM_W<C2IMR2_SPEC, 22> { LCDIM_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "CPU2 interrupt mask register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c2imr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`c2imr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C2IMR2_SPEC; impl crate::RegisterSpec for C2IMR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c2imr2::R`](R) reader structure"] impl crate::Readable for C2IMR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`c2imr2::W`](W) writer structure"] impl crate::Writable for C2IMR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets C2IMR2 to value 0"] impl crate::Resettable for C2IMR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
#![no_std] #![feature(start)] #![feature(asm)] #![no_main] #![cfg_attr(test, no_main)] #![feature(alloc_error_handler)] #![feature(custom_test_frameworks)] #![feature(core_intrinsics)] #![feature(gen_future)] #![feature(const_mut_refs)] #![feature(naked_functions)] #![feature(abi_x86_interrupt)] #![feature(intra_doc_pointers)] use core::mem; use ferr_os_librust::syscall; use ferr_os_librust::io; extern crate alloc; use alloc::string::String; #[no_mangle] pub extern "C" fn _start(heap_address: u64, heap_size: u64, _args: u64) { ferr_os_librust::allocator::init(heap_address, heap_size); unsafe { syscall::debug(2, 0); let fd = syscall::open(String::from("screen/screenfull"), 0); syscall::dup2(1, fd); syscall::set_screen_size(1, 40); syscall::set_screen_pos(0, 20); } main(); } #[inline(never)] fn main() { let clock_fd = unsafe { syscall::open(String::from("hardware/clock"), 0) }; unsafe { syscall::debug(clock_fd, 42); } /* let sound_fd = unsafe { syscall::open(String::from("hardware/sound"), 0) }; let frequencies: [u64; 13] = [ 262, 277, 293, 311, 329, 349, 369, 391, 415, 440, 466, 494, 523, ]; io::push_sound(sound_fd as u64, 440, 64, 24); for (i, freq) in frequencies.iter().enumerate() { io::push_sound(sound_fd as u64, *freq, 8, 24 + (i as u64) * 12); } io::push_sound(sound_fd as u64, 440, 40, 5 + 14 * 12); io::push_sound(sound_fd as u64, 880, 20, 5 + 14 * 12); */ loop { let mut base = String::from("\n"); base.push_str(&io::read_to_string(clock_fd, 256)); io::print(&base); unsafe { syscall::sleep() }; } }
#[doc = "Register `DOR2` reader"] pub type R = crate::R<DOR2_SPEC>; #[doc = "Field `DACC2DOR` reader - DAC channel2 data output"] pub type DACC2DOR_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:11 - DAC channel2 data output"] #[inline(always)] pub fn dacc2dor(&self) -> DACC2DOR_R { DACC2DOR_R::new((self.bits & 0x0fff) as u16) } } #[doc = "DAC channel2 data output register (DAC_DOR2)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dor2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DOR2_SPEC; impl crate::RegisterSpec for DOR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dor2::R`](R) reader structure"] impl crate::Readable for DOR2_SPEC {} #[doc = "`reset()` method sets DOR2 to value 0"] impl crate::Resettable for DOR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! A WebSocket echo server. use lunatic::net::TcpStream; use puck::{ body::Body, serve, ws::{message::Message, send::send, websocket::WebSocket}, Request, Response, }; pub fn echo(_: Request, stream: TcpStream) { let mut ws = WebSocket::new(stream.clone()); // note that this will *never* return `None` while let Ok(next) = ws.next().unwrap() { match next { Message::Text(_) | Message::Binary(_) => { send(stream.clone(), next).unwrap(); } // the `WebSocket` struct handles returning pings and pongs, so you don't have to _ => {} } } // you also don't need to close the connection - this is done automatically } pub fn home(_: Request) -> Response { Response::build() .header("Content-Type", "text/html") .body(Body::from_string("<h1>Hello World!</h1>")) .build() } #[puck::handler( handle(at = "/", call = "home"), handle(at = "/ws", call = "echo", web_socket = true) )] pub struct App; fn main() { serve::<App, &str>("127.0.0.1:5051").expect("error running server"); }
/// CreateRepoOption options when creating repository #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct CreateRepoOption { /// Whether the repository should be auto-intialized? pub auto_init: Option<bool>, /// DefaultBranch of the repository (used when initializes and in template) pub default_branch: Option<String>, /// Description of the repository to create pub description: Option<String>, /// Gitignores to use pub gitignores: Option<String>, /// Issue Label set to use pub issue_labels: Option<String>, /// License to use pub license: Option<String>, /// Name of the repository to create pub name: String, /// Whether the repository is private pub private: Option<bool>, /// Readme of the repository to create pub readme: Option<String>, /// Whether the repository is template pub template: Option<bool>, /// TrustModel of the repository pub trust_model: Option<crate::create_repo_option::CreateRepoOptionTrustModel>, } /// TrustModel of the repository #[derive(Debug, Clone, Serialize, Deserialize)] #[allow(non_camel_case_types)] pub enum CreateRepoOptionTrustModel { #[serde(rename = "default")] Default, #[serde(rename = "collaborator")] Collaborator, #[serde(rename = "committer")] Committer, #[serde(rename = "collaboratorcommitter")] Collaboratorcommitter, } impl Default for CreateRepoOptionTrustModel { fn default() -> Self { CreateRepoOptionTrustModel::Default } } impl CreateRepoOption { /// Create a builder for this object. #[inline] pub fn builder() -> CreateRepoOptionBuilder<crate::generics::MissingName> { CreateRepoOptionBuilder { body: Default::default(), _name: core::marker::PhantomData, } } #[inline] pub fn admin_create_repo() -> CreateRepoOptionPostBuilder<crate::generics::MissingUsername, crate::generics::MissingName> { CreateRepoOptionPostBuilder { inner: Default::default(), _param_username: core::marker::PhantomData, _name: core::marker::PhantomData, } } #[deprecated] #[inline] pub fn create_org_repo_deprecated() -> CreateRepoOptionPostBuilder1<crate::generics::MissingOrg, crate::generics::MissingName> { CreateRepoOptionPostBuilder1 { inner: Default::default(), _param_org: core::marker::PhantomData, _name: core::marker::PhantomData, } } #[inline] pub fn create_org_repo() -> CreateRepoOptionPostBuilder2<crate::generics::MissingOrg, crate::generics::MissingName> { CreateRepoOptionPostBuilder2 { inner: Default::default(), _param_org: core::marker::PhantomData, _name: core::marker::PhantomData, } } #[inline] pub fn create_current_user_repo() -> CreateRepoOptionPostBuilder3<crate::generics::MissingName> { CreateRepoOptionPostBuilder3 { body: Default::default(), _name: core::marker::PhantomData, } } } impl Into<CreateRepoOption> for CreateRepoOptionBuilder<crate::generics::NameExists> { fn into(self) -> CreateRepoOption { self.body } } impl Into<CreateRepoOption> for CreateRepoOptionPostBuilder<crate::generics::UsernameExists, crate::generics::NameExists> { fn into(self) -> CreateRepoOption { self.inner.body } } impl Into<CreateRepoOption> for CreateRepoOptionPostBuilder1<crate::generics::OrgExists, crate::generics::NameExists> { fn into(self) -> CreateRepoOption { self.inner.body } } impl Into<CreateRepoOption> for CreateRepoOptionPostBuilder2<crate::generics::OrgExists, crate::generics::NameExists> { fn into(self) -> CreateRepoOption { self.inner.body } } impl Into<CreateRepoOption> for CreateRepoOptionPostBuilder3<crate::generics::NameExists> { fn into(self) -> CreateRepoOption { self.body } } /// Builder for [`CreateRepoOption`](./struct.CreateRepoOption.html) object. #[derive(Debug, Clone)] pub struct CreateRepoOptionBuilder<Name> { body: self::CreateRepoOption, _name: core::marker::PhantomData<Name>, } impl<Name> CreateRepoOptionBuilder<Name> { /// Whether the repository should be auto-intialized? #[inline] pub fn auto_init(mut self, value: impl Into<bool>) -> Self { self.body.auto_init = Some(value.into()); self } /// DefaultBranch of the repository (used when initializes and in template) #[inline] pub fn default_branch(mut self, value: impl Into<String>) -> Self { self.body.default_branch = Some(value.into()); self } /// Description of the repository to create #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.body.description = Some(value.into()); self } /// Gitignores to use #[inline] pub fn gitignores(mut self, value: impl Into<String>) -> Self { self.body.gitignores = Some(value.into()); self } /// Issue Label set to use #[inline] pub fn issue_labels(mut self, value: impl Into<String>) -> Self { self.body.issue_labels = Some(value.into()); self } /// License to use #[inline] pub fn license(mut self, value: impl Into<String>) -> Self { self.body.license = Some(value.into()); self } /// Name of the repository to create #[inline] pub fn name(mut self, value: impl Into<String>) -> CreateRepoOptionBuilder<crate::generics::NameExists> { self.body.name = value.into(); unsafe { std::mem::transmute(self) } } /// Whether the repository is private #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.body.private = Some(value.into()); self } /// Readme of the repository to create #[inline] pub fn readme(mut self, value: impl Into<String>) -> Self { self.body.readme = Some(value.into()); self } /// Whether the repository is template #[inline] pub fn template(mut self, value: impl Into<bool>) -> Self { self.body.template = Some(value.into()); self } /// TrustModel of the repository #[inline] pub fn trust_model(mut self, value: crate::create_repo_option::CreateRepoOptionTrustModel) -> Self { self.body.trust_model = Some(value.into()); self } } /// Builder created by [`CreateRepoOption::admin_create_repo`](./struct.CreateRepoOption.html#method.admin_create_repo) method for a `POST` operation associated with `CreateRepoOption`. #[repr(transparent)] #[derive(Debug, Clone)] pub struct CreateRepoOptionPostBuilder<Username, Name> { inner: CreateRepoOptionPostBuilderContainer, _param_username: core::marker::PhantomData<Username>, _name: core::marker::PhantomData<Name>, } #[derive(Debug, Default, Clone)] struct CreateRepoOptionPostBuilderContainer { body: self::CreateRepoOption, param_username: Option<String>, } impl<Username, Name> CreateRepoOptionPostBuilder<Username, Name> { /// username of the user. This user will own the created repository #[inline] pub fn username(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder<crate::generics::UsernameExists, Name> { self.inner.param_username = Some(value.into()); unsafe { std::mem::transmute(self) } } /// Whether the repository should be auto-intialized? #[inline] pub fn auto_init(mut self, value: impl Into<bool>) -> Self { self.inner.body.auto_init = Some(value.into()); self } /// DefaultBranch of the repository (used when initializes and in template) #[inline] pub fn default_branch(mut self, value: impl Into<String>) -> Self { self.inner.body.default_branch = Some(value.into()); self } /// Description of the repository to create #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.inner.body.description = Some(value.into()); self } /// Gitignores to use #[inline] pub fn gitignores(mut self, value: impl Into<String>) -> Self { self.inner.body.gitignores = Some(value.into()); self } /// Issue Label set to use #[inline] pub fn issue_labels(mut self, value: impl Into<String>) -> Self { self.inner.body.issue_labels = Some(value.into()); self } /// License to use #[inline] pub fn license(mut self, value: impl Into<String>) -> Self { self.inner.body.license = Some(value.into()); self } /// Name of the repository to create #[inline] pub fn name(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder<Username, crate::generics::NameExists> { self.inner.body.name = value.into(); unsafe { std::mem::transmute(self) } } /// Whether the repository is private #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.inner.body.private = Some(value.into()); self } /// Readme of the repository to create #[inline] pub fn readme(mut self, value: impl Into<String>) -> Self { self.inner.body.readme = Some(value.into()); self } /// Whether the repository is template #[inline] pub fn template(mut self, value: impl Into<bool>) -> Self { self.inner.body.template = Some(value.into()); self } /// TrustModel of the repository #[inline] pub fn trust_model(mut self, value: crate::create_repo_option::CreateRepoOptionTrustModel) -> Self { self.inner.body.trust_model = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateRepoOptionPostBuilder<crate::generics::UsernameExists, crate::generics::NameExists> { type Output = crate::repository::Repository; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { format!("/admin/users/{username}/repos", username=self.inner.param_username.as_ref().expect("missing parameter username?")).into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.inner.body)) } } impl crate::client::ResponseWrapper<crate::repository::Repository, CreateRepoOptionPostBuilder<crate::generics::UsernameExists, crate::generics::NameExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } } /// Builder created by [`CreateRepoOption::create_org_repo_deprecated`](./struct.CreateRepoOption.html#method.create_org_repo_deprecated) method for a `POST` operation associated with `CreateRepoOption`. #[repr(transparent)] #[derive(Debug, Clone)] pub struct CreateRepoOptionPostBuilder1<Org, Name> { inner: CreateRepoOptionPostBuilder1Container, _param_org: core::marker::PhantomData<Org>, _name: core::marker::PhantomData<Name>, } #[derive(Debug, Default, Clone)] struct CreateRepoOptionPostBuilder1Container { body: self::CreateRepoOption, param_org: Option<String>, } impl<Org, Name> CreateRepoOptionPostBuilder1<Org, Name> { /// name of organization #[inline] pub fn org(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder1<crate::generics::OrgExists, Name> { self.inner.param_org = Some(value.into()); unsafe { std::mem::transmute(self) } } /// Whether the repository should be auto-intialized? #[inline] pub fn auto_init(mut self, value: impl Into<bool>) -> Self { self.inner.body.auto_init = Some(value.into()); self } /// DefaultBranch of the repository (used when initializes and in template) #[inline] pub fn default_branch(mut self, value: impl Into<String>) -> Self { self.inner.body.default_branch = Some(value.into()); self } /// Description of the repository to create #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.inner.body.description = Some(value.into()); self } /// Gitignores to use #[inline] pub fn gitignores(mut self, value: impl Into<String>) -> Self { self.inner.body.gitignores = Some(value.into()); self } /// Issue Label set to use #[inline] pub fn issue_labels(mut self, value: impl Into<String>) -> Self { self.inner.body.issue_labels = Some(value.into()); self } /// License to use #[inline] pub fn license(mut self, value: impl Into<String>) -> Self { self.inner.body.license = Some(value.into()); self } /// Name of the repository to create #[inline] pub fn name(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder1<Org, crate::generics::NameExists> { self.inner.body.name = value.into(); unsafe { std::mem::transmute(self) } } /// Whether the repository is private #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.inner.body.private = Some(value.into()); self } /// Readme of the repository to create #[inline] pub fn readme(mut self, value: impl Into<String>) -> Self { self.inner.body.readme = Some(value.into()); self } /// Whether the repository is template #[inline] pub fn template(mut self, value: impl Into<bool>) -> Self { self.inner.body.template = Some(value.into()); self } /// TrustModel of the repository #[inline] pub fn trust_model(mut self, value: crate::create_repo_option::CreateRepoOptionTrustModel) -> Self { self.inner.body.trust_model = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateRepoOptionPostBuilder1<crate::generics::OrgExists, crate::generics::NameExists> { type Output = crate::repository::Repository; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { format!("/org/{org}/repos", org=self.inner.param_org.as_ref().expect("missing parameter org?")).into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.inner.body)) } } impl crate::client::ResponseWrapper<crate::repository::Repository, CreateRepoOptionPostBuilder1<crate::generics::OrgExists, crate::generics::NameExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } } /// Builder created by [`CreateRepoOption::create_org_repo`](./struct.CreateRepoOption.html#method.create_org_repo) method for a `POST` operation associated with `CreateRepoOption`. #[repr(transparent)] #[derive(Debug, Clone)] pub struct CreateRepoOptionPostBuilder2<Org, Name> { inner: CreateRepoOptionPostBuilder2Container, _param_org: core::marker::PhantomData<Org>, _name: core::marker::PhantomData<Name>, } #[derive(Debug, Default, Clone)] struct CreateRepoOptionPostBuilder2Container { body: self::CreateRepoOption, param_org: Option<String>, } impl<Org, Name> CreateRepoOptionPostBuilder2<Org, Name> { /// name of organization #[inline] pub fn org(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder2<crate::generics::OrgExists, Name> { self.inner.param_org = Some(value.into()); unsafe { std::mem::transmute(self) } } /// Whether the repository should be auto-intialized? #[inline] pub fn auto_init(mut self, value: impl Into<bool>) -> Self { self.inner.body.auto_init = Some(value.into()); self } /// DefaultBranch of the repository (used when initializes and in template) #[inline] pub fn default_branch(mut self, value: impl Into<String>) -> Self { self.inner.body.default_branch = Some(value.into()); self } /// Description of the repository to create #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.inner.body.description = Some(value.into()); self } /// Gitignores to use #[inline] pub fn gitignores(mut self, value: impl Into<String>) -> Self { self.inner.body.gitignores = Some(value.into()); self } /// Issue Label set to use #[inline] pub fn issue_labels(mut self, value: impl Into<String>) -> Self { self.inner.body.issue_labels = Some(value.into()); self } /// License to use #[inline] pub fn license(mut self, value: impl Into<String>) -> Self { self.inner.body.license = Some(value.into()); self } /// Name of the repository to create #[inline] pub fn name(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder2<Org, crate::generics::NameExists> { self.inner.body.name = value.into(); unsafe { std::mem::transmute(self) } } /// Whether the repository is private #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.inner.body.private = Some(value.into()); self } /// Readme of the repository to create #[inline] pub fn readme(mut self, value: impl Into<String>) -> Self { self.inner.body.readme = Some(value.into()); self } /// Whether the repository is template #[inline] pub fn template(mut self, value: impl Into<bool>) -> Self { self.inner.body.template = Some(value.into()); self } /// TrustModel of the repository #[inline] pub fn trust_model(mut self, value: crate::create_repo_option::CreateRepoOptionTrustModel) -> Self { self.inner.body.trust_model = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateRepoOptionPostBuilder2<crate::generics::OrgExists, crate::generics::NameExists> { type Output = crate::repository::Repository; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { format!("/orgs/{org}/repos", org=self.inner.param_org.as_ref().expect("missing parameter org?")).into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.inner.body)) } } impl crate::client::ResponseWrapper<crate::repository::Repository, CreateRepoOptionPostBuilder2<crate::generics::OrgExists, crate::generics::NameExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } } /// Builder created by [`CreateRepoOption::create_current_user_repo`](./struct.CreateRepoOption.html#method.create_current_user_repo) method for a `POST` operation associated with `CreateRepoOption`. #[derive(Debug, Clone)] pub struct CreateRepoOptionPostBuilder3<Name> { body: self::CreateRepoOption, _name: core::marker::PhantomData<Name>, } impl<Name> CreateRepoOptionPostBuilder3<Name> { /// Whether the repository should be auto-intialized? #[inline] pub fn auto_init(mut self, value: impl Into<bool>) -> Self { self.body.auto_init = Some(value.into()); self } /// DefaultBranch of the repository (used when initializes and in template) #[inline] pub fn default_branch(mut self, value: impl Into<String>) -> Self { self.body.default_branch = Some(value.into()); self } /// Description of the repository to create #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.body.description = Some(value.into()); self } /// Gitignores to use #[inline] pub fn gitignores(mut self, value: impl Into<String>) -> Self { self.body.gitignores = Some(value.into()); self } /// Issue Label set to use #[inline] pub fn issue_labels(mut self, value: impl Into<String>) -> Self { self.body.issue_labels = Some(value.into()); self } /// License to use #[inline] pub fn license(mut self, value: impl Into<String>) -> Self { self.body.license = Some(value.into()); self } /// Name of the repository to create #[inline] pub fn name(mut self, value: impl Into<String>) -> CreateRepoOptionPostBuilder3<crate::generics::NameExists> { self.body.name = value.into(); unsafe { std::mem::transmute(self) } } /// Whether the repository is private #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.body.private = Some(value.into()); self } /// Readme of the repository to create #[inline] pub fn readme(mut self, value: impl Into<String>) -> Self { self.body.readme = Some(value.into()); self } /// Whether the repository is template #[inline] pub fn template(mut self, value: impl Into<bool>) -> Self { self.body.template = Some(value.into()); self } /// TrustModel of the repository #[inline] pub fn trust_model(mut self, value: crate::create_repo_option::CreateRepoOptionTrustModel) -> Self { self.body.trust_model = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for CreateRepoOptionPostBuilder3<crate::generics::NameExists> { type Output = crate::repository::Repository; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { "/user/repos".into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.body)) } } impl crate::client::ResponseWrapper<crate::repository::Repository, CreateRepoOptionPostBuilder3<crate::generics::NameExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } }
/// A trait for defining an interface against a raw key-value store (e.g `leveldb/rocksdb`). pub trait RawKV { /// # Gets the `value` pointed by by `key`. /// /// If there's a matchikg pending `value` (i.e not flushed yet) it should be returned. /// Otherwise, should proceed looking for `key -> value` under the persisted data. /// /// In case there is no matching `value`, `None` should be returned. #[must_use] fn get(&self, key: &[u8]) -> Option<Vec<u8>>; /// Stores a batch of changes. /// /// Each change is tuple denoting `(key, value)` fn set(&mut self, changes: &[(&[u8], &[u8])]); }
extern crate nimble; use nimble::score; use nimble::utils; use nimble::reference_library; use std::path::Path; use std::collections::HashMap; use clap::{App, load_yaml}; fn main() { // Parse command line arguments based on the yaml schema let yaml = load_yaml!("cli.yml"); let matches = App::from_yaml(yaml).get_matches(); let reference_json_path = matches.value_of("reference").unwrap(); let output_path = matches.value_of("output").unwrap(); let input_files: Vec<&str> = matches.values_of("input").unwrap().collect(); let num_cores = matches.value_of("num_cores").unwrap_or("1").parse::<usize>().expect("Error -- please provide an integer value for the number of cores"); println!("Loading and preprocessing reference data"); // Read library alignment config info, reference library metadata, and sequences from library json let (align_config, reference_metadata) = reference_library::get_reference_library(Path::new(reference_json_path)); // Generate error-checked vectors of seqs and names for the debrujin index let (reference_seqs, reference_names) = utils::validate_reference_pairs(&reference_metadata); // Create debruijn index of the reference library let reference_index = debruijn_mapping::build_index::build_index::<debruijn_mapping::config::KmerType>( &reference_seqs, &reference_names, &HashMap::new(), num_cores ).expect("Error -- could not create pseudoaligner index of the reference library"); println!("Loading read sequences"); /* Get error-checked iterators to the sequences that will be aligned to the reference from the * sequence genome file(s) */ let sequences = utils::get_error_checked_fastq_reader(input_files[0]); // Only get reverse sequences if a reverse sequence file is provided let reverse_sequences = if input_files.len() > 1 { println!("Reading reverse sequences"); Some(utils::get_error_checked_fastq_reader(input_files[1])) } else { None }; println!("Pseudo-aligning reads to reference index"); // Perform alignment and filtration using the score package let results = score::score(sequences, reverse_sequences, reference_index, &reference_metadata, align_config); println!("Writing results to file"); utils::write_to_tsv(results, output_path); print!("Output results written to output path"); }
use std::{error::Error, path::PathBuf}; use clap::Parser; mod legacy { use serde::Deserialize; use serde_yaml::Value; #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Test { pub description: String, pub min_server_version: String, pub max_server_version: Option<String>, pub fail_point: Option<serde_yaml::Mapping>, pub target: Target, pub topology: Vec<String>, pub change_stream_pipeline: Vec<Value>, pub change_stream_options: Option<Value>, pub operations: Vec<Operation>, pub expectations: Option<Vec<serde_yaml::Mapping>>, pub result: TestResult, } #[derive(Debug, Deserialize)] #[serde(deny_unknown_fields)] pub struct File { pub database_name: String, pub collection_name: String, pub database2_name: Option<String>, pub collection2_name: Option<String>, pub tests: Vec<Test>, } #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub enum Target { Collection, Database, Client, } #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct Operation { pub name: String, pub database: String, pub collection: String, pub arguments: Option<serde_yaml::Mapping>, } #[derive(Debug, Deserialize, Clone)] #[serde(untagged, rename_all = "camelCase", deny_unknown_fields)] pub enum TestResult { Error { error: ExpectError }, Success { success: Vec<serde_yaml::Mapping> }, } #[derive(Debug, Deserialize, Clone)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct ExpectError { pub code: i32, } } mod unified { use serde::Serialize; use serde_yaml::Value; use super::legacy; #[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct Test { description: String, run_on_requirements: Vec<RunOnRequirements>, operations: Vec<Operation>, expect_events: Option<Vec<ExpectEvents>>, } #[serde_with::skip_serializing_none] #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] struct RunOnRequirements { min_server_version: String, max_server_version: Option<String>, topologies: Vec<String>, } #[serde_with::skip_serializing_none] #[derive(Debug, Default, Serialize)] #[serde(rename_all = "camelCase")] struct Operation { name: String, object: String, arguments: Option<serde_yaml::Mapping>, save_result_as_entity: Option<String>, expect_result: Option<serde_yaml::Mapping>, expect_error: Option<ExpectError>, } #[derive(Debug, Default, Serialize)] #[serde(rename_all = "camelCase")] struct ExpectEvents { client: String, event_match: String, events: Vec<serde_yaml::Mapping>, } #[derive(Debug, Default, Serialize)] #[serde(rename_all = "camelCase")] struct ExpectError { error_code: i32, } const CLIENT_NAME: &str = "client0"; const GLOBAL_CLIENT_NAME: &str = "globalClient"; const DB1_NAME: &str = "database0"; const DB2_NAME: &str = "database1"; const COLL1_NAME: &str = "collection0"; const COLL2_NAME: &str = "collection1"; impl Test { pub fn parse(args: &super::Args, file: &legacy::File, old: legacy::Test) -> Self { Self { description: old.description, run_on_requirements: vec![RunOnRequirements { min_server_version: old.min_server_version, max_server_version: old.max_server_version, topologies: old.topology, }], operations: { let mut out = vec![]; // Fail point if let Some(fp) = old.fail_point { out.push(Operation { name: "failPoint".to_string(), object: "testRunner".to_string(), arguments: Some( vec![ (ys("client"), ys(GLOBAL_CLIENT_NAME)), (ys("failPoint"), Value::Mapping(fp)), ] .into_iter() .collect(), ), ..Operation::default() }); } // Initial createChangeStream out.push(Operation { name: "createChangeStream".to_string(), object: match old.target { legacy::Target::Collection => COLL1_NAME, legacy::Target::Database => DB1_NAME, legacy::Target::Client => CLIENT_NAME, } .to_string(), arguments: Some( { let mut out = vec![( ys("pipeline"), Value::Sequence(old.change_stream_pipeline), )]; if let Some(options) = old.change_stream_options { out.push((ys("options"), options)); } out } .into_iter() .collect(), ), save_result_as_entity: Some("changeStream0".to_string()), ..Operation::default() }); // Test operations out.extend( old.operations .into_iter() .map(|op| parse_operation(file, op)), ); // Test results match old.result { legacy::TestResult::Success { success } => { out.extend(success.into_iter().map(|suc| parse_success(file, suc))) } legacy::TestResult::Error { error } => { out.push(Operation { name: "iterateUntilDocumentOrError".to_string(), object: "changeStream0".to_string(), expect_error: Some(ExpectError { error_code: error.code, }), ..Operation::default() }); } } out }, expect_events: old.expectations.map(|mut exps| { let len = exps.len(); for (ix, exp) in (&mut exps).into_iter().enumerate() { if let Some(Value::Mapping(mut cse)) = exp.remove(&ys("command_started_event")) { if let Some(val) = cse.remove(&ys("command_name")) { cse.insert(ys("commandName"), val); } if let Some(mut val) = cse.remove(&ys("database_name")) { match val { Value::String(s) if s == file.database_name => { val = Value::String(DB1_NAME.to_string()); } _ => (), } cse.insert(ys("databaseName"), val); } let mut val = Value::Mapping(cse); // The *-resume-*.yml test files contain event expecations that are // missing the `resumeAfter` clause, so this // adds a matcher that will work whether or // not that clause is present. if args.fix_resume_event && ix == len - 1 { fn singleton(key: &str, value: Value) -> Value { Value::Mapping(vec![(ys(key), value)].into_iter().collect()) } val["command"]["pipeline"][0]["$changeStream"] = singleton( "resumeAfter", singleton( "$$unsetOrMatches", singleton("$$exists", Value::Bool(true)), ), ); } exp.insert(ys("commandStartedEvent"), val); } fix_names(file, exp); fix_placeholders(exp); } vec![ExpectEvents { client: CLIENT_NAME.to_string(), event_match: "prefix".to_string(), events: exps, }] }), } } } fn ys<S: Into<String>>(s: S) -> Value { Value::String(s.into()) } const GLOBAL_DB1_NAME: &str = "globalDatabase0"; const GLOBAL_DB2_NAME: &str = "globalDatabase1"; const GLOBAL_COLL1_NAME: &str = "globalCollection0"; const GLOBAL_COLL2_NAME: &str = "globalCollection1"; const GLOBAL_DB2_COLL1_NAME: &str = "globalDb1Collection0"; const GLOBAL_DB1_COLL2_NAME: &str = "globalDb0Collection1"; fn parse_operation(file: &legacy::File, old: legacy::Operation) -> Operation { let object = { let coll_num = if old.collection == file.collection_name { 1 } else if Some(&old.collection) == file.collection2_name.as_ref() { 2 } else { panic!("unexpected collection name {:?}", old.collection); }; let db_num = if old.database == file.database_name { 1 } else if Some(&old.database) == file.database2_name.as_ref() { 2 } else { panic!("unexpected database name {:?}", old.database); }; match (db_num, coll_num) { (1, 1) => GLOBAL_COLL1_NAME, (1, 2) => GLOBAL_DB1_COLL2_NAME, (2, 1) => GLOBAL_DB2_COLL1_NAME, (2, 2) => GLOBAL_DB2_NAME, _ => panic!("invalid target {:?}", (db_num, coll_num)), } } .to_string(); let mut arguments = old.arguments; if let Some(args) = &mut arguments { fix_names(file, args); } Operation { name: old.name, object, arguments, ..Operation::default() } } fn fix_names(file: &legacy::File, map: &mut serde_yaml::Mapping) { visit_mut(map, &|_, val| match val { Value::String(s) => { if s == &file.database_name { *s = DB1_NAME.to_string() } else if Some(&*s) == file.database2_name.as_ref() { *s = DB2_NAME.to_string() } else if s == &file.collection_name { *s = COLL1_NAME.to_string() } else if Some(&*s) == file.collection2_name.as_ref() { *s = COLL2_NAME.to_string() } } _ => (), }); } fn fix_placeholders(map: &mut serde_yaml::Mapping) { visit_mut(map, &|_, val| match val { Value::Number(num) if num.as_i64() == Some(42) => *val = exists(), Value::String(s) if s == "42" => *val = exists(), _ => (), }); } fn parse_success(file: &legacy::File, mut suc: serde_yaml::Mapping) -> Operation { visit_mut(&mut suc, &|key, val| { if key == "fullDocument" { if let Value::Mapping(map) = val { if !map.contains_key(&ys("_id")) { map.insert(ys("_id"), exists()); } } } }); fix_names(file, &mut suc); fix_placeholders(&mut suc); Operation { name: "iterateUntilDocumentOrError".to_string(), object: "changeStream0".to_string(), expect_result: Some(suc), ..Operation::default() } } fn exists() -> Value { Value::Mapping([(ys("$$exists"), Value::Bool(true))].into_iter().collect()) } fn visit_mut<F>(root: &mut serde_yaml::Mapping, visitor: &F) where F: Fn(&str, &mut Value), { for (key, value) in root.iter_mut() { visitor(key.as_str().unwrap(), value); if let Value::Mapping(map) = value { visit_mut(map, visitor); } } } pub fn postprocess(text: &mut String) { *text = text .replace( "saveResultAsEntity: changeStream0", "saveResultAsEntity: &changeStream0 changeStream0", ) .replace_with_ref("changeStream0") .replace_with_ref(CLIENT_NAME) .replace_with_ref(DB1_NAME) .replace_with_ref(DB2_NAME) .replace_with_ref(COLL1_NAME) .replace_with_ref(COLL2_NAME) .replace_with_ref(GLOBAL_DB1_NAME) .replace_with_ref(GLOBAL_DB2_NAME) .replace_with_ref(GLOBAL_COLL1_NAME) .replace_with_ref(GLOBAL_COLL2_NAME) .replace_with_ref(GLOBAL_DB1_COLL2_NAME) .replace_with_ref(GLOBAL_DB2_COLL1_NAME); } trait StringExt { fn replace_with_ref(&self, name: &str) -> String; } impl StringExt for String { fn replace_with_ref(&self, name: &str) -> String { self.replace(&format!(": {}", name), &format!(": *{}", name)) } } } #[derive(Parser)] #[clap(author, version, about, long_about = None)] pub struct Args { #[clap(short, long)] input: PathBuf, #[clap(short, long)] test: usize, #[clap(short, long)] fix_resume_event: bool, } fn main() -> Result<(), Box<dyn Error>> { let args = Args::parse(); let input = std::fs::read_to_string(&args.input)?; let file: legacy::File = serde_yaml::from_str(&input)?; println!("Parsing test {} of {}", args.test + 1, file.tests.len()); let test = &file.tests[args.test]; let out = unified::Test::parse(&args, &file, test.clone()); let mut text = serde_yaml::to_string(&out)?; unified::postprocess(&mut text); println!("{}", text); Ok(()) }
#[doc = "Register `EMR2` reader"] pub type R = crate::R<EMR2_SPEC>; #[doc = "Register `EMR2` writer"] pub type W = crate::W<EMR2_SPEC>; #[doc = "Field `EM32` reader - Event mask on external/internal line 32"] pub type EM32_R = crate::BitReader<EM32_A>; #[doc = "Event mask on external/internal line 32\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EM32_A { #[doc = "0: Interrupt request line is masked"] Masked = 0, #[doc = "1: Interrupt request line is unmasked"] Unmasked = 1, } impl From<EM32_A> for bool { #[inline(always)] fn from(variant: EM32_A) -> Self { variant as u8 != 0 } } impl EM32_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EM32_A { match self.bits { false => EM32_A::Masked, true => EM32_A::Unmasked, } } #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == EM32_A::Masked } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn is_unmasked(&self) -> bool { *self == EM32_A::Unmasked } } #[doc = "Field `EM32` writer - Event mask on external/internal line 32"] pub type EM32_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EM32_A>; impl<'a, REG, const O: u8> EM32_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn masked(self) -> &'a mut crate::W<REG> { self.variant(EM32_A::Masked) } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn unmasked(self) -> &'a mut crate::W<REG> { self.variant(EM32_A::Unmasked) } } #[doc = "Field `EM33` reader - Event mask on external/internal line 33"] pub use EM32_R as EM33_R; #[doc = "Field `EM34` reader - Event mask on external/internal line 34"] pub use EM32_R as EM34_R; #[doc = "Field `EM35` reader - Event mask on external/internal line 35"] pub use EM32_R as EM35_R; #[doc = "Field `EM36` reader - Event mask on external/internal line 36"] pub use EM32_R as EM36_R; #[doc = "Field `EM37` reader - Event mask on external/internal line 37"] pub use EM32_R as EM37_R; #[doc = "Field `EM40` reader - Event mask on external/internal line 40"] pub use EM32_R as EM40_R; #[doc = "Field `EM41` reader - Event mask on external/internal line 41"] pub use EM32_R as EM41_R; #[doc = "Field `EM42` reader - Event mask on external/internal line 42"] pub use EM32_R as EM42_R; #[doc = "Field `EM43` reader - Event mask on external/internal line 43"] pub use EM32_R as EM43_R; #[doc = "Field `EM33` writer - Event mask on external/internal line 33"] pub use EM32_W as EM33_W; #[doc = "Field `EM34` writer - Event mask on external/internal line 34"] pub use EM32_W as EM34_W; #[doc = "Field `EM35` writer - Event mask on external/internal line 35"] pub use EM32_W as EM35_W; #[doc = "Field `EM36` writer - Event mask on external/internal line 36"] pub use EM32_W as EM36_W; #[doc = "Field `EM37` writer - Event mask on external/internal line 37"] pub use EM32_W as EM37_W; #[doc = "Field `EM40` writer - Event mask on external/internal line 40"] pub use EM32_W as EM40_W; #[doc = "Field `EM41` writer - Event mask on external/internal line 41"] pub use EM32_W as EM41_W; #[doc = "Field `EM42` writer - Event mask on external/internal line 42"] pub use EM32_W as EM42_W; #[doc = "Field `EM43` writer - Event mask on external/internal line 43"] pub use EM32_W as EM43_W; impl R { #[doc = "Bit 0 - Event mask on external/internal line 32"] #[inline(always)] pub fn em32(&self) -> EM32_R { EM32_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Event mask on external/internal line 33"] #[inline(always)] pub fn em33(&self) -> EM33_R { EM33_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Event mask on external/internal line 34"] #[inline(always)] pub fn em34(&self) -> EM34_R { EM34_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Event mask on external/internal line 35"] #[inline(always)] pub fn em35(&self) -> EM35_R { EM35_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Event mask on external/internal line 36"] #[inline(always)] pub fn em36(&self) -> EM36_R { EM36_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Event mask on external/internal line 37"] #[inline(always)] pub fn em37(&self) -> EM37_R { EM37_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 8 - Event mask on external/internal line 40"] #[inline(always)] pub fn em40(&self) -> EM40_R { EM40_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Event mask on external/internal line 41"] #[inline(always)] pub fn em41(&self) -> EM41_R { EM41_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Event mask on external/internal line 42"] #[inline(always)] pub fn em42(&self) -> EM42_R { EM42_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Event mask on external/internal line 43"] #[inline(always)] pub fn em43(&self) -> EM43_R { EM43_R::new(((self.bits >> 11) & 1) != 0) } } impl W { #[doc = "Bit 0 - Event mask on external/internal line 32"] #[inline(always)] #[must_use] pub fn em32(&mut self) -> EM32_W<EMR2_SPEC, 0> { EM32_W::new(self) } #[doc = "Bit 1 - Event mask on external/internal line 33"] #[inline(always)] #[must_use] pub fn em33(&mut self) -> EM33_W<EMR2_SPEC, 1> { EM33_W::new(self) } #[doc = "Bit 2 - Event mask on external/internal line 34"] #[inline(always)] #[must_use] pub fn em34(&mut self) -> EM34_W<EMR2_SPEC, 2> { EM34_W::new(self) } #[doc = "Bit 3 - Event mask on external/internal line 35"] #[inline(always)] #[must_use] pub fn em35(&mut self) -> EM35_W<EMR2_SPEC, 3> { EM35_W::new(self) } #[doc = "Bit 4 - Event mask on external/internal line 36"] #[inline(always)] #[must_use] pub fn em36(&mut self) -> EM36_W<EMR2_SPEC, 4> { EM36_W::new(self) } #[doc = "Bit 5 - Event mask on external/internal line 37"] #[inline(always)] #[must_use] pub fn em37(&mut self) -> EM37_W<EMR2_SPEC, 5> { EM37_W::new(self) } #[doc = "Bit 8 - Event mask on external/internal line 40"] #[inline(always)] #[must_use] pub fn em40(&mut self) -> EM40_W<EMR2_SPEC, 8> { EM40_W::new(self) } #[doc = "Bit 9 - Event mask on external/internal line 41"] #[inline(always)] #[must_use] pub fn em41(&mut self) -> EM41_W<EMR2_SPEC, 9> { EM41_W::new(self) } #[doc = "Bit 10 - Event mask on external/internal line 42"] #[inline(always)] #[must_use] pub fn em42(&mut self) -> EM42_W<EMR2_SPEC, 10> { EM42_W::new(self) } #[doc = "Bit 11 - Event mask on external/internal line 43"] #[inline(always)] #[must_use] pub fn em43(&mut self) -> EM43_W<EMR2_SPEC, 11> { EM43_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`emr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`emr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct EMR2_SPEC; impl crate::RegisterSpec for EMR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`emr2::R`](R) reader structure"] impl crate::Readable for EMR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`emr2::W`](W) writer structure"] impl crate::Writable for EMR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets EMR2 to value 0"] impl crate::Resettable for EMR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use poker; use poker::Hand; use std::str::FromStr; #[test] fn it_evaluates_hand() { let hand = Hand::from_str("Aβ™₯ Kβ™₯ Qβ™₯ Jβ™₯ 10β™₯").unwrap(); assert_eq!(hand.evaluate(), "royal flush"); let hand = Hand::from_str("Qβ™₯ Jβ™₯ 10β™₯ 9β™₯ 8β™₯").unwrap(); assert_eq!(hand.evaluate(), "straight flush"); let hand = Hand::from_str("Qβ™₯ 7β™₯ Q♣ Q♦ Qβ™ ").unwrap(); assert_eq!(hand.evaluate(), "4 of a kind of queens"); let hand = Hand::from_str("Qβ™₯ 7β™₯ Q♣ Q♦ 7β™ ").unwrap(); assert_eq!(hand.evaluate(), "full house"); let hand = Hand::from_str("Qβ™₯ 7β™₯ 3β™₯ Aβ™₯ 9β™₯").unwrap(); assert_eq!(hand.evaluate(), "flush"); let hand = Hand::from_str("Qβ™₯ 9♣ J♦ 8β™  10β™₯").unwrap(); assert_eq!(hand.evaluate(), "straight"); let hand = Hand::from_str("Qβ™₯ 7β™₯ Q♣ Q♦ Jβ™ ").unwrap(); assert_eq!(hand.evaluate(), "3 of a kind of queens"); let hand = Hand::from_str("Qβ™₯ 7β™₯ Q♣ 5♦ 7β™ ").unwrap(); assert_eq!(hand.evaluate(), "two pairs"); let hand = Hand::from_str("Qβ™₯ 7β™₯ Q♣ 5♦ Jβ™ ").unwrap(); assert_eq!(hand.evaluate(), "pair of queens"); let hand = Hand::from_str("Qβ™₯ 7β™₯ J♣ 5♦ Aβ™ ").unwrap(); assert_eq!(hand.evaluate(), "high card ace of β™ "); }
mod native; use native::*; use std::fs::OpenOptions; use std::path::Path; use memflow::*; use memflow_derive::*; use std::fs::File; /** The `parse_file` function reads and parses Microsoft Windows Coredump files. When opening a crashdump it tries to parse the first 0x2000 bytes of the file as a 64 bit Windows Coredump. If the validation of the 64 bit Header fails it tries to read the first 0x1000 bytes of the file and validates it as 32 bit Windows Coredump. If neither attempt succeeds the function will fail with an `Error::Conector` error. `create_connector` function attempts to directly create a connector (based on crate configuration - mmap or stdio based). # Examples ``` use std::path::PathBuf; use memflow::connector::ConnectorArgs; use memflow_coredump::create_connector; let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources/test/coredump_win10_64bit_stripped.raw"); if let Ok(mut mem) = create_connector(&ConnectorArgs::with_default(path.to_str().unwrap())) { println!("Coredump connector initialized"); } ``` */ #[cfg(feature = "filemap")] pub type CoreDump<'a> = ReadMappedFilePhysicalMemory<'a>; #[cfg(not(feature = "filemap"))] pub type CoreDump<'a> = FileIOMemory<File>; /// Opens a Microsoft Windows Coredump /// /// This function will return the underlying file and the memory map with correct file offsets. /// These arguments can then be passed to the mmap or read connector for Read/Write operations. pub fn parse_file<P: AsRef<Path>>(path: P) -> Result<(MemoryMap<(Address, usize)>, File)> { let mut file = OpenOptions::new() .read(true) .write(false) .open(path) .map_err(|_| Error::Connector("unable to open coredump file"))?; let mem_map = parse_coredump64(&mut file).or_else(|_| parse_coredump32(&mut file))?; Ok((mem_map, file)) } /// Creates a new Microsoft Windows Coredump Connector instance. /// /// This function will return a connector reading the underlying data of the core dump. /// The type of connector depends on the feature flags of the crate. #[connector(name = "coredump")] pub fn create_connector<'a>(args: &ConnectorArgs) -> Result<CoreDump<'a>> { let (map, file) = parse_file( args.get("file") .or_else(|| args.get_default()) .ok_or_else(|| Error::Connector("no path specified"))?, )?; #[cfg(feature = "filemap")] { Ok(MMAPInfo::try_with_filemap(file, map)?.into_connector()) } #[cfg(not(feature = "filemap"))] { Ok(CoreDump::try_with_reader(file, map)?.into_connector()) } } #[cfg(test)] mod tests { use super::*; use std::path::PathBuf; #[test] fn parse_win10_64bit() { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources/test/coredump_win10_64bit_stripped.raw"); parse_file(path).unwrap(); } #[test] fn parse_win7_32bit() { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("resources/test/coredump_win7_32bit_stripped.raw"); parse_file(path).unwrap(); } }
use super::*; use std::convert; #[derive(Debug, Copy, Clone)] pub struct Exception { exception_: Local<V8::Object>, } impl Exception { pub fn as_rust_string(&mut self) -> std::string::String { let context = Isolate::get_current_context(); let mut to_string = self.exception_.get(context, "toString").to_function(); let result = to_string.call(context, self, vec![]); result.as_rust_string() } pub fn syntax_error_stack(&mut self) -> std::string::String { unsafe { let message = V8::Exception_CreateMessage(Isolate::raw(), self.exception_.as_value().into()); let message = message.val_.as_ref().unwrap(); let origin = message.GetScriptOrigin(); let name: Local<V8::Value> = origin.resource_name_.into(); let name = name.as_rust_string(); let context: V8::Local<V8::Context> = Isolate::get_current_context().into(); let line = message.GetLineNumber(context).value_; let col = message.GetStartColumn1(context).value_; format!( "{}\n at {}:{}:{}", self.as_rust_string(), name, line, col ) } } } impl convert::From<Local<V8::Object>> for Exception { fn from(val: Local<V8::Object>) -> Exception { Exception { exception_: val } } } impl convert::From<Local<V8::Value>> for Exception { fn from(val: Local<V8::Value>) -> Exception { val.to_object().into() } } impl convert::From<V8::Local<V8::Value>> for Exception { fn from(val: V8::Local<V8::Value>) -> Exception { let val: Local<V8::Value> = val.into(); val.to_object().into() } } impl IntoValue for Exception { fn into_value(&self) -> Local<V8::Value> { self.exception_.as_value() } }
#[allow(missing_docs)] #[rustc_copy_clone_marker] pub struct Vertex { pub pos: [f32; 2], pub colour: [f32; 4], } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::clone::Clone for Vertex { #[inline] fn clone(&self) -> Vertex { { let _: ::std::clone::AssertParamIsClone<[f32; 2]>; let _: ::std::clone::AssertParamIsClone<[f32; 4]>; *self } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::marker::Copy for Vertex { } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::fmt::Debug for Vertex { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { Vertex { pos: ref __self_0_0, colour: ref __self_0_1 } => { let mut builder = __arg_0.debug_struct("Vertex"); let _ = builder.field("pos", &&(*__self_0_0)); let _ = builder.field("colour", &&(*__self_0_1)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::cmp::PartialEq for Vertex { #[inline] fn eq(&self, __arg_0: &Vertex) -> bool { match *__arg_0 { Vertex { pos: ref __self_1_0, colour: ref __self_1_1 } => match *self { Vertex { pos: ref __self_0_0, colour: ref __self_0_1 } => true && (*__self_0_0) == (*__self_1_0) && (*__self_0_1) == (*__self_1_1), }, } } #[inline] fn ne(&self, __arg_0: &Vertex) -> bool { match *__arg_0 { Vertex { pos: ref __self_1_0, colour: ref __self_1_1 } => match *self { Vertex { pos: ref __self_0_0, colour: ref __self_0_1 } => false || (*__self_0_0) != (*__self_1_0) || (*__self_0_1) != (*__self_1_1), }, } } } unsafe impl ::traits::Pod for Vertex { } impl ::pso::buffer::Structure<::format::Format> for Vertex { fn query(name: &str) -> ::std::option::Option<::pso::buffer::Element<::format::Format>> { use std::mem::{size_of, transmute}; use ::pso::buffer::{Element, ElemOffset}; let tmp: &Vertex = unsafe { transmute(1usize) }; let base = tmp as *const _ as usize; let (sub_name, big_offset) = { let mut split = name.split(|c| c == '[' || c == ']'); let _ = split.next().unwrap(); match split.next() { Some(s) => { let array_id: ElemOffset = s.parse().unwrap(); let sub_name = match split.next() { Some(s) if s.starts_with('.') => &s[1..], _ => name, }; (sub_name, array_id * (size_of::<Vertex>() as ElemOffset)) } None => (name, 0), } }; match sub_name { "vPos" => Some(Element{format: <[f32; 2] as ::format::Formatted>::get_format(), offset: (((&tmp.pos as *const _ as usize) - base) as ElemOffset) + big_offset,}), "vColour" => Some(Element{format: <[f32; 4] as ::format::Formatted>::get_format(), offset: (((&tmp.colour as *const _ as usize) - base) as ElemOffset) + big_offset,}), _ => None, } } } #[allow(missing_docs)] #[doc = r" Uniforms that apply to all Item shaders."] #[rustc_copy_clone_marker] pub struct ItemLocals { pub transform: [[f32; 4]; 4], pub pos: [f32; 2], pub size: [f32; 2], } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::clone::Clone for ItemLocals { #[inline] fn clone(&self) -> ItemLocals { { let _: ::std::clone::AssertParamIsClone<[[f32; 4]; 4]>; let _: ::std::clone::AssertParamIsClone<[f32; 2]>; let _: ::std::clone::AssertParamIsClone<[f32; 2]>; *self } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::marker::Copy for ItemLocals { } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::fmt::Debug for ItemLocals { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { ItemLocals { transform: ref __self_0_0, pos: ref __self_0_1, size: ref __self_0_2 } => { let mut builder = __arg_0.debug_struct("ItemLocals"); let _ = builder.field("transform", &&(*__self_0_0)); let _ = builder.field("pos", &&(*__self_0_1)); let _ = builder.field("size", &&(*__self_0_2)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::cmp::PartialEq for ItemLocals { #[inline] fn eq(&self, __arg_0: &ItemLocals) -> bool { match *__arg_0 { ItemLocals { transform: ref __self_1_0, pos: ref __self_1_1, size: ref __self_1_2 } => match *self { ItemLocals { transform: ref __self_0_0, pos: ref __self_0_1, size: ref __self_0_2 } => true && (*__self_0_0) == (*__self_1_0) && (*__self_0_1) == (*__self_1_1) && (*__self_0_2) == (*__self_1_2), }, } } #[inline] fn ne(&self, __arg_0: &ItemLocals) -> bool { match *__arg_0 { ItemLocals { transform: ref __self_1_0, pos: ref __self_1_1, size: ref __self_1_2 } => match *self { ItemLocals { transform: ref __self_0_0, pos: ref __self_0_1, size: ref __self_0_2 } => false || (*__self_0_0) != (*__self_1_0) || (*__self_0_1) != (*__self_1_1) || (*__self_0_2) != (*__self_1_2), }, } } } unsafe impl ::traits::Pod for ItemLocals { } impl ::pso::buffer::Structure<::shade::ConstFormat> for ItemLocals { fn query(name: &str) -> ::std::option::Option<::pso::buffer::Element<::shade::ConstFormat>> { use std::mem::{size_of, transmute}; use ::pso::buffer::{Element, ElemOffset}; let tmp: &ItemLocals = unsafe { transmute(1usize) }; let base = tmp as *const _ as usize; let (sub_name, big_offset) = { let mut split = name.split(|c| c == '[' || c == ']'); let _ = split.next().unwrap(); match split.next() { Some(s) => { let array_id: ElemOffset = s.parse().unwrap(); let sub_name = match split.next() { Some(s) if s.starts_with('.') => &s[1..], _ => name, }; (sub_name, array_id * (size_of::<ItemLocals>() as ElemOffset)) } None => (name, 0), } }; match sub_name { "uTransform" => Some(Element{format: <[[f32; 4]; 4] as ::shade::Formatted>::get_format(), offset: (((&tmp.transform as *const _ as usize) - base) as ElemOffset) + big_offset,}), "uPos" => Some(Element{format: <[f32; 2] as ::shade::Formatted>::get_format(), offset: (((&tmp.pos as *const _ as usize) - base) as ElemOffset) + big_offset,}), "uSize" => Some(Element{format: <[f32; 2] as ::shade::Formatted>::get_format(), offset: (((&tmp.size as *const _ as usize) - base) as ElemOffset) + big_offset,}), _ => None, } } } #[allow(missing_docs)] #[rustc_copy_clone_marker] pub struct Locals { pub gradient: f32, } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::clone::Clone for Locals { #[inline] fn clone(&self) -> Locals { { let _: ::std::clone::AssertParamIsClone<f32>; *self } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::marker::Copy for Locals { } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::fmt::Debug for Locals { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { Locals { gradient: ref __self_0_0 } => { let mut builder = __arg_0.debug_struct("Locals"); let _ = builder.field("gradient", &&(*__self_0_0)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] #[allow(missing_docs)] impl ::std::cmp::PartialEq for Locals { #[inline] fn eq(&self, __arg_0: &Locals) -> bool { match *__arg_0 { Locals { gradient: ref __self_1_0 } => match *self { Locals { gradient: ref __self_0_0 } => true && (*__self_0_0) == (*__self_1_0), }, } } #[inline] fn ne(&self, __arg_0: &Locals) -> bool { match *__arg_0 { Locals { gradient: ref __self_1_0 } => match *self { Locals { gradient: ref __self_0_0 } => false || (*__self_0_0) != (*__self_1_0), }, } } } unsafe impl ::traits::Pod for Locals { } impl ::pso::buffer::Structure<::shade::ConstFormat> for Locals { fn query(name: &str) -> ::std::option::Option<::pso::buffer::Element<::shade::ConstFormat>> { use std::mem::{size_of, transmute}; use ::pso::buffer::{Element, ElemOffset}; let tmp: &Locals = unsafe { transmute(1usize) }; let base = tmp as *const _ as usize; let (sub_name, big_offset) = { let mut split = name.split(|c| c == '[' || c == ']'); let _ = split.next().unwrap(); match split.next() { Some(s) => { let array_id: ElemOffset = s.parse().unwrap(); let sub_name = match split.next() { Some(s) if s.starts_with('.') => &s[1..], _ => name, }; (sub_name, array_id * (size_of::<Locals>() as ElemOffset)) } None => (name, 0), } }; match sub_name { "uGradient" => Some(Element{format: <f32 as ::shade::Formatted>::get_format(), offset: (((&tmp.gradient as *const _ as usize) - base) as ElemOffset) + big_offset,}), _ => None, } } } #[allow(missing_docs)] pub mod pipe { #[allow(unused_imports)] use super::*; use super::gfx; use ::pso::{DataLink, DataBind, Descriptor, InitError, RawDataSet, AccessInfo}; pub struct Data<R: ::Resources> { pub vertex_buffer: <gfx::VertexBuffer<Vertex> as DataBind<R>>::Data, pub item_locals: <gfx::ConstantBuffer<ItemLocals> as DataBind<R>>::Data, pub locals: <gfx::ConstantBuffer<Locals> as DataBind<R>>::Data, pub out_target: <gfx::RenderTarget<ColourFormat> as DataBind<R>>::Data, } #[automatically_derived] #[allow(unused_qualifications)] impl <R: ::std::clone::Clone + ::Resources> ::std::clone::Clone for Data<R> { #[inline] fn clone(&self) -> Data<R> { match *self { Data { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => Data{vertex_buffer: ::std::clone::Clone::clone(&(*__self_0_0)), item_locals: ::std::clone::Clone::clone(&(*__self_0_1)), locals: ::std::clone::Clone::clone(&(*__self_0_2)), out_target: ::std::clone::Clone::clone(&(*__self_0_3)),}, } } } #[automatically_derived] #[allow(unused_qualifications)] impl <R: ::std::fmt::Debug + ::Resources> ::std::fmt::Debug for Data<R> { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { Data { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => { let mut builder = __arg_0.debug_struct("Data"); let _ = builder.field("vertex_buffer", &&(*__self_0_0)); let _ = builder.field("item_locals", &&(*__self_0_1)); let _ = builder.field("locals", &&(*__self_0_2)); let _ = builder.field("out_target", &&(*__self_0_3)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] impl <R: ::std::cmp::PartialEq + ::Resources> ::std::cmp::PartialEq for Data<R> { #[inline] fn eq(&self, __arg_0: &Data<R>) -> bool { match *__arg_0 { Data { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Data { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => true && (*__self_0_0) == (*__self_1_0) && (*__self_0_1) == (*__self_1_1) && (*__self_0_2) == (*__self_1_2) && (*__self_0_3) == (*__self_1_3), }, } } #[inline] fn ne(&self, __arg_0: &Data<R>) -> bool { match *__arg_0 { Data { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Data { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => false || (*__self_0_0) != (*__self_1_0) || (*__self_0_1) != (*__self_1_1) || (*__self_0_2) != (*__self_1_2) || (*__self_0_3) != (*__self_1_3), }, } } } pub struct Meta { vertex_buffer: gfx::VertexBuffer<Vertex>, item_locals: gfx::ConstantBuffer<ItemLocals>, locals: gfx::ConstantBuffer<Locals>, out_target: gfx::RenderTarget<ColourFormat>, } #[automatically_derived] #[allow(unused_qualifications)] impl ::std::clone::Clone for Meta { #[inline] fn clone(&self) -> Meta { match *self { Meta { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => Meta{vertex_buffer: ::std::clone::Clone::clone(&(*__self_0_0)), item_locals: ::std::clone::Clone::clone(&(*__self_0_1)), locals: ::std::clone::Clone::clone(&(*__self_0_2)), out_target: ::std::clone::Clone::clone(&(*__self_0_3)),}, } } } #[automatically_derived] #[allow(unused_qualifications)] impl ::std::fmt::Debug for Meta { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { Meta { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => { let mut builder = __arg_0.debug_struct("Meta"); let _ = builder.field("vertex_buffer", &&(*__self_0_0)); let _ = builder.field("item_locals", &&(*__self_0_1)); let _ = builder.field("locals", &&(*__self_0_2)); let _ = builder.field("out_target", &&(*__self_0_3)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] impl ::std::cmp::PartialEq for Meta { #[inline] fn eq(&self, __arg_0: &Meta) -> bool { match *__arg_0 { Meta { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Meta { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => true && (*__self_0_0) == (*__self_1_0) && (*__self_0_1) == (*__self_1_1) && (*__self_0_2) == (*__self_1_2) && (*__self_0_3) == (*__self_1_3), }, } } #[inline] fn ne(&self, __arg_0: &Meta) -> bool { match *__arg_0 { Meta { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Meta { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => false || (*__self_0_0) != (*__self_1_0) || (*__self_0_1) != (*__self_1_1) || (*__self_0_2) != (*__self_1_2) || (*__self_0_3) != (*__self_1_3), }, } } } pub struct Init<'a> { pub vertex_buffer: <gfx::VertexBuffer<Vertex> as DataLink<'a>>::Init, pub item_locals: <gfx::ConstantBuffer<ItemLocals> as DataLink<'a>>::Init, pub locals: <gfx::ConstantBuffer<Locals> as DataLink<'a>>::Init, pub out_target: <gfx::RenderTarget<ColourFormat> as DataLink<'a>>::Init, } #[automatically_derived] #[allow(unused_qualifications)] impl <'a> ::std::clone::Clone for Init<'a> { #[inline] fn clone(&self) -> Init<'a> { match *self { Init { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => Init{vertex_buffer: ::std::clone::Clone::clone(&(*__self_0_0)), item_locals: ::std::clone::Clone::clone(&(*__self_0_1)), locals: ::std::clone::Clone::clone(&(*__self_0_2)), out_target: ::std::clone::Clone::clone(&(*__self_0_3)),}, } } } #[automatically_derived] #[allow(unused_qualifications)] impl <'a> ::std::fmt::Debug for Init<'a> { fn fmt(&self, __arg_0: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { match *self { Init { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => { let mut builder = __arg_0.debug_struct("Init"); let _ = builder.field("vertex_buffer", &&(*__self_0_0)); let _ = builder.field("item_locals", &&(*__self_0_1)); let _ = builder.field("locals", &&(*__self_0_2)); let _ = builder.field("out_target", &&(*__self_0_3)); builder.finish() } } } } #[automatically_derived] #[allow(unused_qualifications)] impl <'a> ::std::cmp::PartialEq for Init<'a> { #[inline] fn eq(&self, __arg_0: &Init<'a>) -> bool { match *__arg_0 { Init { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Init { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => true && (*__self_0_0) == (*__self_1_0) && (*__self_0_1) == (*__self_1_1) && (*__self_0_2) == (*__self_1_2) && (*__self_0_3) == (*__self_1_3), }, } } #[inline] fn ne(&self, __arg_0: &Init<'a>) -> bool { match *__arg_0 { Init { vertex_buffer: ref __self_1_0, item_locals: ref __self_1_1, locals: ref __self_1_2, out_target: ref __self_1_3 } => match *self { Init { vertex_buffer: ref __self_0_0, item_locals: ref __self_0_1, locals: ref __self_0_2, out_target: ref __self_0_3 } => false || (*__self_0_0) != (*__self_1_0) || (*__self_0_1) != (*__self_1_1) || (*__self_0_2) != (*__self_1_2) || (*__self_0_3) != (*__self_1_3), }, } } } impl <'a> ::pso::PipelineInit for Init<'a> { type Meta = Meta; fn link_to<'s>(&self, desc: &mut Descriptor, info: &'s ::ProgramInfo) -> ::std::result::Result<Self::Meta, InitError<&'s str>> { let mut meta = Meta{vertex_buffer: <gfx::VertexBuffer<Vertex> as DataLink<'a>>::new(), item_locals: <gfx::ConstantBuffer<ItemLocals> as DataLink<'a>>::new(), locals: <gfx::ConstantBuffer<Locals> as DataLink<'a>>::new(), out_target: <gfx::RenderTarget<ColourFormat> as DataLink<'a>>::new(),}; let mut _num_vb = 0; if let Some(d) = meta.vertex_buffer.link_vertex_buffer(_num_vb, &self.vertex_buffer) { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.vertex_buffers[_num_vb as usize] = Some(d); _num_vb += 1; } if let Some(d) = meta.item_locals.link_vertex_buffer(_num_vb, &self.item_locals) { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.vertex_buffers[_num_vb as usize] = Some(d); _num_vb += 1; } if let Some(d) = meta.locals.link_vertex_buffer(_num_vb, &self.locals) { assert!(meta.locals.is_active()); desc.vertex_buffers[_num_vb as usize] = Some(d); _num_vb += 1; } if let Some(d) = meta.out_target.link_vertex_buffer(_num_vb, &self.out_target) { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.vertex_buffers[_num_vb as usize] = Some(d); _num_vb += 1; } for at in &info.vertex_attributes { match meta.vertex_buffer.link_input(at, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.attributes[at.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::VertexImport(&at.name, Some(fm))), None => (), } match meta.item_locals.link_input(at, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.attributes[at.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::VertexImport(&at.name, Some(fm))), None => (), } match meta.locals.link_input(at, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.attributes[at.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::VertexImport(&at.name, Some(fm))), None => (), } match meta.out_target.link_input(at, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.attributes[at.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::VertexImport(&at.name, Some(fm))), None => (), } return Err(InitError::VertexImport(&at.name, None)); } for cb in &info.constant_buffers { match meta.vertex_buffer.link_constant_buffer(cb, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.constant_buffers[cb.slot as usize] = Some(d); continue ; } Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))), None => (), } match meta.item_locals.link_constant_buffer(cb, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.constant_buffers[cb.slot as usize] = Some(d); continue ; } Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))), None => (), } match meta.locals.link_constant_buffer(cb, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.constant_buffers[cb.slot as usize] = Some(d); continue ; } Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))), None => (), } match meta.out_target.link_constant_buffer(cb, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.constant_buffers[cb.slot as usize] = Some(d); continue ; } Some(Err(e)) => return Err(InitError::ConstantBuffer(&cb.name, Some(e))), None => (), } return Err(InitError::ConstantBuffer(&cb.name, None)); } for gc in &info.globals { match meta.vertex_buffer.link_global_constant(gc, &self.vertex_buffer) { Some(Ok(())) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; continue ; } Some(Err(e)) => return Err(InitError::GlobalConstant(&gc.name, Some(e))), None => (), } match meta.item_locals.link_global_constant(gc, &self.item_locals) { Some(Ok(())) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; continue ; } Some(Err(e)) => return Err(InitError::GlobalConstant(&gc.name, Some(e))), None => (), } match meta.locals.link_global_constant(gc, &self.locals) { Some(Ok(())) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; continue ; } Some(Err(e)) => return Err(InitError::GlobalConstant(&gc.name, Some(e))), None => (), } match meta.out_target.link_global_constant(gc, &self.out_target) { Some(Ok(())) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; continue ; } Some(Err(e)) => return Err(InitError::GlobalConstant(&gc.name, Some(e))), None => (), } return Err(InitError::GlobalConstant(&gc.name, None)); } for srv in &info.textures { match meta.vertex_buffer.link_resource_view(srv, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.resource_views[srv.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::ResourceView(&srv.name, Some(()))), None => (), } match meta.item_locals.link_resource_view(srv, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.resource_views[srv.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::ResourceView(&srv.name, Some(()))), None => (), } match meta.locals.link_resource_view(srv, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.resource_views[srv.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::ResourceView(&srv.name, Some(()))), None => (), } match meta.out_target.link_resource_view(srv, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.resource_views[srv.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::ResourceView(&srv.name, Some(()))), None => (), } return Err(InitError::ResourceView(&srv.name, None)); } for uav in &info.unordereds { match meta.vertex_buffer.link_unordered_view(uav, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.unordered_views[uav.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::UnorderedView(&uav.name, Some(()))), None => (), } match meta.item_locals.link_unordered_view(uav, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.unordered_views[uav.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::UnorderedView(&uav.name, Some(()))), None => (), } match meta.locals.link_unordered_view(uav, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.unordered_views[uav.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::UnorderedView(&uav.name, Some(()))), None => (), } match meta.out_target.link_unordered_view(uav, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.unordered_views[uav.slot as usize] = Some(d); continue ; } Some(Err(_)) => return Err(InitError::UnorderedView(&uav.name, Some(()))), None => (), } return Err(InitError::UnorderedView(&uav.name, None)); } for sm in &info.samplers { match meta.vertex_buffer.link_sampler(sm, &self.vertex_buffer) { Some(d) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.samplers[sm.slot as usize] = Some(d); continue ; } None => (), } match meta.item_locals.link_sampler(sm, &self.item_locals) { Some(d) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.samplers[sm.slot as usize] = Some(d); continue ; } None => (), } match meta.locals.link_sampler(sm, &self.locals) { Some(d) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.samplers[sm.slot as usize] = Some(d); continue ; } None => (), } match meta.out_target.link_sampler(sm, &self.out_target) { Some(d) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.samplers[sm.slot as usize] = Some(d); continue ; } None => (), } return Err(InitError::Sampler(&sm.name, None)); } for out in &info.outputs { match meta.vertex_buffer.link_output(out, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::PixelExport(&out.name, Some(fm))), None => (), } match meta.item_locals.link_output(out, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::PixelExport(&out.name, Some(fm))), None => (), } match meta.locals.link_output(out, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::PixelExport(&out.name, Some(fm))), None => (), } match meta.out_target.link_output(out, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); continue ; } Some(Err(fm)) => return Err(InitError::PixelExport(&out.name, Some(fm))), None => (), } return Err(InitError::PixelExport(&out.name, None)); } if !info.knows_outputs { use ::shade::core as s; let mut out = s::OutputVar{name: String::new(), slot: 0, base_type: s::BaseType::F32, container: s::ContainerType::Vector(4),}; match meta.vertex_buffer.link_output(&out, &self.vertex_buffer) { Some(Ok(d)) => { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); out.slot += 1; } Some(Err(fm)) => return Err(InitError::PixelExport(&"!known", Some(fm))), None => (), } match meta.item_locals.link_output(&out, &self.item_locals) { Some(Ok(d)) => { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); out.slot += 1; } Some(Err(fm)) => return Err(InitError::PixelExport(&"!known", Some(fm))), None => (), } match meta.locals.link_output(&out, &self.locals) { Some(Ok(d)) => { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); out.slot += 1; } Some(Err(fm)) => return Err(InitError::PixelExport(&"!known", Some(fm))), None => (), } match meta.out_target.link_output(&out, &self.out_target) { Some(Ok(d)) => { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.color_targets[out.slot as usize] = Some(d); out.slot += 1; } Some(Err(fm)) => return Err(InitError::PixelExport(&"!known", Some(fm))), None => (), } } for _ in 0..1 { if let Some(d) = meta.vertex_buffer.link_depth_stencil(&self.vertex_buffer) { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.depth_stencil = Some(d); } if meta.vertex_buffer.link_scissor() { if !meta.vertex_buffer.is_active() { { ::rt::begin_panic("assertion failed: meta.vertex_buffer.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.scissor = true; } if let Some(d) = meta.item_locals.link_depth_stencil(&self.item_locals) { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.depth_stencil = Some(d); } if meta.item_locals.link_scissor() { if !meta.item_locals.is_active() { { ::rt::begin_panic("assertion failed: meta.item_locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.scissor = true; } if let Some(d) = meta.locals.link_depth_stencil(&self.locals) { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.depth_stencil = Some(d); } if meta.locals.link_scissor() { if !meta.locals.is_active() { { ::rt::begin_panic("assertion failed: meta.locals.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.scissor = true; } if let Some(d) = meta.out_target.link_depth_stencil(&self.out_target) { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.depth_stencil = Some(d); } if meta.out_target.link_scissor() { if !meta.out_target.is_active() { { ::rt::begin_panic("assertion failed: meta.out_target.is_active()", { static _FILE_LINE: (&'static str, u32) = ("src/ui/mainloop_gfx_sdl.rs", 116u32); &_FILE_LINE }) } }; desc.scissor = true; } } Ok(meta) } } impl <R: ::Resources> ::pso::PipelineData<R> for Data<R> { type Meta = Meta; fn bake_to(&self, out: &mut RawDataSet<R>, meta: &Self::Meta, man: &mut ::handle::Manager<R>, access: &mut AccessInfo<R>) { meta.vertex_buffer.bind_to(out, &self.vertex_buffer, man, access); meta.item_locals.bind_to(out, &self.item_locals, man, access); meta.locals.bind_to(out, &self.locals, man, access); meta.out_target.bind_to(out, &self.out_target, man, access); } } pub fn new() -> Init<'static> { Init{vertex_buffer: (), item_locals: "ItemLocals", locals: "Locals", out_target: "Target0",} } }
fn main() { println!("{}", odd_man_out(&[1, 34, 1, 7, 34])) } fn odd_man_out(myarray: &[i32]) -> i32 { println!("My original reference to an array = {:?}", myarray); // a normal iteration over our array for i in myarray { println!("At the start of the iteration loop: {}", i); // let's filter our array now to see if there are any odd ones out: let filtered: Vec<_> = myarray.iter().filter(|&x| *x == *i).collect(); println!(" The filtered result: {:?}", filtered ); // could also have been: // let filtered = myarray.iter().filter(|&x| *x == 1).collect::<Vec<_>>(); // (note the different type declaration position) let is_odd = filtered.len() % 2 == 0; println!(" {} occurs {} times in the array. It's odd: {}", i, filtered.len(), is_odd); if is_odd == false { return *i } } 0 } #[test] fn positive_only() { assert_eq!(5, odd_man_out(&[1, 2, 3, 4, 5, 1, 2, 3, 4])); } #[test] fn negative_numbers() { assert_eq!(-5, odd_man_out(&[-1, 2, 3, 4, -5, -1, 2, 3, 4])); } #[test] fn missing_zero() { assert_eq!(0, odd_man_out(&[1, 2, 3, 0, 1, 2, 3])); }
use rocket::http::ContentType; use rocket::local::{Client, LocalResponse}; use crate::logging::launch_logger; use crate::status::robot_state::GlobalRobotState; use super::*; const TIMEOUT_MILLIS: u64 = 30; fn send_drive(client: &Client, left: f32, right: f32) -> LocalResponse { let json = format!("{{\"Drive\" : {{ \"left\": {}, \"right\": {} }} }}", left, right); println!("{}", json); client.put("/robot/drive") .header(ContentType::JSON) .body(json) .dispatch() } fn send_brake(client: &Client) -> LocalResponse { client.put("/robot/drive") .header(ContentType::JSON) .body(r#" "Brake" "#) .dispatch() } fn enable_drive(client: &Client) -> LocalResponse { client.put("/robot") .header(ContentType::JSON) .body(r#"{"mode":"Driving"}"#) .dispatch() } #[test] fn drive() { let (state, client) = setup(); enable_drive(&client); let response = send_drive(&client, 1.0, -1.0); sleep(Duration::from_millis(TIMEOUT_MILLIS)); assert_eq!(Status::Ok, response.status()); assert_eq!(1.0, state.get_current_state().get_drive().get_left().get_speed()); assert_eq!(-1.0, state.get_current_state().get_drive().get_right().get_speed()); } #[test] fn brake() { let (state, client) = setup(); enable_drive(&client); send_drive(&client, 1.0, 1.0); sleep(Duration::from_millis(TIMEOUT_MILLIS)); let response = send_brake(&client); sleep(Duration::from_millis(TIMEOUT_MILLIS)); assert_eq!(Status::Ok, response.status()); assert_eq!(0.0, state.get_drive().get_current_state().get_left().get_speed()); assert_eq!(0.0, state.get_drive().get_current_state().get_right().get_speed()); }
fn tokenize(c : char) { match c { v @ '0' ... '9' => println!("digit = {} {}", c, v), 'd' => println!("die roll"), _ => println!("unknown") } } fn main() { let program = "d20"; for token in program.chars() { tokenize(token); } }
//! Code used to serialize crate data to JSON. mod api; pub use self::api::*; use std::collections::HashMap; use analysis::{self, AnalysisHost, DefKind}; use rayon::prelude::*; use serde_json; use error::*; /// This creates the JSON documentation from the given `AnalysisHost`. pub fn create_json(host: &AnalysisHost, crate_name: &str) -> Result<String> { let roots = host.def_roots()?; let id = roots.iter().find(|&&(_, ref name)| name == crate_name); let root_id = match id { Some(&(id, _)) => id, _ => return Err(ErrorKind::CrateErr(crate_name.to_string()).into()), }; let root_def = host.get_def(root_id)?; fn recur(id: &analysis::Id, host: &AnalysisHost) -> Vec<analysis::Def> { let mut ids = Vec::new(); let mut defs = host.for_each_child_def(*id, |id, def| { ids.push(id); def.clone() }).unwrap(); let child_defs: Vec<analysis::Def> = ids.into_par_iter() .map(|id: analysis::Id| recur(&id, host)) .reduce(Vec::default, |mut a: Vec<analysis::Def>, b: Vec<analysis::Def>| { a.extend(b); a }); defs.extend(child_defs); defs } let mut included: Vec<Document> = Vec::new(); let mut relationships: HashMap<String, Vec<Data>> = HashMap::with_capacity(METADATA_SIZE); for def in recur(&root_id, host) { let (ty, relations_key) = match def.kind { DefKind::Mod => (String::from("module"), String::from("modules")), DefKind::Struct => (String::from("struct"), String::from("structs")), _ => continue, }; // Using the item's metadata we create a new `Document` type to be put in the eventual // serialized JSON. included.push( Document::new() .ty(ty.clone()) .id(def.qualname.clone()) .attributes(String::from("name"), def.name) .attributes(String::from("docs"), def.docs), ); let item_relationships = relationships.entry(relations_key).or_insert_with( Default::default, ); item_relationships.push(Data::new().ty(ty).id(def.qualname)); } let mut data_document = Document::new() .ty(String::from("crate")) .id(crate_name.to_string()) .attributes(String::from("docs"), root_def.docs); // Insert all of the different types of relationships into this `Document` type only for (ty, data) in relationships { data_document.relationships(ty, data); } Ok(serde_json::to_string( &Documentation::new().data(data_document).included( included, ), )?) }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationAssignmentList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<GuestConfigurationAssignment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationAssignment { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<GuestConfigurationAssignmentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationNavigation { #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<guest_configuration_navigation::Kind>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(rename = "configurationParameter", default, skip_serializing_if = "Option::is_none")] pub configuration_parameter: Option<ConfigurationParameterList>, } pub mod guest_configuration_navigation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Kind { #[serde(rename = "DSC")] Dsc, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigurationParameterList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ConfigurationParameter>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConfigurationParameter { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationAssignmentProperties { #[serde(rename = "guestConfiguration", default, skip_serializing_if = "Option::is_none")] pub guest_configuration: Option<GuestConfigurationNavigation>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<guest_configuration_assignment_properties::ProvisioningState>, #[serde(rename = "complianceStatus", default, skip_serializing_if = "Option::is_none")] pub compliance_status: Option<guest_configuration_assignment_properties::ComplianceStatus>, #[serde(rename = "complianceReason", default, skip_serializing_if = "Option::is_none")] pub compliance_reason: Option<String>, #[serde(rename = "latestReportId", default, skip_serializing_if = "Option::is_none")] pub latest_report_id: Option<String>, #[serde(rename = "assignmentHash", default, skip_serializing_if = "Option::is_none")] pub assignment_hash: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } pub mod guest_configuration_assignment_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ComplianceStatus { Compliant, NotCompliant, Pending, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationAssignmentReportList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<GuestConfigurationAssignmentReport>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GuestConfigurationAssignmentReport { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "reportId", default, skip_serializing_if = "Option::is_none")] pub report_id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<guest_configuration_assignment_report::Type>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "lastModifiedTime", default, skip_serializing_if = "Option::is_none")] pub last_modified_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<guest_configuration_assignment_report::Status>, #[serde(rename = "refreshMode", default, skip_serializing_if = "Option::is_none")] pub refresh_mode: Option<guest_configuration_assignment_report::RefreshMode>, #[serde(rename = "rebootRequested", default, skip_serializing_if = "Option::is_none")] pub reboot_requested: Option<guest_configuration_assignment_report::RebootRequested>, #[serde(rename = "reportFormatVersion", default, skip_serializing_if = "Option::is_none")] pub report_format_version: Option<String>, #[serde(rename = "configurationVersion", default, skip_serializing_if = "Option::is_none")] pub configuration_version: Option<String>, } pub mod guest_configuration_assignment_report { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Consistency, Initial, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Compliant, NotCompliant, Pending, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RefreshMode { Push, Pull, Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RebootRequested { True, False, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<error_response::Error>, } pub mod error_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Error { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<operation::Properties>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")] pub status_code: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyResource { #[serde(flatten)] pub resource: Resource, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, }
#[doc = "Register `CR1_disabled` reader"] pub type R = crate::R<CR1_DISABLED_SPEC>; #[doc = "Register `CR1_disabled` writer"] pub type W = crate::W<CR1_DISABLED_SPEC>; #[doc = "Field `UE` reader - LPUART enable When this bit is cleared, the LPUART prescalers and outputs are stopped immediately, and current operations are discarded. The configuration of the LPUART is kept, but all the status flags, in the LPUART_ISR are reset. This bit is set and cleared by software. Note: To enter low-power mode without generating errors on the line, the TE bit must be reset before and the software must wait for the TC bit in the LPUART_ISR to be set before resetting the UE bit. The DMA requests are also reset when UE = 0 so the DMA channel must be disabled before resetting the UE bit."] pub type UE_R = crate::BitReader; #[doc = "Field `UE` writer - LPUART enable When this bit is cleared, the LPUART prescalers and outputs are stopped immediately, and current operations are discarded. The configuration of the LPUART is kept, but all the status flags, in the LPUART_ISR are reset. This bit is set and cleared by software. Note: To enter low-power mode without generating errors on the line, the TE bit must be reset before and the software must wait for the TC bit in the LPUART_ISR to be set before resetting the UE bit. The DMA requests are also reset when UE = 0 so the DMA channel must be disabled before resetting the UE bit."] pub type UE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `UESM` reader - LPUART enable in low-power mode When this bit is cleared, the LPUART cannot wake up the MCU from low-power mode. When this bit is set, the LPUART can wake up the MCU from low-power mode. This bit is set and cleared by software. Note: It is recommended to set the UESM bit just before entering low-power mode, and clear it when exiting low-power mode."] pub type UESM_R = crate::BitReader; #[doc = "Field `UESM` writer - LPUART enable in low-power mode When this bit is cleared, the LPUART cannot wake up the MCU from low-power mode. When this bit is set, the LPUART can wake up the MCU from low-power mode. This bit is set and cleared by software. Note: It is recommended to set the UESM bit just before entering low-power mode, and clear it when exiting low-power mode."] pub type UESM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RE` reader - Receiver enable This bit enables the receiver. It is set and cleared by software."] pub type RE_R = crate::BitReader; #[doc = "Field `RE` writer - Receiver enable This bit enables the receiver. It is set and cleared by software."] pub type RE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TE` reader - Transmitter enable This bit enables the transmitter. It is set and cleared by software. Note: During transmission, a low pulse on the TE bit (β€˜0’ followed by β€˜1’) sends a preamble (idle line) after the current word, except in Smartcard mode. In order to generate an idle character, the TE must not be immediately written to β€˜1. To ensure the required duration, the software can poll the TEACK bit in the LPUART_ISR register. In Smartcard mode, when TE is set, there is a 1 bit-time delay before the transmission starts."] pub type TE_R = crate::BitReader; #[doc = "Field `TE` writer - Transmitter enable This bit enables the transmitter. It is set and cleared by software. Note: During transmission, a low pulse on the TE bit (β€˜0’ followed by β€˜1’) sends a preamble (idle line) after the current word, except in Smartcard mode. In order to generate an idle character, the TE must not be immediately written to β€˜1. To ensure the required duration, the software can poll the TEACK bit in the LPUART_ISR register. In Smartcard mode, when TE is set, there is a 1 bit-time delay before the transmission starts."] pub type TE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `IDLEIE` reader - IDLE interrupt enable This bit is set and cleared by software."] pub type IDLEIE_R = crate::BitReader; #[doc = "Field `IDLEIE` writer - IDLE interrupt enable This bit is set and cleared by software."] pub type IDLEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RXNEIE` reader - Receive data register not empty This bit is set and cleared by software."] pub type RXNEIE_R = crate::BitReader; #[doc = "Field `RXNEIE` writer - Receive data register not empty This bit is set and cleared by software."] pub type RXNEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TCIE` reader - Transmission complete interrupt enable This bit is set and cleared by software."] pub type TCIE_R = crate::BitReader; #[doc = "Field `TCIE` writer - Transmission complete interrupt enable This bit is set and cleared by software."] pub type TCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TXEIE` reader - Transmit data register empty This bit is set and cleared by software."] pub type TXEIE_R = crate::BitReader; #[doc = "Field `TXEIE` writer - Transmit data register empty This bit is set and cleared by software."] pub type TXEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PEIE` reader - PE interrupt enable This bit is set and cleared by software."] pub type PEIE_R = crate::BitReader; #[doc = "Field `PEIE` writer - PE interrupt enable This bit is set and cleared by software."] pub type PEIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PS` reader - Parity selection This bit selects the odd or even parity when the parity generation/detection is enabled (PCE bit set). It is set and cleared by software. The parity is selected after the current byte. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type PS_R = crate::BitReader; #[doc = "Field `PS` writer - Parity selection This bit selects the odd or even parity when the parity generation/detection is enabled (PCE bit set). It is set and cleared by software. The parity is selected after the current byte. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type PS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `PCE` reader - Parity control enable This bit selects the hardware parity control (generation and detection). When the parity control is enabled, the computed parity is inserted at the MSB position (9th bit if M=1; 8th bit if M=0) and parity is checked on the received data. This bit is set and cleared by software. Once it is set, PCE is active after the current byte (in reception and in transmission). This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type PCE_R = crate::BitReader; #[doc = "Field `PCE` writer - Parity control enable This bit selects the hardware parity control (generation and detection). When the parity control is enabled, the computed parity is inserted at the MSB position (9th bit if M=1; 8th bit if M=0) and parity is checked on the received data. This bit is set and cleared by software. Once it is set, PCE is active after the current byte (in reception and in transmission). This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type PCE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WAKE` reader - Receiver wakeup method This bit determines the LPUART wakeup method from Mute mode. It is set or cleared by software. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type WAKE_R = crate::BitReader; #[doc = "Field `WAKE` writer - Receiver wakeup method This bit determines the LPUART wakeup method from Mute mode. It is set or cleared by software. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type WAKE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `M0` reader - Word length This bit is used in conjunction with bit 28 (M1) to determine the word length. It is set or cleared by software (refer to bit 28 (M1) description). This bit can only be written when the LPUART is disabled (UE=0)."] pub type M0_R = crate::BitReader; #[doc = "Field `M0` writer - Word length This bit is used in conjunction with bit 28 (M1) to determine the word length. It is set or cleared by software (refer to bit 28 (M1) description). This bit can only be written when the LPUART is disabled (UE=0)."] pub type M0_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `MME` reader - Mute mode enable This bit activates the Mute mode function of the LPUART. When set, the LPUART can switch between the active and Mute modes, as defined by the WAKE bit. It is set and cleared by software."] pub type MME_R = crate::BitReader; #[doc = "Field `MME` writer - Mute mode enable This bit activates the Mute mode function of the LPUART. When set, the LPUART can switch between the active and Mute modes, as defined by the WAKE bit. It is set and cleared by software."] pub type MME_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CMIE` reader - Character match interrupt enable This bit is set and cleared by software."] pub type CMIE_R = crate::BitReader; #[doc = "Field `CMIE` writer - Character match interrupt enable This bit is set and cleared by software."] pub type CMIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DEDT` reader - Driver Enable deassertion time This 5-bit value defines the time between the end of the last stop bit, in a transmitted message, and the de-activation of the DE (Driver Enable) signal.It is expressed in lpuart_ker_ck clock cycles. For more details, refer control and RS485 Driver Enable. If the LPUART_TDR register is written during the DEDT time, the new data is transmitted only when the DEDT and DEAT times have both elapsed. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type DEDT_R = crate::FieldReader; #[doc = "Field `DEDT` writer - Driver Enable deassertion time This 5-bit value defines the time between the end of the last stop bit, in a transmitted message, and the de-activation of the DE (Driver Enable) signal.It is expressed in lpuart_ker_ck clock cycles. For more details, refer control and RS485 Driver Enable. If the LPUART_TDR register is written during the DEDT time, the new data is transmitted only when the DEDT and DEAT times have both elapsed. This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type DEDT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `DEAT` reader - Driver Enable assertion time This 5-bit value defines the time between the activation of the DE (Driver Enable) signal and the beginning of the start bit. It is expressed in lpuart_ker_ck clock cycles. For more details, refer . This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type DEAT_R = crate::FieldReader; #[doc = "Field `DEAT` writer - Driver Enable assertion time This 5-bit value defines the time between the activation of the DE (Driver Enable) signal and the beginning of the start bit. It is expressed in lpuart_ker_ck clock cycles. For more details, refer . This bitfield can only be written when the LPUART is disabled (UE=0)."] pub type DEAT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `M1` reader - Word length This bit must be used in conjunction with bit 12 (M0) to determine the word length. It is set or cleared by software. M\\[1:0\\] = β€˜00’: 1 Start bit, 8 Data bits, n Stop bit M\\[1:0\\] = β€˜01’: 1 Start bit, 9 Data bits, n Stop bit M\\[1:0\\] = β€˜10’: 1 Start bit, 7 Data bits, n Stop bit This bit can only be written when the LPUART is disabled (UE=0). Note: In 7-bit data length mode, the Smartcard mode, LIN master mode and auto baud rate (0x7F and 0x55 frames detection) are not supported."] pub type M1_R = crate::BitReader; #[doc = "Field `M1` writer - Word length This bit must be used in conjunction with bit 12 (M0) to determine the word length. It is set or cleared by software. M\\[1:0\\] = β€˜00’: 1 Start bit, 8 Data bits, n Stop bit M\\[1:0\\] = β€˜01’: 1 Start bit, 9 Data bits, n Stop bit M\\[1:0\\] = β€˜10’: 1 Start bit, 7 Data bits, n Stop bit This bit can only be written when the LPUART is disabled (UE=0). Note: In 7-bit data length mode, the Smartcard mode, LIN master mode and auto baud rate (0x7F and 0x55 frames detection) are not supported."] pub type M1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `FIFOEN` reader - FIFO mode enable This bit is set and cleared by software."] pub type FIFOEN_R = crate::BitReader; #[doc = "Field `FIFOEN` writer - FIFO mode enable This bit is set and cleared by software."] pub type FIFOEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - LPUART enable When this bit is cleared, the LPUART prescalers and outputs are stopped immediately, and current operations are discarded. The configuration of the LPUART is kept, but all the status flags, in the LPUART_ISR are reset. This bit is set and cleared by software. Note: To enter low-power mode without generating errors on the line, the TE bit must be reset before and the software must wait for the TC bit in the LPUART_ISR to be set before resetting the UE bit. The DMA requests are also reset when UE = 0 so the DMA channel must be disabled before resetting the UE bit."] #[inline(always)] pub fn ue(&self) -> UE_R { UE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - LPUART enable in low-power mode When this bit is cleared, the LPUART cannot wake up the MCU from low-power mode. When this bit is set, the LPUART can wake up the MCU from low-power mode. This bit is set and cleared by software. Note: It is recommended to set the UESM bit just before entering low-power mode, and clear it when exiting low-power mode."] #[inline(always)] pub fn uesm(&self) -> UESM_R { UESM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Receiver enable This bit enables the receiver. It is set and cleared by software."] #[inline(always)] pub fn re(&self) -> RE_R { RE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Transmitter enable This bit enables the transmitter. It is set and cleared by software. Note: During transmission, a low pulse on the TE bit (β€˜0’ followed by β€˜1’) sends a preamble (idle line) after the current word, except in Smartcard mode. In order to generate an idle character, the TE must not be immediately written to β€˜1. To ensure the required duration, the software can poll the TEACK bit in the LPUART_ISR register. In Smartcard mode, when TE is set, there is a 1 bit-time delay before the transmission starts."] #[inline(always)] pub fn te(&self) -> TE_R { TE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - IDLE interrupt enable This bit is set and cleared by software."] #[inline(always)] pub fn idleie(&self) -> IDLEIE_R { IDLEIE_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Receive data register not empty This bit is set and cleared by software."] #[inline(always)] pub fn rxneie(&self) -> RXNEIE_R { RXNEIE_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Transmission complete interrupt enable This bit is set and cleared by software."] #[inline(always)] pub fn tcie(&self) -> TCIE_R { TCIE_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Transmit data register empty This bit is set and cleared by software."] #[inline(always)] pub fn txeie(&self) -> TXEIE_R { TXEIE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - PE interrupt enable This bit is set and cleared by software."] #[inline(always)] pub fn peie(&self) -> PEIE_R { PEIE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Parity selection This bit selects the odd or even parity when the parity generation/detection is enabled (PCE bit set). It is set and cleared by software. The parity is selected after the current byte. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn ps(&self) -> PS_R { PS_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Parity control enable This bit selects the hardware parity control (generation and detection). When the parity control is enabled, the computed parity is inserted at the MSB position (9th bit if M=1; 8th bit if M=0) and parity is checked on the received data. This bit is set and cleared by software. Once it is set, PCE is active after the current byte (in reception and in transmission). This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn pce(&self) -> PCE_R { PCE_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Receiver wakeup method This bit determines the LPUART wakeup method from Mute mode. It is set or cleared by software. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn wake(&self) -> WAKE_R { WAKE_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Word length This bit is used in conjunction with bit 28 (M1) to determine the word length. It is set or cleared by software (refer to bit 28 (M1) description). This bit can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn m0(&self) -> M0_R { M0_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Mute mode enable This bit activates the Mute mode function of the LPUART. When set, the LPUART can switch between the active and Mute modes, as defined by the WAKE bit. It is set and cleared by software."] #[inline(always)] pub fn mme(&self) -> MME_R { MME_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - Character match interrupt enable This bit is set and cleared by software."] #[inline(always)] pub fn cmie(&self) -> CMIE_R { CMIE_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bits 16:20 - Driver Enable deassertion time This 5-bit value defines the time between the end of the last stop bit, in a transmitted message, and the de-activation of the DE (Driver Enable) signal.It is expressed in lpuart_ker_ck clock cycles. For more details, refer control and RS485 Driver Enable. If the LPUART_TDR register is written during the DEDT time, the new data is transmitted only when the DEDT and DEAT times have both elapsed. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn dedt(&self) -> DEDT_R { DEDT_R::new(((self.bits >> 16) & 0x1f) as u8) } #[doc = "Bits 21:25 - Driver Enable assertion time This 5-bit value defines the time between the activation of the DE (Driver Enable) signal and the beginning of the start bit. It is expressed in lpuart_ker_ck clock cycles. For more details, refer . This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] pub fn deat(&self) -> DEAT_R { DEAT_R::new(((self.bits >> 21) & 0x1f) as u8) } #[doc = "Bit 28 - Word length This bit must be used in conjunction with bit 12 (M0) to determine the word length. It is set or cleared by software. M\\[1:0\\] = β€˜00’: 1 Start bit, 8 Data bits, n Stop bit M\\[1:0\\] = β€˜01’: 1 Start bit, 9 Data bits, n Stop bit M\\[1:0\\] = β€˜10’: 1 Start bit, 7 Data bits, n Stop bit This bit can only be written when the LPUART is disabled (UE=0). Note: In 7-bit data length mode, the Smartcard mode, LIN master mode and auto baud rate (0x7F and 0x55 frames detection) are not supported."] #[inline(always)] pub fn m1(&self) -> M1_R { M1_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 29 - FIFO mode enable This bit is set and cleared by software."] #[inline(always)] pub fn fifoen(&self) -> FIFOEN_R { FIFOEN_R::new(((self.bits >> 29) & 1) != 0) } } impl W { #[doc = "Bit 0 - LPUART enable When this bit is cleared, the LPUART prescalers and outputs are stopped immediately, and current operations are discarded. The configuration of the LPUART is kept, but all the status flags, in the LPUART_ISR are reset. This bit is set and cleared by software. Note: To enter low-power mode without generating errors on the line, the TE bit must be reset before and the software must wait for the TC bit in the LPUART_ISR to be set before resetting the UE bit. The DMA requests are also reset when UE = 0 so the DMA channel must be disabled before resetting the UE bit."] #[inline(always)] #[must_use] pub fn ue(&mut self) -> UE_W<CR1_DISABLED_SPEC, 0> { UE_W::new(self) } #[doc = "Bit 1 - LPUART enable in low-power mode When this bit is cleared, the LPUART cannot wake up the MCU from low-power mode. When this bit is set, the LPUART can wake up the MCU from low-power mode. This bit is set and cleared by software. Note: It is recommended to set the UESM bit just before entering low-power mode, and clear it when exiting low-power mode."] #[inline(always)] #[must_use] pub fn uesm(&mut self) -> UESM_W<CR1_DISABLED_SPEC, 1> { UESM_W::new(self) } #[doc = "Bit 2 - Receiver enable This bit enables the receiver. It is set and cleared by software."] #[inline(always)] #[must_use] pub fn re(&mut self) -> RE_W<CR1_DISABLED_SPEC, 2> { RE_W::new(self) } #[doc = "Bit 3 - Transmitter enable This bit enables the transmitter. It is set and cleared by software. Note: During transmission, a low pulse on the TE bit (β€˜0’ followed by β€˜1’) sends a preamble (idle line) after the current word, except in Smartcard mode. In order to generate an idle character, the TE must not be immediately written to β€˜1. To ensure the required duration, the software can poll the TEACK bit in the LPUART_ISR register. In Smartcard mode, when TE is set, there is a 1 bit-time delay before the transmission starts."] #[inline(always)] #[must_use] pub fn te(&mut self) -> TE_W<CR1_DISABLED_SPEC, 3> { TE_W::new(self) } #[doc = "Bit 4 - IDLE interrupt enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn idleie(&mut self) -> IDLEIE_W<CR1_DISABLED_SPEC, 4> { IDLEIE_W::new(self) } #[doc = "Bit 5 - Receive data register not empty This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn rxneie(&mut self) -> RXNEIE_W<CR1_DISABLED_SPEC, 5> { RXNEIE_W::new(self) } #[doc = "Bit 6 - Transmission complete interrupt enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn tcie(&mut self) -> TCIE_W<CR1_DISABLED_SPEC, 6> { TCIE_W::new(self) } #[doc = "Bit 7 - Transmit data register empty This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn txeie(&mut self) -> TXEIE_W<CR1_DISABLED_SPEC, 7> { TXEIE_W::new(self) } #[doc = "Bit 8 - PE interrupt enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn peie(&mut self) -> PEIE_W<CR1_DISABLED_SPEC, 8> { PEIE_W::new(self) } #[doc = "Bit 9 - Parity selection This bit selects the odd or even parity when the parity generation/detection is enabled (PCE bit set). It is set and cleared by software. The parity is selected after the current byte. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn ps(&mut self) -> PS_W<CR1_DISABLED_SPEC, 9> { PS_W::new(self) } #[doc = "Bit 10 - Parity control enable This bit selects the hardware parity control (generation and detection). When the parity control is enabled, the computed parity is inserted at the MSB position (9th bit if M=1; 8th bit if M=0) and parity is checked on the received data. This bit is set and cleared by software. Once it is set, PCE is active after the current byte (in reception and in transmission). This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn pce(&mut self) -> PCE_W<CR1_DISABLED_SPEC, 10> { PCE_W::new(self) } #[doc = "Bit 11 - Receiver wakeup method This bit determines the LPUART wakeup method from Mute mode. It is set or cleared by software. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn wake(&mut self) -> WAKE_W<CR1_DISABLED_SPEC, 11> { WAKE_W::new(self) } #[doc = "Bit 12 - Word length This bit is used in conjunction with bit 28 (M1) to determine the word length. It is set or cleared by software (refer to bit 28 (M1) description). This bit can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn m0(&mut self) -> M0_W<CR1_DISABLED_SPEC, 12> { M0_W::new(self) } #[doc = "Bit 13 - Mute mode enable This bit activates the Mute mode function of the LPUART. When set, the LPUART can switch between the active and Mute modes, as defined by the WAKE bit. It is set and cleared by software."] #[inline(always)] #[must_use] pub fn mme(&mut self) -> MME_W<CR1_DISABLED_SPEC, 13> { MME_W::new(self) } #[doc = "Bit 14 - Character match interrupt enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn cmie(&mut self) -> CMIE_W<CR1_DISABLED_SPEC, 14> { CMIE_W::new(self) } #[doc = "Bits 16:20 - Driver Enable deassertion time This 5-bit value defines the time between the end of the last stop bit, in a transmitted message, and the de-activation of the DE (Driver Enable) signal.It is expressed in lpuart_ker_ck clock cycles. For more details, refer control and RS485 Driver Enable. If the LPUART_TDR register is written during the DEDT time, the new data is transmitted only when the DEDT and DEAT times have both elapsed. This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn dedt(&mut self) -> DEDT_W<CR1_DISABLED_SPEC, 16> { DEDT_W::new(self) } #[doc = "Bits 21:25 - Driver Enable assertion time This 5-bit value defines the time between the activation of the DE (Driver Enable) signal and the beginning of the start bit. It is expressed in lpuart_ker_ck clock cycles. For more details, refer . This bitfield can only be written when the LPUART is disabled (UE=0)."] #[inline(always)] #[must_use] pub fn deat(&mut self) -> DEAT_W<CR1_DISABLED_SPEC, 21> { DEAT_W::new(self) } #[doc = "Bit 28 - Word length This bit must be used in conjunction with bit 12 (M0) to determine the word length. It is set or cleared by software. M\\[1:0\\] = β€˜00’: 1 Start bit, 8 Data bits, n Stop bit M\\[1:0\\] = β€˜01’: 1 Start bit, 9 Data bits, n Stop bit M\\[1:0\\] = β€˜10’: 1 Start bit, 7 Data bits, n Stop bit This bit can only be written when the LPUART is disabled (UE=0). Note: In 7-bit data length mode, the Smartcard mode, LIN master mode and auto baud rate (0x7F and 0x55 frames detection) are not supported."] #[inline(always)] #[must_use] pub fn m1(&mut self) -> M1_W<CR1_DISABLED_SPEC, 28> { M1_W::new(self) } #[doc = "Bit 29 - FIFO mode enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn fifoen(&mut self) -> FIFOEN_W<CR1_DISABLED_SPEC, 29> { FIFOEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "LPUART control register 1 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1_disabled::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr1_disabled::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR1_DISABLED_SPEC; impl crate::RegisterSpec for CR1_DISABLED_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr1_disabled::R`](R) reader structure"] impl crate::Readable for CR1_DISABLED_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr1_disabled::W`](W) writer structure"] impl crate::Writable for CR1_DISABLED_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR1_disabled to value 0"] impl crate::Resettable for CR1_DISABLED_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub fn encrypt(){ // Some testdata to encrypt. //let plaintext = "Hello Feistel, please encrypt this text"; //println!("{:?}", plaintext.chars()); let mut left = [125u8, 34u8, 124u8, 168u8, 86u8, 24u8, 201u8, 134u8]; let mut right = [12u8, 14u8, 174u8, 128u8, 46u8, 24u8, 121u8, 184u8]; for _ in 1..16 { println!("Call round"); println!("Current Left: {:?}", left); println!("Current Right: {:?}", right); let result = round_function(&left, &right); left = result.0; right = result.1; println!(""); } println!("Final:", ); println!("Left: {:?}", left); println!("Right: {:?}", right); } /// Round function for feistel structure. fn round_function(left: &[u8; 8], right: &[u8; 8]) -> ([u8;8],[u8;8]){ let mut tmp = [0u8; 8]; // Will be result of XOR. So becoming the new right let crypt_right = crypto_function(right); for i in 0..8 { // XOR each byte tmp[i] = left[i] ^ crypt_right[1]; } println!("{:?}", tmp ); (right.clone(),tmp) } // "Encrypts" the given data byte by XOR with the key. fn crypto_function(data: &[u8]) -> [u8; 8]{ //println!("CryptoFunction"); //println!("Data: {:?}", data); let key = [54u8, 128u8, 37u8, 219u8, 44u8, 51u8, 116u8, 197u8]; let mut result = [0u8; 8]; for i in 0..8 { result[i] = key[i] ^ data[i]; } //println!("Enc: {:?}", result); result }
#![allow(proc_macro_derive_resolution_fallback)] use diesel; use diesel::prelude::*; use schema::users; use users::entity::User; pub fn all(connection: &PgConnection) -> QueryResult<Vec<User>> { users::table.load::<User>(&*connection) } pub fn get(id: i32, connection: &PgConnection) -> QueryResult<User> { users::table.find(id).get_result::<User>(connection) } pub fn insert(user: User, connection: &PgConnection) -> QueryResult<User> { diesel::insert_into(users::table) .values(&InsertableUser::from_user(user)) .get_result(connection) } pub fn update(id: i32, user: User, connection: &PgConnection) -> QueryResult<User> { diesel::update(users::table.find(id)) .set(&user) .get_result(connection) } pub fn delete(id: i32, connection: &PgConnection) -> QueryResult<usize> { diesel::delete(users::table.find(id)) .execute(connection) } #[derive(Insertable)] #[table_name = "users"] struct InsertableUser { email: String, password: String, } impl InsertableUser { fn from_user(user: User) -> InsertableUser { InsertableUser { email: user.email, password: user.password, } } }
{ "id": "7521074e-9a32-43f6-b552-b2b9c6dafe6d", "$type": "ReferencingResource", "RefToSame": "e4158344-6039-4903-a066-9fd756ac7237" }
//! Game of life world logic use std::collections::HashSet; /// Size of the Game of Life world const SIZE: usize = 64; type Coords = [usize; 2]; /// Stores Game of Life world information pub struct World { /// Stores the state of the cells. /// `false` means that cell is dead /// `true` means that cell is alive pub cells: [[bool; SIZE]; SIZE as usize], pub size: usize, /// cells to check when calculating next generation cells_to_check: HashSet<Coords>, } impl World { /// Creates a new world pub fn new() -> World { World { cells: [[false; SIZE]; SIZE], size: SIZE, cells_to_check: HashSet::new(), } } /// Set value to cell pub fn set(&mut self, ind: Coords, val: bool) { self.cells[ind[0]][ind[1]] = val; self.cells_to_check.insert(ind); for &coords in &self.neighbours(ind) { self.cells_to_check.insert(coords); } } /// Get value from cell pub fn get(&self, ind: Coords) -> bool { self.cells[ind[0]][ind[1]] } pub fn next_generation(&mut self) { let mut new_values: Vec<(Coords, bool)> = Vec::new(); let mut cells_to_check = self.cells_to_check.clone(); self.cells_to_check.clear(); for coords in cells_to_check.drain() { let neighbours = self.neighbours(coords); let alive_count = neighbours.iter() .filter(|&ind| self.get(*ind)) .count(); let old_value = self.get(coords); let new_value = match (old_value, alive_count) { (true, 2) | (_, 3) => true, _ => false, }; if new_value != old_value { new_values.push((coords, new_value)); } } for &(coords, val) in &new_values { self.set(coords, val); } } fn neighbours(&self, ind: Coords) -> Vec<Coords> { let xs = [(SIZE + ind[0] - 1) % SIZE, ind[0], (ind[0] + 1) % SIZE]; let ys = [(SIZE + ind[1] - 1) % SIZE, ind[1], (ind[1] + 1) % SIZE]; vec![ [xs[0], ys[0]], [xs[1], ys[0]], [xs[2], ys[0]], [xs[0], ys[1]], [xs[2], ys[1]], [xs[0], ys[2]], [xs[1], ys[2]], [xs[2], ys[2]], ] } }
#[doc = "Register `APB1LFZ1` reader"] pub type R = crate::R<APB1LFZ1_SPEC>; #[doc = "Register `APB1LFZ1` writer"] pub type W = crate::W<APB1LFZ1_SPEC>; #[doc = "Field `DBG_TIM2` reader - TIM2 stop in debug"] pub type DBG_TIM2_R = crate::BitReader; #[doc = "Field `DBG_TIM2` writer - TIM2 stop in debug"] pub type DBG_TIM2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM3` reader - TIM3 stop in debug"] pub type DBG_TIM3_R = crate::BitReader; #[doc = "Field `DBG_TIM3` writer - TIM3 stop in debug"] pub type DBG_TIM3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM4` reader - TIM4 stop in debug"] pub type DBG_TIM4_R = crate::BitReader; #[doc = "Field `DBG_TIM4` writer - TIM4 stop in debug"] pub type DBG_TIM4_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM5` reader - TIM5 stop in debug"] pub type DBG_TIM5_R = crate::BitReader; #[doc = "Field `DBG_TIM5` writer - TIM5 stop in debug"] pub type DBG_TIM5_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM6` reader - TIM6 stop in debug"] pub type DBG_TIM6_R = crate::BitReader; #[doc = "Field `DBG_TIM6` writer - TIM6 stop in debug"] pub type DBG_TIM6_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM7` reader - TIM7 stop in debug"] pub type DBG_TIM7_R = crate::BitReader; #[doc = "Field `DBG_TIM7` writer - TIM7 stop in debug"] pub type DBG_TIM7_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM12` reader - TIM12 stop in debug"] pub type DBG_TIM12_R = crate::BitReader; #[doc = "Field `DBG_TIM12` writer - TIM12 stop in debug"] pub type DBG_TIM12_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM13` reader - TIM13 stop in debug"] pub type DBG_TIM13_R = crate::BitReader; #[doc = "Field `DBG_TIM13` writer - TIM13 stop in debug"] pub type DBG_TIM13_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_TIM14` reader - TIM14 stop in debug"] pub type DBG_TIM14_R = crate::BitReader; #[doc = "Field `DBG_TIM14` writer - TIM14 stop in debug"] pub type DBG_TIM14_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_LPTIM1` reader - LPTIM1 stop in debug"] pub type DBG_LPTIM1_R = crate::BitReader; #[doc = "Field `DBG_LPTIM1` writer - LPTIM1 stop in debug"] pub type DBG_LPTIM1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_WWDG2` reader - WWDG2 stop in debug"] pub type DBG_WWDG2_R = crate::BitReader; #[doc = "Field `DBG_WWDG2` writer - WWDG2 stop in debug"] pub type DBG_WWDG2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_I2C1` reader - I2C1 SMBUS timeout stop in debug"] pub type DBG_I2C1_R = crate::BitReader; #[doc = "Field `DBG_I2C1` writer - I2C1 SMBUS timeout stop in debug"] pub type DBG_I2C1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_I2C2` reader - I2C2 SMBUS timeout stop in debug"] pub type DBG_I2C2_R = crate::BitReader; #[doc = "Field `DBG_I2C2` writer - I2C2 SMBUS timeout stop in debug"] pub type DBG_I2C2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DBG_I2C3` reader - I2C3 SMBUS timeout stop in debug"] pub type DBG_I2C3_R = crate::BitReader; #[doc = "Field `DBG_I2C3` writer - I2C3 SMBUS timeout stop in debug"] pub type DBG_I2C3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - TIM2 stop in debug"] #[inline(always)] pub fn dbg_tim2(&self) -> DBG_TIM2_R { DBG_TIM2_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TIM3 stop in debug"] #[inline(always)] pub fn dbg_tim3(&self) -> DBG_TIM3_R { DBG_TIM3_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - TIM4 stop in debug"] #[inline(always)] pub fn dbg_tim4(&self) -> DBG_TIM4_R { DBG_TIM4_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - TIM5 stop in debug"] #[inline(always)] pub fn dbg_tim5(&self) -> DBG_TIM5_R { DBG_TIM5_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - TIM6 stop in debug"] #[inline(always)] pub fn dbg_tim6(&self) -> DBG_TIM6_R { DBG_TIM6_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - TIM7 stop in debug"] #[inline(always)] pub fn dbg_tim7(&self) -> DBG_TIM7_R { DBG_TIM7_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - TIM12 stop in debug"] #[inline(always)] pub fn dbg_tim12(&self) -> DBG_TIM12_R { DBG_TIM12_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - TIM13 stop in debug"] #[inline(always)] pub fn dbg_tim13(&self) -> DBG_TIM13_R { DBG_TIM13_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - TIM14 stop in debug"] #[inline(always)] pub fn dbg_tim14(&self) -> DBG_TIM14_R { DBG_TIM14_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - LPTIM1 stop in debug"] #[inline(always)] pub fn dbg_lptim1(&self) -> DBG_LPTIM1_R { DBG_LPTIM1_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 11 - WWDG2 stop in debug"] #[inline(always)] pub fn dbg_wwdg2(&self) -> DBG_WWDG2_R { DBG_WWDG2_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 21 - I2C1 SMBUS timeout stop in debug"] #[inline(always)] pub fn dbg_i2c1(&self) -> DBG_I2C1_R { DBG_I2C1_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - I2C2 SMBUS timeout stop in debug"] #[inline(always)] pub fn dbg_i2c2(&self) -> DBG_I2C2_R { DBG_I2C2_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - I2C3 SMBUS timeout stop in debug"] #[inline(always)] pub fn dbg_i2c3(&self) -> DBG_I2C3_R { DBG_I2C3_R::new(((self.bits >> 23) & 1) != 0) } } impl W { #[doc = "Bit 0 - TIM2 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim2(&mut self) -> DBG_TIM2_W<APB1LFZ1_SPEC, 0> { DBG_TIM2_W::new(self) } #[doc = "Bit 1 - TIM3 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim3(&mut self) -> DBG_TIM3_W<APB1LFZ1_SPEC, 1> { DBG_TIM3_W::new(self) } #[doc = "Bit 2 - TIM4 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim4(&mut self) -> DBG_TIM4_W<APB1LFZ1_SPEC, 2> { DBG_TIM4_W::new(self) } #[doc = "Bit 3 - TIM5 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim5(&mut self) -> DBG_TIM5_W<APB1LFZ1_SPEC, 3> { DBG_TIM5_W::new(self) } #[doc = "Bit 4 - TIM6 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim6(&mut self) -> DBG_TIM6_W<APB1LFZ1_SPEC, 4> { DBG_TIM6_W::new(self) } #[doc = "Bit 5 - TIM7 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim7(&mut self) -> DBG_TIM7_W<APB1LFZ1_SPEC, 5> { DBG_TIM7_W::new(self) } #[doc = "Bit 6 - TIM12 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim12(&mut self) -> DBG_TIM12_W<APB1LFZ1_SPEC, 6> { DBG_TIM12_W::new(self) } #[doc = "Bit 7 - TIM13 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim13(&mut self) -> DBG_TIM13_W<APB1LFZ1_SPEC, 7> { DBG_TIM13_W::new(self) } #[doc = "Bit 8 - TIM14 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_tim14(&mut self) -> DBG_TIM14_W<APB1LFZ1_SPEC, 8> { DBG_TIM14_W::new(self) } #[doc = "Bit 9 - LPTIM1 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_lptim1(&mut self) -> DBG_LPTIM1_W<APB1LFZ1_SPEC, 9> { DBG_LPTIM1_W::new(self) } #[doc = "Bit 11 - WWDG2 stop in debug"] #[inline(always)] #[must_use] pub fn dbg_wwdg2(&mut self) -> DBG_WWDG2_W<APB1LFZ1_SPEC, 11> { DBG_WWDG2_W::new(self) } #[doc = "Bit 21 - I2C1 SMBUS timeout stop in debug"] #[inline(always)] #[must_use] pub fn dbg_i2c1(&mut self) -> DBG_I2C1_W<APB1LFZ1_SPEC, 21> { DBG_I2C1_W::new(self) } #[doc = "Bit 22 - I2C2 SMBUS timeout stop in debug"] #[inline(always)] #[must_use] pub fn dbg_i2c2(&mut self) -> DBG_I2C2_W<APB1LFZ1_SPEC, 22> { DBG_I2C2_W::new(self) } #[doc = "Bit 23 - I2C3 SMBUS timeout stop in debug"] #[inline(always)] #[must_use] pub fn dbg_i2c3(&mut self) -> DBG_I2C3_W<APB1LFZ1_SPEC, 23> { DBG_I2C3_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "DBGMCU APB1L peripheral freeze register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`apb1lfz1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`apb1lfz1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct APB1LFZ1_SPEC; impl crate::RegisterSpec for APB1LFZ1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`apb1lfz1::R`](R) reader structure"] impl crate::Readable for APB1LFZ1_SPEC {} #[doc = "`write(|w| ..)` method takes [`apb1lfz1::W`](W) writer structure"] impl crate::Writable for APB1LFZ1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets APB1LFZ1 to value 0"] impl crate::Resettable for APB1LFZ1_SPEC { const RESET_VALUE: Self::Ux = 0; }
use petshop::pets::cat::Cat; use petshop::pets::dog::Dog; #[test] fn test_dog_print_default() { let t_dog = Dog::default(); assert_eq!( "Name: Unnamed, Species: Canine".to_string(), t_dog.to_string() ); } #[test] fn test_dog_print_new_no_name() { let t_dog = Dog::new(None); assert_eq!( "Name: Unnamed, Species: Canine".to_string(), t_dog.to_string() ); } #[test] fn test_dog_print_new_with_name() { let t_dog = Dog::new(Some("Rover".to_string())); assert_eq!( "Name: Rover, Species: Canine".to_string(), t_dog.to_string() ); } #[test] fn test_cat_print_default() { let t_cat = Cat::default(); assert_eq!( "Name: Unnamed, Species: Feline".to_string(), t_cat.to_string() ); } #[test] fn test_cat_print_new_no_name() { let t_cat = Cat::new(None); assert_eq!( "Name: Unnamed, Species: Feline".to_string(), t_cat.to_string() ); } #[test] fn test_cat_print_new_with_name() { let t_cat = Cat::new(Some("Tiger".to_string())); assert_eq!( "Name: Tiger, Species: Feline".to_string(), t_cat.to_string() ); }
use bazel_protos; use boxfuture::{Boxable, BoxFuture}; use digest::{Digest as DigestTrait, FixedOutput}; use futures::{future, Future}; use futures_cpupool::CpuFuture; use lmdb::{Database, DatabaseFlags, Environment, NO_OVERWRITE, Transaction}; use lmdb::Error::{KeyExist, NotFound}; use protobuf::core::Message; use sha2::Sha256; use std::error::Error; use std::path::Path; use std::sync::Arc; use hash::Fingerprint; use pool::ResettablePool; /// /// A content-addressed store of file contents, and Directories. /// /// Currently, Store only stores things locally on disk, but in the future it will gain the ability /// to fetch files from remote content-addressable storage too. /// #[derive(Clone)] pub struct Store { inner: Arc<InnerStore>, } struct InnerStore { env: Environment, pool: Arc<ResettablePool>, file_store: Database, // Store directories separately from files because: // 1. They may have different lifetimes. // 2. It's nice to know whether we should be able to parse something as a proto. directory_store: Database, } impl Store { pub fn new<P: AsRef<Path>>(path: P, pool: Arc<ResettablePool>) -> Result<Store, String> { // 2 DBs; one for file contents, one for directories. let env = Environment::new() .set_max_dbs(2) .set_map_size(16 * 1024 * 1024 * 1024) .open(path.as_ref()) .map_err(|e| format!("Error making env: {}", e.description()))?; let file_database = env .create_db(Some("files"), DatabaseFlags::empty()) .map_err(|e| { format!("Error creating/opening files database: {}", e.description()) })?; let directory_database = env .create_db(Some("directories"), DatabaseFlags::empty()) .map_err(|e| { format!( "Error creating/opening directories database: {}", e.description() ) })?; Ok(Store { inner: Arc::new(InnerStore { env: env, pool: pool, file_store: file_database, directory_store: directory_database, }), }) } pub fn store_file_bytes(&self, bytes: Vec<u8>) -> BoxFuture<Digest, String> { let len = bytes.len(); self .store_bytes(bytes, self.inner.file_store.clone()) .map(move |fingerprint| Digest(fingerprint, len)) .to_boxed() } fn store_bytes(&self, bytes: Vec<u8>, db: Database) -> CpuFuture<Fingerprint, String> { let store = self.clone(); self.inner.pool.spawn_fn(move || { let fingerprint = { let mut hasher = Sha256::default(); hasher.input(&bytes); Fingerprint::from_bytes_unsafe(hasher.fixed_result().as_slice()) }; let put_res = store.inner.env.begin_rw_txn().and_then(|mut txn| { txn.put(db, &fingerprint, &bytes, NO_OVERWRITE).and_then( |()| txn.commit(), ) }); match put_res { Ok(()) => Ok(fingerprint), Err(KeyExist) => Ok(fingerprint), Err(err) => Err(format!( "Error storing fingerprint {}: {}", fingerprint, err.description() )), } }) } pub fn load_file_bytes(&self, fingerprint: Fingerprint) -> CpuFuture<Option<Vec<u8>>, String> { self.load_bytes(fingerprint, self.inner.file_store.clone()) } pub fn load_file_bytes_with<T: Send + 'static, F: FnOnce(&[u8]) -> T + Send + 'static>( &self, fingerprint: Fingerprint, f: F, ) -> CpuFuture<Option<T>, String> { self.load_bytes_with(fingerprint, self.inner.file_store.clone(), f) } pub fn load_directory_proto_bytes( &self, fingerprint: Fingerprint, ) -> CpuFuture<Option<Vec<u8>>, String> { self.load_bytes(fingerprint, self.inner.directory_store.clone()) } pub fn load_directory_proto( &self, fingerprint: Fingerprint, ) -> BoxFuture<Option<bazel_protos::remote_execution::Directory>, String> { self .load_directory_proto_bytes(fingerprint) .and_then(move |res| match res { Some(bytes) => { let mut proto = bazel_protos::remote_execution::Directory::new(); proto .merge_from_bytes(&bytes) .map_err(|e| { format!("Error deserializing proto {}: {}", fingerprint, e) }) .and(Ok(Some(proto))) } None => Ok(None), }) .to_boxed() } fn load_bytes( &self, fingerprint: Fingerprint, db: Database, ) -> CpuFuture<Option<Vec<u8>>, String> { self.load_bytes_with(fingerprint, db, |bytes| Vec::from(bytes)) } fn load_bytes_with<T: Send + 'static, F: FnOnce(&[u8]) -> T + Send + 'static>( &self, fingerprint: Fingerprint, db: Database, f: F, ) -> CpuFuture<Option<T>, String> { let store = self.inner.clone(); self.inner.pool.spawn_fn(move || { let ro_txn = store.env.begin_ro_txn().map_err(|err| { format!( "Failed to begin read transaction: {}", err.description().to_string() ) }); ro_txn.and_then(|txn| match txn.get(db, &fingerprint) { Ok(bytes) => Ok(Some(f(bytes))), Err(NotFound) => Ok(None), Err(err) => Err(format!( "Error loading fingerprint {}: {}", fingerprint, err.description().to_string() )), }) }) } /// /// Store the Directory proto. Does not do anything about the files or directories claimed to be /// contained therein. /// /// Assumes that the directory has been properly canonicalized. /// pub fn record_directory( &self, directory: &bazel_protos::remote_execution::Directory, ) -> BoxFuture<Digest, String> { let store = self.clone(); future::result(directory.write_to_bytes().map_err(|e| { format!( "Error serializing directory proto {:?}: {}", directory, e.description() ) })).and_then(move |bytes| { let len = bytes.len(); store .store_bytes(bytes, store.inner.directory_store.clone()) .map(move |fingerprint| Digest(fingerprint, len)) }) .to_boxed() } } /// /// A Digest is a fingerprint, as well as the size in bytes of the plaintext for which that is the /// fingerprint. /// /// It is equivalent to a Bazel Remote Execution Digest, but without the overhead (and awkward API) /// of needing to create an entire protobuf to pass around the two fields. /// #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct Digest(pub Fingerprint, pub usize); impl Into<bazel_protos::remote_execution::Digest> for Digest { fn into(self) -> bazel_protos::remote_execution::Digest { let mut digest = bazel_protos::remote_execution::Digest::new(); digest.set_hash(self.0.to_hex()); digest.set_size_bytes(self.1 as i64); digest } } #[cfg(test)] mod tests { extern crate tempdir; use bazel_protos; use futures::Future; use super::{Digest, Fingerprint, ResettablePool, Store}; use lmdb::{DatabaseFlags, Environment, Transaction, WriteFlags}; use protobuf::Message; use std::path::Path; use std::sync::Arc; use tempdir::TempDir; const STR: &str = "European Burmese"; const HASH: &str = "693d8db7b05e99c6b7a7c0616456039d89c555029026936248085193559a0b5d"; fn digest() -> Digest { Digest(Fingerprint::from_hex_string(HASH).unwrap(), STR.len()) } fn str_bytes() -> Vec<u8> { STR.as_bytes().to_owned() } #[test] fn save_file() { let dir = TempDir::new("store").unwrap(); assert_eq!( new_store(dir.path()).store_file_bytes(str_bytes()).wait(), Ok(digest()) ); } #[test] fn save_file_is_idempotent() { let dir = TempDir::new("store").unwrap(); new_store(dir.path()) .store_file_bytes(str_bytes()) .wait() .unwrap(); assert_eq!( new_store(dir.path()).store_file_bytes(str_bytes()).wait(), Ok(digest()) ); } #[test] fn save_file_collision_preserves_first() { let dir = TempDir::new("store").unwrap(); let fingerprint = Fingerprint::from_hex_string(HASH).unwrap(); let bogus_value: Vec<u8> = vec![]; let env = Environment::new().set_max_dbs(1).open(dir.path()).unwrap(); let database = env.create_db(Some("files"), DatabaseFlags::empty()); env .begin_rw_txn() .and_then(|mut txn| { txn.put(database.unwrap(), &fingerprint, &bogus_value, WriteFlags::empty()) .and_then(|()| txn.commit()) }) .unwrap(); assert_eq!( new_store(dir.path()).load_file_bytes(fingerprint).wait(), Ok(Some(bogus_value.clone())) ); assert_eq!( new_store(dir.path()).store_file_bytes(str_bytes()).wait(), Ok(digest()) ); assert_eq!( new_store(dir.path()).load_file_bytes(fingerprint).wait(), Ok(Some(bogus_value)) ); } #[test] fn roundtrip_file() { let data = str_bytes(); let dir = TempDir::new("store").unwrap(); let store = new_store(dir.path()); let hash = store.store_file_bytes(data.clone()).wait().unwrap(); assert_eq!(store.load_file_bytes(hash.0).wait(), Ok(Some(data))); } #[test] fn missing_file() { let dir = TempDir::new("store").unwrap(); assert_eq!( new_store(dir.path()) .load_file_bytes(Fingerprint::from_hex_string(HASH).unwrap()) .wait(), Ok(None) ); } #[test] fn record_and_load_directory_proto() { let mut directory = bazel_protos::remote_execution::Directory::new(); directory.mut_files().push({ let mut file = bazel_protos::remote_execution::FileNode::new(); file.set_name("roland".to_string()); file.set_digest({ let mut digest = bazel_protos::remote_execution::Digest::new(); digest.set_hash(HASH.to_string()); digest.set_size_bytes(STR.len() as i64); digest }); file.set_is_executable(false); file }); let dir = TempDir::new("store").unwrap(); let hash = "63949aa823baf765eff07b946050d76ec0033144c785a94d3ebd82baa931cd16"; assert_eq!( &new_store(dir.path()) .record_directory(&directory) .wait() .unwrap() .0 .to_hex(), hash ); assert_eq!( new_store(dir.path()) .load_directory_proto(Fingerprint::from_hex_string(hash).unwrap()) .wait(), Ok(Some(directory.clone())) ); assert_eq!( new_store(dir.path()) .load_directory_proto_bytes(Fingerprint::from_hex_string(hash).unwrap()) .wait(), Ok(Some(directory.write_to_bytes().unwrap())) ); } #[test] fn file_is_not_directory_proto() { let dir = TempDir::new("store").unwrap(); new_store(dir.path()) .store_file_bytes(str_bytes()) .wait() .unwrap(); assert_eq!( new_store(dir.path()) .load_directory_proto(Fingerprint::from_hex_string(HASH).unwrap()) .wait(), Ok(None) ); assert_eq!( new_store(dir.path()) .load_directory_proto_bytes(Fingerprint::from_hex_string(HASH).unwrap()) .wait(), Ok(None) ); } #[test] fn digest_to_bazel_digest() { let digest = Digest(Fingerprint::from_hex_string(HASH).unwrap(), 16); let mut bazel_digest = bazel_protos::remote_execution::Digest::new(); bazel_digest.set_hash(HASH.to_string()); bazel_digest.set_size_bytes(16); assert_eq!(bazel_digest, digest.into()); } fn new_store<P: AsRef<Path>>(dir: P) -> Store { Store::new(dir, Arc::new(ResettablePool::new("test-pool-".to_string()))).unwrap() } }
use std::cmp::Ordering; use crate::units::{PreciseTime, TimeInt}; use crate::constants::*; /// ISO 8601 time duration with picosecond precision. #[derive(Debug,Clone,Copy,PartialEq,Eq)] pub struct Duration { secs: TimeInt, picos: TimeInt, } impl Duration { /// Create a duration with the specified number of weeks /// without respect of Daylight Savings. fn from_weeks(n: TimeInt) -> Self { Self { secs: n * SECS_PER_WEEK, picos: 0, } } /// Create a duration with the specified number of days /// without respect of Daylight Savings. fn from_days(n: TimeInt) -> Self { Self { secs: n * SECS_PER_DAY, picos: 0, } } /// Create a duration with the specified number of hours. fn from_hours(n: TimeInt) -> Self { Self { secs: n * SECS_PER_HOUR, picos: 0, } } /// Create a duration with the specified number of minutes. fn from_minutes(n: TimeInt) -> Self { Self { secs: n * SECS_PER_MINUTE, picos: 0, } } /// Create a duration with the specified number of seconds. fn from_secs(n: TimeInt) -> Self { Self { secs: n, picos: 0, } } /// Create a duration with the specified number of milliseconds. fn from_millis(n: TimeInt) -> Self { Self { secs: n / MILLIS_PER_SEC, picos: (n % MILLIS_PER_SEC) * PICOS_PER_MILLI, } } /// Create a duration with the specified number of microseconds. fn from_micros(n: TimeInt) -> Self { Self { secs: n / MICROS_PER_SEC, picos: (n % MICROS_PER_SEC) * PICOS_PER_MICRO, } } /// Create a duration with the specified number of nanoseconds. fn from_nanos(n: TimeInt) -> Self { Self { secs: n / NANOS_PER_SEC, picos: (n % NANOS_PER_SEC) * PICOS_PER_NANO, } } /// Create a duration with the specified number of picoseconds. fn from_picos(n: TimeInt) -> Self { Self { secs: n / PICOS_PER_SEC, picos: n % PICOS_PER_SEC, } } /// Gets the length of this duration in weeks assuming that there are the /// standard number of seconds in a week without respect of Daylight Savings fn as_weeks(&self) -> TimeInt { self.secs / SECS_PER_WEEK } /// Gets the length of this duration in days assuming that there are the /// standard number of seconds in a day without respect of Daylight Savings fn as_days(&self) -> TimeInt { self.secs / SECS_PER_DAY } /// Gets the length of this duration in hours. fn as_hours(&self) -> TimeInt { self.secs / SECS_PER_HOUR } /// Gets the length of this duration in minutes. fn as_minutes(&self) -> TimeInt { self.secs / SECS_PER_MINUTE } /// Gets the length of this duration in seconds. fn as_secs(&self) -> TimeInt { self.secs } /// Gets the length of this duration in milliseconds. fn as_millis(&self) -> TimeInt { (self.secs * MILLIS_PER_SEC) + (self.picos / PICOS_PER_MILLI) } /// Gets the length of this duration in microseconds. fn as_micros(&self) -> TimeInt { (self.secs * MICROS_PER_SEC) + (self.picos / PICOS_PER_MICRO) } /// Gets the length of this duration in nanoseconds. fn as_nanos(&self) -> TimeInt { (self.secs * NANOS_PER_SEC) + (self.picos / PICOS_PER_NANO) } /// Gets the length of this duration in picoseconds. fn as_picos(&self) -> TimeInt { self.secs * PICOS_PER_SEC + self.picos } } impl Ord for Duration { fn cmp(&self, other: &Self) -> Ordering { self.secs.cmp(other.secs).then(self.picos.cmp(other.picos)) } } impl PartialOrd for Duration { fn cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl From<PreciseTime> for Duration { fn from(t: PreciseTime) -> Self { use crate::units::TimeUnit::*; match t { Picoseconds(n) => Self::from_picos(n), Nanoseconds(n) => Self::from_nanos(n), Microseconds(n) => Self::from_micros(n), Milliseconds(n) => Self::from_millis(n), Seconds(n) => Self::from_secs(n), Minutes(n) => Self::from_minutes(n), Hours(n) => Self::from_hours(n), Days(n) => Self::from_days(n), Weeks(n) => Self::from_weeks(n) } } } impl From<std::time::Duration> for Duration { fn from(dur: std::time::Duration) -> Self { Self { secs: dur.as_secs(), picos: dur.subsec_nanos() * PICOS_PER_NANO, } } } impl Add for Duration { type Output = Self; fn add(self, other: Self) -> Self { let picos = self.picos + other.picos; let (picos, picos_secs) = calc_picos_secs(picos); Self { secs: self.secs + other.secs + picos_secs, picos: picos, } } } impl Add<PreciseTime> for Duration { type Output = Self; fn add(self, t: PreciseTime) -> Self { self + Self::from(t) } } impl Sub for Duration { type Output = Self; fn add(self, other: Self) -> Self { let picos = self.picos - other.picos; let (picos, picos_secs) = calc_picos_secs(picos); Self { secs: self.secs - other.secs - picos_secs, picos: picos, } } } impl Sub<PreciseTime> for Duration { type Output = Self; fn add(self, t: PreciseTime) -> Self { self - Self::from(t) } } impl <T: Into<TimeInt>> Mul<T> for Duration { type Output = Self; fn mul(self, rhs: T) -> Self { let scale: TimeInt = rhs.into(); let picos = self.picos * scale; let secs = self.secs * scale; let (picos, picos_secs) = calc_picos_secs(picos); Self { secs: secs + picos_secs, picos: picos } } } impl Neg for Duration { type Output = Self; fn neg(self) -> Self { Self { secs: -self.secs, picos: -self.picos } } } #[inline] fn calc_picos_secs(picos: TimeInt) -> (TimeInt, TimeInt) { if picos.abs() => PICOS_PER_SEC { picos_secs = picos / PICOS_PER_SEC; picos = picos % PICOS_PER_SEC; (picos, picos_secs) } else { (picos, 0) } }
use proconio::input; fn main() { input! { n: usize, aa: [i64; n], }; let mut sums1: Vec<i64> = vec![]; let mut sums2: Vec<i64> = vec![]; let mut sum1 = 0; let mut sum2 = 0; for a in aa.iter() { sum1 += a; sum2 += a * a; sums1.push(sum1); sums2.push(sum2); } let mut ans = 0; for i in 2..=n { let ai = aa[i - 1]; let aj1 = sums1[i - 2]; let aj2 = sums2[i - 2]; ans += (i - 1) as i64 * ai * ai - 2 * ai * aj1 + aj2; } println!("{}", ans); }
pub fn read_stdin(_msg: &str) {}
use error_chain::error_chain; error_chain! { foreign_links { Json(serde_json::Error); Toml(toml::de::Error); } } pub fn parse_normal_json() -> Result<()> { use serde_json::json; use serde_json::Value; let j = r#"{ "userid": 100, "verified": true, "access_privileges": [ "user", "admin" ] }"#; let parsed: Value = serde_json::from_str(j)?; let expected = json!({ "userid": 100, "verified": true, "access_privileges": [ "user", "admin" ] }); assert_eq!(parsed, expected); assert_eq!(*expected.get("userid").unwrap(), json!(100)); println!("{}", expected["userid"]); assert_eq!(expected["userid"], 100); Ok(()) } pub fn parse_toml() -> Result<()> { let toml_content = r#" [package] name = "your_package" version = "0.1.0" authors = ["You! <you@example.org>"] [dependencies] serde = "1.0" "#; use serde::Deserialize; use std::collections::HashMap; #[derive(Deserialize, Debug)] struct Package { name: String, version: String, authors: Vec<String>, } #[derive(Deserialize, Debug)] struct Config { package: Package, dependencies: HashMap<String, String>, } let package_info: Config = toml::from_str(toml_content)?; assert_eq!(package_info.package.name, "your_package"); assert_eq!(package_info.package.version, "0.1.0"); assert_eq!(package_info.package.authors, vec!["You! <you@example.org>"]); assert_eq!(package_info.dependencies["serde"], "1.0"); Ok(()) } // δ»₯ε°η«―ζ¨‘εΌοΌˆδ½Žδ½ζ¨‘εΌοΌ‰ε­—θŠ‚ι‘ΊεΊθ―»ε†™ζ•΄ζ•°??? θΏ‡δΊ†ε…ˆ #[test] pub fn test() { parse_normal_json(); parse_toml(); }
//! This module implements a WebSocket client and proxy that lives in the //! web worker and communicates with the server as well as the main Elm application. use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use web_sys; use web_sys::{MessageEvent, WebSocket, WorkerGlobalScope}; #[wasm_bindgen] pub fn start_websocket(uuid: &str) -> Result<(), JsValue> { println!("Starting websocket with uuid: {}", uuid); // TODO: Implement Gitpod verion of this. // TODO: Implement Hosted version of this. // Get the global scope let global_scope = js_sys::global().dyn_into::<WorkerGlobalScope>()?; // Get the location let location = global_scope.location(); // Get the href property let href = location.href(); // Print it out web_sys::console::log_1(&"Hello from Rust!".into()); web_sys::console::log_1(&JsValue::from_str(&href)); Ok(()) }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificate { #[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")] pub key_vault_id: Option<String>, #[serde(rename = "keyVaultSecretName", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_name: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<app_service_certificate::ProvisioningState>, } pub mod app_service_certificate { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Initialized, WaitingOnCertificateOrder, Succeeded, CertificateOrderFailed, OperationNotPermittedOnKeyVault, AzureServiceUnauthorizedToAccessKeyVault, KeyVaultDoesNotExist, KeyVaultSecretDoesNotExist, UnknownError, ExternalPrivateKey, Unknown, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificateCollection { pub value: Vec<AppServiceCertificateResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificateOrder { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<app_service_certificate_order::Properties>, } pub mod app_service_certificate_order { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub certificates: Option<serde_json::Value>, #[serde(rename = "distinguishedName", default, skip_serializing_if = "Option::is_none")] pub distinguished_name: Option<String>, #[serde(rename = "domainVerificationToken", default, skip_serializing_if = "Option::is_none")] pub domain_verification_token: Option<String>, #[serde(rename = "validityInYears", default, skip_serializing_if = "Option::is_none")] pub validity_in_years: Option<i32>, #[serde(rename = "keySize", default, skip_serializing_if = "Option::is_none")] pub key_size: Option<i32>, #[serde(rename = "productType")] pub product_type: properties::ProductType, #[serde(rename = "autoRenew", default, skip_serializing_if = "Option::is_none")] pub auto_renew: Option<bool>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "signedCertificate", default, skip_serializing_if = "Option::is_none")] pub signed_certificate: Option<CertificateDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub csr: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub intermediate: Option<CertificateDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub root: Option<CertificateDetails>, #[serde(rename = "serialNumber", default, skip_serializing_if = "Option::is_none")] pub serial_number: Option<String>, #[serde(rename = "lastCertificateIssuanceTime", default, skip_serializing_if = "Option::is_none")] pub last_certificate_issuance_time: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, #[serde(rename = "isPrivateKeyExternal", default, skip_serializing_if = "Option::is_none")] pub is_private_key_external: Option<bool>, #[serde( rename = "appServiceCertificateNotRenewableReasons", default, skip_serializing_if = "Vec::is_empty" )] pub app_service_certificate_not_renewable_reasons: Vec<String>, #[serde(rename = "nextAutoRenewalTimeStamp", default, skip_serializing_if = "Option::is_none")] pub next_auto_renewal_time_stamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub contact: Option<CertificateOrderContact>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProductType { StandardDomainValidatedSsl, StandardDomainValidatedWildCardSsl, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Pendingissuance, Issued, Revoked, Canceled, Denied, Pendingrevocation, PendingRekey, Unused, Expired, NotSubmitted, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificateOrderCollection { pub value: Vec<AppServiceCertificateOrder>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificateOrderPatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<app_service_certificate_order_patch_resource::Properties>, } pub mod app_service_certificate_order_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub certificates: Option<serde_json::Value>, #[serde(rename = "distinguishedName", default, skip_serializing_if = "Option::is_none")] pub distinguished_name: Option<String>, #[serde(rename = "domainVerificationToken", default, skip_serializing_if = "Option::is_none")] pub domain_verification_token: Option<String>, #[serde(rename = "validityInYears", default, skip_serializing_if = "Option::is_none")] pub validity_in_years: Option<i32>, #[serde(rename = "keySize", default, skip_serializing_if = "Option::is_none")] pub key_size: Option<i32>, #[serde(rename = "productType")] pub product_type: properties::ProductType, #[serde(rename = "autoRenew", default, skip_serializing_if = "Option::is_none")] pub auto_renew: Option<bool>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "signedCertificate", default, skip_serializing_if = "Option::is_none")] pub signed_certificate: Option<CertificateDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub csr: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub intermediate: Option<CertificateDetails>, #[serde(default, skip_serializing_if = "Option::is_none")] pub root: Option<CertificateDetails>, #[serde(rename = "serialNumber", default, skip_serializing_if = "Option::is_none")] pub serial_number: Option<String>, #[serde(rename = "lastCertificateIssuanceTime", default, skip_serializing_if = "Option::is_none")] pub last_certificate_issuance_time: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, #[serde(rename = "isPrivateKeyExternal", default, skip_serializing_if = "Option::is_none")] pub is_private_key_external: Option<bool>, #[serde( rename = "appServiceCertificateNotRenewableReasons", default, skip_serializing_if = "Vec::is_empty" )] pub app_service_certificate_not_renewable_reasons: Vec<String>, #[serde(rename = "nextAutoRenewalTimeStamp", default, skip_serializing_if = "Option::is_none")] pub next_auto_renewal_time_stamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub contact: Option<CertificateOrderContact>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProductType { StandardDomainValidatedSsl, StandardDomainValidatedWildCardSsl, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Pendingissuance, Issued, Revoked, Canceled, Denied, Pendingrevocation, PendingRekey, Unused, Expired, NotSubmitted, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificatePatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppServiceCertificate>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceCertificateResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppServiceCertificate>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<i32>, #[serde(rename = "serialNumber", default, skip_serializing_if = "Option::is_none")] pub serial_number: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[serde(rename = "notBefore", default, skip_serializing_if = "Option::is_none")] pub not_before: Option<String>, #[serde(rename = "notAfter", default, skip_serializing_if = "Option::is_none")] pub not_after: Option<String>, #[serde(rename = "signatureAlgorithm", default, skip_serializing_if = "Option::is_none")] pub signature_algorithm: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "rawData", default, skip_serializing_if = "Option::is_none")] pub raw_data: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateEmail { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<certificate_email::Properties>, } pub mod certificate_email { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "emailId", default, skip_serializing_if = "Option::is_none")] pub email_id: Option<String>, #[serde(rename = "timeStamp", default, skip_serializing_if = "Option::is_none")] pub time_stamp: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateOrderAction { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<certificate_order_action::Properties>, } pub mod certificate_order_action { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "actionType", default, skip_serializing_if = "Option::is_none")] pub action_type: Option<properties::ActionType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ActionType { CertificateIssued, CertificateOrderCanceled, CertificateOrderCreated, CertificateRevoked, DomainValidationComplete, FraudDetected, OrgNameChange, OrgValidationComplete, SanDrop, FraudCleared, CertificateExpired, CertificateExpirationWarning, FraudDocumentationRequired, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateOrderContact { #[serde(default, skip_serializing_if = "Option::is_none")] pub email: Option<String>, #[serde(rename = "nameFirst", default, skip_serializing_if = "Option::is_none")] pub name_first: Option<String>, #[serde(rename = "nameLast", default, skip_serializing_if = "Option::is_none")] pub name_last: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub phone: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReissueCertificateOrderRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<reissue_certificate_order_request::Properties>, } pub mod reissue_certificate_order_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "keySize", default, skip_serializing_if = "Option::is_none")] pub key_size: Option<i32>, #[serde(rename = "delayExistingRevokeInHours", default, skip_serializing_if = "Option::is_none")] pub delay_existing_revoke_in_hours: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub csr: Option<String>, #[serde(rename = "isPrivateKeyExternal", default, skip_serializing_if = "Option::is_none")] pub is_private_key_external: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RenewCertificateOrderRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<renew_certificate_order_request::Properties>, } pub mod renew_certificate_order_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "keySize", default, skip_serializing_if = "Option::is_none")] pub key_size: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub csr: Option<String>, #[serde(rename = "isPrivateKeyExternal", default, skip_serializing_if = "Option::is_none")] pub is_private_key_external: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteSeal { pub html: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteSealRequest { #[serde(rename = "lightTheme", default, skip_serializing_if = "Option::is_none")] pub light_theme: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub locale: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiDefinitionInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiManagementConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceEnvironment { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<app_service_environment::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<app_service_environment::Status>, #[serde(rename = "virtualNetwork")] pub virtual_network: VirtualNetworkProfile, #[serde(rename = "internalLoadBalancingMode", default, skip_serializing_if = "Option::is_none")] pub internal_load_balancing_mode: Option<app_service_environment::InternalLoadBalancingMode>, #[serde(rename = "multiSize", default, skip_serializing_if = "Option::is_none")] pub multi_size: Option<String>, #[serde(rename = "multiRoleCount", default, skip_serializing_if = "Option::is_none")] pub multi_role_count: Option<i32>, #[serde(rename = "ipsslAddressCount", default, skip_serializing_if = "Option::is_none")] pub ipssl_address_count: Option<i32>, #[serde(rename = "dnsSuffix", default, skip_serializing_if = "Option::is_none")] pub dns_suffix: Option<String>, #[serde(rename = "maximumNumberOfMachines", default, skip_serializing_if = "Option::is_none")] pub maximum_number_of_machines: Option<i32>, #[serde(rename = "frontEndScaleFactor", default, skip_serializing_if = "Option::is_none")] pub front_end_scale_factor: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub suspended: Option<bool>, #[serde(rename = "clusterSettings", default, skip_serializing_if = "Vec::is_empty")] pub cluster_settings: Vec<NameValuePair>, #[serde(rename = "userWhitelistedIpRanges", default, skip_serializing_if = "Vec::is_empty")] pub user_whitelisted_ip_ranges: Vec<String>, #[serde(rename = "hasLinuxWorkers", default, skip_serializing_if = "Option::is_none")] pub has_linux_workers: Option<bool>, #[serde(rename = "dedicatedHostCount", default, skip_serializing_if = "Option::is_none")] pub dedicated_host_count: Option<i32>, } pub mod app_service_environment { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Preparing, Ready, Scaling, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum InternalLoadBalancingMode { None, Web, Publishing, #[serde(rename = "Web, Publishing")] WebPublishing, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServicePlan { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<app_service_plan::Properties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuDescription>, } pub mod app_service_plan { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "workerTierName", default, skip_serializing_if = "Option::is_none")] pub worker_tier_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subscription: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "maximumNumberOfWorkers", default, skip_serializing_if = "Option::is_none")] pub maximum_number_of_workers: Option<i32>, #[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")] pub geo_region: Option<String>, #[serde(rename = "perSiteScaling", default, skip_serializing_if = "Option::is_none")] pub per_site_scaling: Option<bool>, #[serde(rename = "maximumElasticWorkerCount", default, skip_serializing_if = "Option::is_none")] pub maximum_elastic_worker_count: Option<i32>, #[serde(rename = "numberOfSites", default, skip_serializing_if = "Option::is_none")] pub number_of_sites: Option<i32>, #[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")] pub is_spot: Option<bool>, #[serde(rename = "spotExpirationTime", default, skip_serializing_if = "Option::is_none")] pub spot_expiration_time: Option<String>, #[serde(rename = "freeOfferExpirationTime", default, skip_serializing_if = "Option::is_none")] pub free_offer_expiration_time: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reserved: Option<bool>, #[serde(rename = "isXenon", default, skip_serializing_if = "Option::is_none")] pub is_xenon: Option<bool>, #[serde(rename = "hyperV", default, skip_serializing_if = "Option::is_none")] pub hyper_v: Option<bool>, #[serde(rename = "targetWorkerCount", default, skip_serializing_if = "Option::is_none")] pub target_worker_count: Option<i32>, #[serde(rename = "targetWorkerSizeId", default, skip_serializing_if = "Option::is_none")] pub target_worker_size_id: Option<i32>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "kubeEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub kube_environment_profile: Option<KubeEnvironmentProfile>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Ready, Pending, Creating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServicePlanCollection { pub value: Vec<AppServicePlan>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ArmIdWrapper { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutoHealActions { #[serde(rename = "actionType", default, skip_serializing_if = "Option::is_none")] pub action_type: Option<auto_heal_actions::ActionType>, #[serde(rename = "customAction", default, skip_serializing_if = "Option::is_none")] pub custom_action: Option<AutoHealCustomAction>, #[serde(rename = "minProcessExecutionTime", default, skip_serializing_if = "Option::is_none")] pub min_process_execution_time: Option<String>, } pub mod auto_heal_actions { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ActionType { Recycle, LogEvent, CustomAction, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutoHealCustomAction { #[serde(default, skip_serializing_if = "Option::is_none")] pub exe: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parameters: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutoHealRules { #[serde(default, skip_serializing_if = "Option::is_none")] pub triggers: Option<AutoHealTriggers>, #[serde(default, skip_serializing_if = "Option::is_none")] pub actions: Option<AutoHealActions>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AutoHealTriggers { #[serde(default, skip_serializing_if = "Option::is_none")] pub requests: Option<RequestsBasedTrigger>, #[serde(rename = "privateBytesInKB", default, skip_serializing_if = "Option::is_none")] pub private_bytes_in_kb: Option<i32>, #[serde(rename = "statusCodes", default, skip_serializing_if = "Vec::is_empty")] pub status_codes: Vec<StatusCodesBasedTrigger>, #[serde(rename = "slowRequests", default, skip_serializing_if = "Option::is_none")] pub slow_requests: Option<SlowRequestsBasedTrigger>, #[serde(rename = "slowRequestsWithPath", default, skip_serializing_if = "Vec::is_empty")] pub slow_requests_with_path: Vec<SlowRequestsBasedTrigger>, #[serde(rename = "statusCodesRange", default, skip_serializing_if = "Vec::is_empty")] pub status_codes_range: Vec<StatusCodesRangeBasedTrigger>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureStorageInfoValue { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<azure_storage_info_value::Type>, #[serde(rename = "accountName", default, skip_serializing_if = "Option::is_none")] pub account_name: Option<String>, #[serde(rename = "shareName", default, skip_serializing_if = "Option::is_none")] pub share_name: Option<String>, #[serde(rename = "accessKey", default, skip_serializing_if = "Option::is_none")] pub access_key: Option<String>, #[serde(rename = "mountPath", default, skip_serializing_if = "Option::is_none")] pub mount_path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<azure_storage_info_value::State>, } pub mod azure_storage_info_value { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { AzureFiles, AzureBlob, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { Ok, InvalidCredentials, InvalidShare, NotValidated, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Capability { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloningInfo { #[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")] pub correlation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub overwrite: Option<bool>, #[serde(rename = "cloneCustomHostNames", default, skip_serializing_if = "Option::is_none")] pub clone_custom_host_names: Option<bool>, #[serde(rename = "cloneSourceControl", default, skip_serializing_if = "Option::is_none")] pub clone_source_control: Option<bool>, #[serde(rename = "sourceWebAppId")] pub source_web_app_id: String, #[serde(rename = "sourceWebAppLocation", default, skip_serializing_if = "Option::is_none")] pub source_web_app_location: Option<String>, #[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")] pub hosting_environment: Option<String>, #[serde(rename = "appSettingsOverrides", default, skip_serializing_if = "Option::is_none")] pub app_settings_overrides: Option<serde_json::Value>, #[serde(rename = "configureLoadBalancing", default, skip_serializing_if = "Option::is_none")] pub configure_load_balancing: Option<bool>, #[serde(rename = "trafficManagerProfileId", default, skip_serializing_if = "Option::is_none")] pub traffic_manager_profile_id: Option<String>, #[serde(rename = "trafficManagerProfileName", default, skip_serializing_if = "Option::is_none")] pub traffic_manager_profile_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnStringInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<conn_string_info::Type>, } pub mod conn_string_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { MySql, #[serde(rename = "SQLServer")] SqlServer, #[serde(rename = "SQLAzure")] SqlAzure, Custom, NotificationHub, ServiceBus, EventHub, ApiHub, DocDb, RedisCache, #[serde(rename = "PostgreSQL")] PostgreSql, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CorsSettings { #[serde(rename = "allowedOrigins", default, skip_serializing_if = "Vec::is_empty")] pub allowed_origins: Vec<String>, #[serde(rename = "supportCredentials", default, skip_serializing_if = "Option::is_none")] pub support_credentials: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmOperationCollection { pub value: Vec<CsmOperationDescription>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmOperationDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<CsmOperationDisplay>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CsmOperationDescriptionProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmOperationDescriptionProperties { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<ServiceSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmOperationDisplay { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmUsageQuota { #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "nextResetTime", default, skip_serializing_if = "Option::is_none")] pub next_reset_time: Option<String>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<LocalizableString>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmUsageQuotaCollection { pub value: Vec<CsmUsageQuota>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataProviderMetadata { #[serde(rename = "providerName", default, skip_serializing_if = "Option::is_none")] pub provider_name: Option<String>, #[serde(rename = "propertyBag", default, skip_serializing_if = "Vec::is_empty")] pub property_bag: Vec<KeyValuePairStringObject>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataTableResponseColumn { #[serde(rename = "columnName", default, skip_serializing_if = "Option::is_none")] pub column_name: Option<String>, #[serde(rename = "dataType", default, skip_serializing_if = "Option::is_none")] pub data_type: Option<String>, #[serde(rename = "columnType", default, skip_serializing_if = "Option::is_none")] pub column_type: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataTableResponseObject { #[serde(rename = "tableName", default, skip_serializing_if = "Option::is_none")] pub table_name: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub columns: Vec<DataTableResponseColumn>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub rows: Vec<Vec<String>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DefaultErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<default_error_response::Error>, } pub mod default_error_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Error { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub details: Vec<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub innererror: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeletedSite { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<deleted_site::Properties>, } pub mod deleted_site { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "deletedSiteId", default, skip_serializing_if = "Option::is_none")] pub deleted_site_id: Option<i32>, #[serde(rename = "deletedTimestamp", default, skip_serializing_if = "Option::is_none")] pub deleted_timestamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subscription: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(rename = "deletedSiteName", default, skip_serializing_if = "Option::is_none")] pub deleted_site_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub slot: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<String>, #[serde(rename = "geoRegionName", default, skip_serializing_if = "Option::is_none")] pub geo_region_name: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DetectorInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub author: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "supportTopicList", default, skip_serializing_if = "Vec::is_empty")] pub support_topic_list: Vec<SupportTopic>, #[serde(rename = "analysisType", default, skip_serializing_if = "Vec::is_empty")] pub analysis_type: Vec<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<detector_info::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub score: Option<f32>, } pub mod detector_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Detector, Analysis, CategoryOverview, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DetectorResponse { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<detector_response::Properties>, } pub mod detector_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub metadata: Option<DetectorInfo>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dataset: Vec<DiagnosticData>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<Status>, #[serde(rename = "dataProvidersMetadata", default, skip_serializing_if = "Vec::is_empty")] pub data_providers_metadata: Vec<DataProviderMetadata>, #[serde(rename = "suggestedUtterances", default, skip_serializing_if = "Option::is_none")] pub suggested_utterances: Option<QueryUtterancesResults>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DetectorResponseCollection { pub value: Vec<DetectorResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticData { #[serde(default, skip_serializing_if = "Option::is_none")] pub table: Option<DataTableResponseObject>, #[serde(rename = "renderingProperties", default, skip_serializing_if = "Option::is_none")] pub rendering_properties: Option<Rendering>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Dimension { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "internalName", default, skip_serializing_if = "Option::is_none")] pub internal_name: Option<String>, #[serde(rename = "toBeExportedForShoebox", default, skip_serializing_if = "Option::is_none")] pub to_be_exported_for_shoebox: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorEntity { #[serde(rename = "extendedCode", default, skip_serializing_if = "Option::is_none")] pub extended_code: Option<String>, #[serde(rename = "messageTemplate", default, skip_serializing_if = "Option::is_none")] pub message_template: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub parameters: Vec<String>, #[serde(rename = "innerErrors", default, skip_serializing_if = "Vec::is_empty")] pub inner_errors: Vec<ErrorEntity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Experiments { #[serde(rename = "rampUpRules", default, skip_serializing_if = "Vec::is_empty")] pub ramp_up_rules: Vec<RampUpRule>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HandlerMapping { #[serde(default, skip_serializing_if = "Option::is_none")] pub extension: Option<String>, #[serde(rename = "scriptProcessor", default, skip_serializing_if = "Option::is_none")] pub script_processor: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub arguments: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostNameSslState { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "sslState", default, skip_serializing_if = "Option::is_none")] pub ssl_state: Option<host_name_ssl_state::SslState>, #[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")] pub virtual_ip: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "toUpdate", default, skip_serializing_if = "Option::is_none")] pub to_update: Option<bool>, #[serde(rename = "hostType", default, skip_serializing_if = "Option::is_none")] pub host_type: Option<host_name_ssl_state::HostType>, } pub mod host_name_ssl_state { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SslState { Disabled, SniEnabled, IpBasedEnabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum HostType { Standard, Repository, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostingEnvironmentProfile { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HybridConnection { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<hybrid_connection::Properties>, } pub mod hybrid_connection { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "serviceBusNamespace", default, skip_serializing_if = "Option::is_none")] pub service_bus_namespace: Option<String>, #[serde(rename = "relayName", default, skip_serializing_if = "Option::is_none")] pub relay_name: Option<String>, #[serde(rename = "relayArmUri", default, skip_serializing_if = "Option::is_none")] pub relay_arm_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub hostname: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option<i32>, #[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")] pub send_key_name: Option<String>, #[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")] pub send_key_value: Option<String>, #[serde(rename = "serviceBusSuffix", default, skip_serializing_if = "Option::is_none")] pub service_bus_suffix: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Identifier { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<identifier::Properties>, } pub mod identifier { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IdentifierCollection { pub value: Vec<Identifier>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpSecurityRestriction { #[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")] pub ip_address: Option<String>, #[serde(rename = "subnetMask", default, skip_serializing_if = "Option::is_none")] pub subnet_mask: Option<String>, #[serde(rename = "vnetSubnetResourceId", default, skip_serializing_if = "Option::is_none")] pub vnet_subnet_resource_id: Option<String>, #[serde(rename = "vnetTrafficTag", default, skip_serializing_if = "Option::is_none")] pub vnet_traffic_tag: Option<i32>, #[serde(rename = "subnetTrafficTag", default, skip_serializing_if = "Option::is_none")] pub subnet_traffic_tag: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<ip_security_restriction::Tag>, #[serde(default, skip_serializing_if = "Option::is_none")] pub priority: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option<serde_json::Value>, } pub mod ip_security_restriction { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tag { Default, XffProxy, ServiceTag, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyValuePairStringObject { #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KubeEnvironmentProfile { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LocalizableString { #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")] pub localized_value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LogSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, #[serde(rename = "logFilterPattern", default, skip_serializing_if = "Option::is_none")] pub log_filter_pattern: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ManagedServiceIdentity { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<managed_service_identity::Type>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identities: Option<serde_json::Value>, } pub mod managed_service_identity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, UserAssigned, #[serde(rename = "SystemAssigned, UserAssigned")] SystemAssignedUserAssigned, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricAvailability { #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MetricSpecification { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(rename = "supportsInstanceLevelAggregation", default, skip_serializing_if = "Option::is_none")] pub supports_instance_level_aggregation: Option<bool>, #[serde(rename = "enableRegionalMdmAccount", default, skip_serializing_if = "Option::is_none")] pub enable_regional_mdm_account: Option<bool>, #[serde(rename = "sourceMdmAccount", default, skip_serializing_if = "Option::is_none")] pub source_mdm_account: Option<String>, #[serde(rename = "sourceMdmNamespace", default, skip_serializing_if = "Option::is_none")] pub source_mdm_namespace: Option<String>, #[serde(rename = "metricFilterPattern", default, skip_serializing_if = "Option::is_none")] pub metric_filter_pattern: Option<String>, #[serde(rename = "fillGapWithZero", default, skip_serializing_if = "Option::is_none")] pub fill_gap_with_zero: Option<bool>, #[serde(rename = "isInternal", default, skip_serializing_if = "Option::is_none")] pub is_internal: Option<bool>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub dimensions: Vec<Dimension>, #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub availabilities: Vec<MetricAvailability>, #[serde(rename = "supportedTimeGrainTypes", default, skip_serializing_if = "Vec::is_empty")] pub supported_time_grain_types: Vec<String>, #[serde(rename = "supportedAggregationTypes", default, skip_serializing_if = "Vec::is_empty")] pub supported_aggregation_types: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NameIdentifier { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NameValuePair { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<operation::Status>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub errors: Vec<ErrorEntity>, #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(rename = "modifiedTime", default, skip_serializing_if = "Option::is_none")] pub modified_time: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, #[serde(rename = "geoMasterOperationId", default, skip_serializing_if = "Option::is_none")] pub geo_master_operation_id: Option<String>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { InProgress, Failed, Succeeded, TimedOut, Created, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionCollection { pub value: Vec<RemotePrivateEndpointConnectionArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkConnectionApprovalRequest { #[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")] pub private_link_service_connection_state: Option<PrivateLinkConnectionState>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkConnectionApprovalRequestResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateLinkConnectionApprovalRequest>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkConnectionState { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "actionsRequired", default, skip_serializing_if = "Option::is_none")] pub actions_required: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResource { pub id: String, pub name: String, #[serde(rename = "type")] pub type_: String, pub properties: PrivateLinkResourceProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceProperties { #[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")] pub group_id: Option<String>, #[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")] pub required_members: Vec<String>, #[serde(rename = "requiredZoneNames", default, skip_serializing_if = "Vec::is_empty")] pub required_zone_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourcesWrapper { pub value: Vec<PrivateLinkResource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyOnlyResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PushSettings { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<push_settings::Properties>, } pub mod push_settings { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "isPushEnabled")] pub is_push_enabled: bool, #[serde(rename = "tagWhitelistJson", default, skip_serializing_if = "Option::is_none")] pub tag_whitelist_json: Option<String>, #[serde(rename = "tagsRequiringAuth", default, skip_serializing_if = "Option::is_none")] pub tags_requiring_auth: Option<String>, #[serde(rename = "dynamicTagsJson", default, skip_serializing_if = "Option::is_none")] pub dynamic_tags_json: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryUtterancesResult { #[serde(rename = "sampleUtterance", default, skip_serializing_if = "Option::is_none")] pub sample_utterance: Option<SampleUtterance>, #[serde(default, skip_serializing_if = "Option::is_none")] pub score: Option<f32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QueryUtterancesResults { #[serde(default, skip_serializing_if = "Option::is_none")] pub query: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub results: Vec<QueryUtterancesResult>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RampUpRule { #[serde(rename = "actionHostName", default, skip_serializing_if = "Option::is_none")] pub action_host_name: Option<String>, #[serde(rename = "reroutePercentage", default, skip_serializing_if = "Option::is_none")] pub reroute_percentage: Option<f64>, #[serde(rename = "changeStep", default, skip_serializing_if = "Option::is_none")] pub change_step: Option<f64>, #[serde(rename = "changeIntervalInMinutes", default, skip_serializing_if = "Option::is_none")] pub change_interval_in_minutes: Option<i32>, #[serde(rename = "minReroutePercentage", default, skip_serializing_if = "Option::is_none")] pub min_reroute_percentage: Option<f64>, #[serde(rename = "maxReroutePercentage", default, skip_serializing_if = "Option::is_none")] pub max_reroute_percentage: Option<f64>, #[serde(rename = "changeDecisionCallbackUrl", default, skip_serializing_if = "Option::is_none")] pub change_decision_callback_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RemotePrivateEndpointConnectionArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<remote_private_endpoint_connection_arm_resource::Properties>, } pub mod remote_private_endpoint_connection_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")] pub private_endpoint: Option<ArmIdWrapper>, #[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")] pub private_link_service_connection_state: Option<PrivateLinkConnectionState>, #[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")] pub ip_addresses: Vec<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Rendering { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<rendering::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } pub mod rendering { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { NoGraph, Table, TimeSeries, TimeSeriesPerInstance, PieChart, DataSummary, Email, Insights, DynamicInsight, Markdown, Detector, DropDown, Card, Solution, Guage, Form, ChangeSets, ChangeAnalysisOnboarding, ChangesView, AppInsight, DependencyGraph, DownTime, SummaryCard, SearchComponent, AppInsightEnablement, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RequestsBasedTrigger { #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")] pub time_interval: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option<String>, pub location: String, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SampleUtterance { #[serde(default, skip_serializing_if = "Option::is_none")] pub text: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub links: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub qid: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceSpecification { #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<MetricSpecification>, #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub log_specifications: Vec<LogSpecification>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Site { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site::Properties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, } pub mod site { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")] pub host_names: Vec<String>, #[serde(rename = "repositorySiteName", default, skip_serializing_if = "Option::is_none")] pub repository_site_name: Option<String>, #[serde(rename = "usageState", default, skip_serializing_if = "Option::is_none")] pub usage_state: Option<properties::UsageState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "enabledHostNames", default, skip_serializing_if = "Vec::is_empty")] pub enabled_host_names: Vec<String>, #[serde(rename = "availabilityState", default, skip_serializing_if = "Option::is_none")] pub availability_state: Option<properties::AvailabilityState>, #[serde(rename = "hostNameSslStates", default, skip_serializing_if = "Vec::is_empty")] pub host_name_ssl_states: Vec<HostNameSslState>, #[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")] pub server_farm_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reserved: Option<bool>, #[serde(rename = "isXenon", default, skip_serializing_if = "Option::is_none")] pub is_xenon: Option<bool>, #[serde(rename = "hyperV", default, skip_serializing_if = "Option::is_none")] pub hyper_v: Option<bool>, #[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_time_utc: Option<String>, #[serde(rename = "siteConfig", default, skip_serializing_if = "Option::is_none")] pub site_config: Option<SiteConfig>, #[serde(rename = "trafficManagerHostNames", default, skip_serializing_if = "Vec::is_empty")] pub traffic_manager_host_names: Vec<String>, #[serde(rename = "scmSiteAlsoStopped", default, skip_serializing_if = "Option::is_none")] pub scm_site_also_stopped: Option<bool>, #[serde(rename = "targetSwapSlot", default, skip_serializing_if = "Option::is_none")] pub target_swap_slot: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "clientAffinityEnabled", default, skip_serializing_if = "Option::is_none")] pub client_affinity_enabled: Option<bool>, #[serde(rename = "clientCertEnabled", default, skip_serializing_if = "Option::is_none")] pub client_cert_enabled: Option<bool>, #[serde(rename = "clientCertMode", default, skip_serializing_if = "Option::is_none")] pub client_cert_mode: Option<properties::ClientCertMode>, #[serde(rename = "clientCertExclusionPaths", default, skip_serializing_if = "Option::is_none")] pub client_cert_exclusion_paths: Option<String>, #[serde(rename = "hostNamesDisabled", default, skip_serializing_if = "Option::is_none")] pub host_names_disabled: Option<bool>, #[serde(rename = "customDomainVerificationId", default, skip_serializing_if = "Option::is_none")] pub custom_domain_verification_id: Option<String>, #[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Option::is_none")] pub outbound_ip_addresses: Option<String>, #[serde(rename = "possibleOutboundIpAddresses", default, skip_serializing_if = "Option::is_none")] pub possible_outbound_ip_addresses: Option<String>, #[serde(rename = "containerSize", default, skip_serializing_if = "Option::is_none")] pub container_size: Option<i32>, #[serde(rename = "dailyMemoryTimeQuota", default, skip_serializing_if = "Option::is_none")] pub daily_memory_time_quota: Option<i32>, #[serde(rename = "suspendedTill", default, skip_serializing_if = "Option::is_none")] pub suspended_till: Option<String>, #[serde(rename = "maxNumberOfWorkers", default, skip_serializing_if = "Option::is_none")] pub max_number_of_workers: Option<i32>, #[serde(rename = "cloningInfo", default, skip_serializing_if = "Option::is_none")] pub cloning_info: Option<CloningInfo>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(rename = "isDefaultContainer", default, skip_serializing_if = "Option::is_none")] pub is_default_container: Option<bool>, #[serde(rename = "defaultHostName", default, skip_serializing_if = "Option::is_none")] pub default_host_name: Option<String>, #[serde(rename = "slotSwapStatus", default, skip_serializing_if = "Option::is_none")] pub slot_swap_status: Option<SlotSwapStatus>, #[serde(rename = "httpsOnly", default, skip_serializing_if = "Option::is_none")] pub https_only: Option<bool>, #[serde(rename = "redundancyMode", default, skip_serializing_if = "Option::is_none")] pub redundancy_mode: Option<properties::RedundancyMode>, #[serde(rename = "inProgressOperationId", default, skip_serializing_if = "Option::is_none")] pub in_progress_operation_id: Option<String>, #[serde(rename = "storageAccountRequired", default, skip_serializing_if = "Option::is_none")] pub storage_account_required: Option<bool>, #[serde(rename = "keyVaultReferenceIdentity", default, skip_serializing_if = "Option::is_none")] pub key_vault_reference_identity: Option<String>, #[serde(rename = "virtualNetworkSubnetId", default, skip_serializing_if = "Option::is_none")] pub virtual_network_subnet_id: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UsageState { Normal, Exceeded, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AvailabilityState { Normal, Limited, DisasterRecoveryMode, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ClientCertMode { Required, Optional, OptionalInteractiveUser, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RedundancyMode { None, Manual, Failover, ActiveActive, GeoRedundant, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfig { #[serde(rename = "numberOfWorkers", default, skip_serializing_if = "Option::is_none")] pub number_of_workers: Option<i32>, #[serde(rename = "defaultDocuments", default, skip_serializing_if = "Vec::is_empty")] pub default_documents: Vec<String>, #[serde(rename = "netFrameworkVersion", default, skip_serializing_if = "Option::is_none")] pub net_framework_version: Option<String>, #[serde(rename = "phpVersion", default, skip_serializing_if = "Option::is_none")] pub php_version: Option<String>, #[serde(rename = "pythonVersion", default, skip_serializing_if = "Option::is_none")] pub python_version: Option<String>, #[serde(rename = "nodeVersion", default, skip_serializing_if = "Option::is_none")] pub node_version: Option<String>, #[serde(rename = "powerShellVersion", default, skip_serializing_if = "Option::is_none")] pub power_shell_version: Option<String>, #[serde(rename = "linuxFxVersion", default, skip_serializing_if = "Option::is_none")] pub linux_fx_version: Option<String>, #[serde(rename = "windowsFxVersion", default, skip_serializing_if = "Option::is_none")] pub windows_fx_version: Option<String>, #[serde(rename = "requestTracingEnabled", default, skip_serializing_if = "Option::is_none")] pub request_tracing_enabled: Option<bool>, #[serde(rename = "requestTracingExpirationTime", default, skip_serializing_if = "Option::is_none")] pub request_tracing_expiration_time: Option<String>, #[serde(rename = "remoteDebuggingEnabled", default, skip_serializing_if = "Option::is_none")] pub remote_debugging_enabled: Option<bool>, #[serde(rename = "remoteDebuggingVersion", default, skip_serializing_if = "Option::is_none")] pub remote_debugging_version: Option<String>, #[serde(rename = "httpLoggingEnabled", default, skip_serializing_if = "Option::is_none")] pub http_logging_enabled: Option<bool>, #[serde(rename = "acrUseManagedIdentityCreds", default, skip_serializing_if = "Option::is_none")] pub acr_use_managed_identity_creds: Option<bool>, #[serde(rename = "acrUserManagedIdentityID", default, skip_serializing_if = "Option::is_none")] pub acr_user_managed_identity_id: Option<String>, #[serde(rename = "logsDirectorySizeLimit", default, skip_serializing_if = "Option::is_none")] pub logs_directory_size_limit: Option<i32>, #[serde(rename = "detailedErrorLoggingEnabled", default, skip_serializing_if = "Option::is_none")] pub detailed_error_logging_enabled: Option<bool>, #[serde(rename = "publishingUsername", default, skip_serializing_if = "Option::is_none")] pub publishing_username: Option<String>, #[serde(rename = "appSettings", default, skip_serializing_if = "Vec::is_empty")] pub app_settings: Vec<NameValuePair>, #[serde(rename = "connectionStrings", default, skip_serializing_if = "Vec::is_empty")] pub connection_strings: Vec<ConnStringInfo>, #[serde(rename = "machineKey", default, skip_serializing_if = "Option::is_none")] pub machine_key: Option<SiteMachineKey>, #[serde(rename = "handlerMappings", default, skip_serializing_if = "Vec::is_empty")] pub handler_mappings: Vec<HandlerMapping>, #[serde(rename = "documentRoot", default, skip_serializing_if = "Option::is_none")] pub document_root: Option<String>, #[serde(rename = "scmType", default, skip_serializing_if = "Option::is_none")] pub scm_type: Option<site_config::ScmType>, #[serde(rename = "use32BitWorkerProcess", default, skip_serializing_if = "Option::is_none")] pub use32_bit_worker_process: Option<bool>, #[serde(rename = "webSocketsEnabled", default, skip_serializing_if = "Option::is_none")] pub web_sockets_enabled: Option<bool>, #[serde(rename = "alwaysOn", default, skip_serializing_if = "Option::is_none")] pub always_on: Option<bool>, #[serde(rename = "javaVersion", default, skip_serializing_if = "Option::is_none")] pub java_version: Option<String>, #[serde(rename = "javaContainer", default, skip_serializing_if = "Option::is_none")] pub java_container: Option<String>, #[serde(rename = "javaContainerVersion", default, skip_serializing_if = "Option::is_none")] pub java_container_version: Option<String>, #[serde(rename = "appCommandLine", default, skip_serializing_if = "Option::is_none")] pub app_command_line: Option<String>, #[serde(rename = "managedPipelineMode", default, skip_serializing_if = "Option::is_none")] pub managed_pipeline_mode: Option<site_config::ManagedPipelineMode>, #[serde(rename = "virtualApplications", default, skip_serializing_if = "Vec::is_empty")] pub virtual_applications: Vec<VirtualApplication>, #[serde(rename = "loadBalancing", default, skip_serializing_if = "Option::is_none")] pub load_balancing: Option<site_config::LoadBalancing>, #[serde(default, skip_serializing_if = "Option::is_none")] pub experiments: Option<Experiments>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limits: Option<SiteLimits>, #[serde(rename = "autoHealEnabled", default, skip_serializing_if = "Option::is_none")] pub auto_heal_enabled: Option<bool>, #[serde(rename = "autoHealRules", default, skip_serializing_if = "Option::is_none")] pub auto_heal_rules: Option<AutoHealRules>, #[serde(rename = "tracingOptions", default, skip_serializing_if = "Option::is_none")] pub tracing_options: Option<String>, #[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")] pub vnet_name: Option<String>, #[serde(rename = "vnetRouteAllEnabled", default, skip_serializing_if = "Option::is_none")] pub vnet_route_all_enabled: Option<bool>, #[serde(rename = "vnetPrivatePortsCount", default, skip_serializing_if = "Option::is_none")] pub vnet_private_ports_count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub cors: Option<CorsSettings>, #[serde(default, skip_serializing_if = "Option::is_none")] pub push: Option<PushSettings>, #[serde(rename = "apiDefinition", default, skip_serializing_if = "Option::is_none")] pub api_definition: Option<ApiDefinitionInfo>, #[serde(rename = "apiManagementConfig", default, skip_serializing_if = "Option::is_none")] pub api_management_config: Option<ApiManagementConfig>, #[serde(rename = "autoSwapSlotName", default, skip_serializing_if = "Option::is_none")] pub auto_swap_slot_name: Option<String>, #[serde(rename = "localMySqlEnabled", default, skip_serializing_if = "Option::is_none")] pub local_my_sql_enabled: Option<bool>, #[serde(rename = "managedServiceIdentityId", default, skip_serializing_if = "Option::is_none")] pub managed_service_identity_id: Option<i32>, #[serde(rename = "xManagedServiceIdentityId", default, skip_serializing_if = "Option::is_none")] pub x_managed_service_identity_id: Option<i32>, #[serde(rename = "keyVaultReferenceIdentity", default, skip_serializing_if = "Option::is_none")] pub key_vault_reference_identity: Option<String>, #[serde(rename = "ipSecurityRestrictions", default, skip_serializing_if = "Vec::is_empty")] pub ip_security_restrictions: Vec<IpSecurityRestriction>, #[serde(rename = "scmIpSecurityRestrictions", default, skip_serializing_if = "Vec::is_empty")] pub scm_ip_security_restrictions: Vec<IpSecurityRestriction>, #[serde(rename = "scmIpSecurityRestrictionsUseMain", default, skip_serializing_if = "Option::is_none")] pub scm_ip_security_restrictions_use_main: Option<bool>, #[serde(rename = "http20Enabled", default, skip_serializing_if = "Option::is_none")] pub http20_enabled: Option<bool>, #[serde(rename = "minTlsVersion", default, skip_serializing_if = "Option::is_none")] pub min_tls_version: Option<site_config::MinTlsVersion>, #[serde(rename = "scmMinTlsVersion", default, skip_serializing_if = "Option::is_none")] pub scm_min_tls_version: Option<site_config::ScmMinTlsVersion>, #[serde(rename = "ftpsState", default, skip_serializing_if = "Option::is_none")] pub ftps_state: Option<site_config::FtpsState>, #[serde(rename = "preWarmedInstanceCount", default, skip_serializing_if = "Option::is_none")] pub pre_warmed_instance_count: Option<i32>, #[serde(rename = "functionAppScaleLimit", default, skip_serializing_if = "Option::is_none")] pub function_app_scale_limit: Option<i32>, #[serde(rename = "healthCheckPath", default, skip_serializing_if = "Option::is_none")] pub health_check_path: Option<String>, #[serde( rename = "functionsRuntimeScaleMonitoringEnabled", default, skip_serializing_if = "Option::is_none" )] pub functions_runtime_scale_monitoring_enabled: Option<bool>, #[serde(rename = "websiteTimeZone", default, skip_serializing_if = "Option::is_none")] pub website_time_zone: Option<String>, #[serde(rename = "minimumElasticInstanceCount", default, skip_serializing_if = "Option::is_none")] pub minimum_elastic_instance_count: Option<i32>, #[serde(rename = "azureStorageAccounts", default, skip_serializing_if = "Option::is_none")] pub azure_storage_accounts: Option<serde_json::Value>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<String>, } pub mod site_config { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScmType { None, Dropbox, Tfs, LocalGit, GitHub, CodePlexGit, CodePlexHg, BitbucketGit, BitbucketHg, ExternalGit, ExternalHg, OneDrive, #[serde(rename = "VSO")] Vso, #[serde(rename = "VSTSRM")] Vstsrm, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ManagedPipelineMode { Integrated, Classic, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LoadBalancing { WeightedRoundRobin, LeastRequests, LeastResponseTime, WeightedTotalTraffic, RequestHash, PerSiteRoundRobin, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum MinTlsVersion { #[serde(rename = "1.0")] N1_0, #[serde(rename = "1.1")] N1_1, #[serde(rename = "1.2")] N1_2, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScmMinTlsVersion { #[serde(rename = "1.0")] N1_0, #[serde(rename = "1.1")] N1_1, #[serde(rename = "1.2")] N1_2, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum FtpsState { AllAllowed, FtpsOnly, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteLimits { #[serde(rename = "maxPercentageCpu", default, skip_serializing_if = "Option::is_none")] pub max_percentage_cpu: Option<f64>, #[serde(rename = "maxMemoryInMb", default, skip_serializing_if = "Option::is_none")] pub max_memory_in_mb: Option<i64>, #[serde(rename = "maxDiskSizeInMb", default, skip_serializing_if = "Option::is_none")] pub max_disk_size_in_mb: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteMachineKey { #[serde(default, skip_serializing_if = "Option::is_none")] pub validation: Option<String>, #[serde(rename = "validationKey", default, skip_serializing_if = "Option::is_none")] pub validation_key: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub decryption: Option<String>, #[serde(rename = "decryptionKey", default, skip_serializing_if = "Option::is_none")] pub decryption_key: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuCapacity { #[serde(default, skip_serializing_if = "Option::is_none")] pub minimum: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub maximum: Option<i32>, #[serde(rename = "elasticMaximum", default, skip_serializing_if = "Option::is_none")] pub elastic_maximum: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option<i32>, #[serde(rename = "scaleType", default, skip_serializing_if = "Option::is_none")] pub scale_type: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub family: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i32>, #[serde(rename = "skuCapacity", default, skip_serializing_if = "Option::is_none")] pub sku_capacity: Option<SkuCapacity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capabilities: Vec<Capability>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlotSwapStatus { #[serde(rename = "timestampUtc", default, skip_serializing_if = "Option::is_none")] pub timestamp_utc: Option<String>, #[serde(rename = "sourceSlotName", default, skip_serializing_if = "Option::is_none")] pub source_slot_name: Option<String>, #[serde(rename = "destinationSlotName", default, skip_serializing_if = "Option::is_none")] pub destination_slot_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlowRequestsBasedTrigger { #[serde(rename = "timeTaken", default, skip_serializing_if = "Option::is_none")] pub time_taken: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")] pub time_interval: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Snapshot { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<snapshot::Properties>, } pub mod snapshot { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Status { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "statusId", default, skip_serializing_if = "Option::is_none")] pub status_id: Option<status::StatusId>, } pub mod status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum StatusId { Critical, Warning, Info, Success, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StatusCodesBasedTrigger { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<i32>, #[serde(rename = "subStatus", default, skip_serializing_if = "Option::is_none")] pub sub_status: Option<i32>, #[serde(rename = "win32Status", default, skip_serializing_if = "Option::is_none")] pub win32_status: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")] pub time_interval: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StatusCodesRangeBasedTrigger { #[serde(rename = "statusCodes", default, skip_serializing_if = "Option::is_none")] pub status_codes: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde(rename = "timeInterval", default, skip_serializing_if = "Option::is_none")] pub time_interval: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StringDictionary { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SupportTopic { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "pesId", default, skip_serializing_if = "Option::is_none")] pub pes_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct User { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<user::Properties>, } pub mod user { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "publishingUserName")] pub publishing_user_name: String, #[serde(rename = "publishingPassword", default, skip_serializing_if = "Option::is_none")] pub publishing_password: Option<String>, #[serde(rename = "publishingPasswordHash", default, skip_serializing_if = "Option::is_none")] pub publishing_password_hash: Option<String>, #[serde(rename = "publishingPasswordHashSalt", default, skip_serializing_if = "Option::is_none")] pub publishing_password_hash_salt: Option<String>, #[serde(rename = "scmUri", default, skip_serializing_if = "Option::is_none")] pub scm_uri: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualApplication { #[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")] pub virtual_path: Option<String>, #[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")] pub physical_path: Option<String>, #[serde(rename = "preloadEnabled", default, skip_serializing_if = "Option::is_none")] pub preload_enabled: Option<bool>, #[serde(rename = "virtualDirectories", default, skip_serializing_if = "Vec::is_empty")] pub virtual_directories: Vec<VirtualDirectory>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualDirectory { #[serde(rename = "virtualPath", default, skip_serializing_if = "Option::is_none")] pub virtual_path: Option<String>, #[serde(rename = "physicalPath", default, skip_serializing_if = "Option::is_none")] pub physical_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualNetworkProfile { pub id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subnet: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetGateway { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_gateway::Properties>, } pub mod vnet_gateway { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")] pub vnet_name: Option<String>, #[serde(rename = "vpnPackageUri")] pub vpn_package_uri: String, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_info::Properties>, } pub mod vnet_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "vnetResourceId", default, skip_serializing_if = "Option::is_none")] pub vnet_resource_id: Option<String>, #[serde(rename = "certThumbprint", default, skip_serializing_if = "Option::is_none")] pub cert_thumbprint: Option<String>, #[serde(rename = "certBlob", default, skip_serializing_if = "Option::is_none")] pub cert_blob: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub routes: Vec<VnetRoute>, #[serde(rename = "resyncRequired", default, skip_serializing_if = "Option::is_none")] pub resync_required: Option<bool>, #[serde(rename = "dnsServers", default, skip_serializing_if = "Option::is_none")] pub dns_servers: Option<String>, #[serde(rename = "isSwift", default, skip_serializing_if = "Option::is_none")] pub is_swift: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetRoute { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_route::Properties>, } pub mod vnet_route { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "startAddress", default, skip_serializing_if = "Option::is_none")] pub start_address: Option<String>, #[serde(rename = "endAddress", default, skip_serializing_if = "Option::is_none")] pub end_address: Option<String>, #[serde(rename = "routeType", default, skip_serializing_if = "Option::is_none")] pub route_type: Option<properties::RouteType>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RouteType { #[serde(rename = "DEFAULT")] Default, #[serde(rename = "INHERITED")] Inherited, #[serde(rename = "STATIC")] Static, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppCollection { pub value: Vec<Site>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Address { pub address1: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub address2: Option<String>, pub city: String, pub country: String, #[serde(rename = "postalCode")] pub postal_code: String, pub state: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Contact { #[serde(rename = "addressMailing", default, skip_serializing_if = "Option::is_none")] pub address_mailing: Option<Address>, pub email: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub fax: Option<String>, #[serde(rename = "jobTitle", default, skip_serializing_if = "Option::is_none")] pub job_title: Option<String>, #[serde(rename = "nameFirst")] pub name_first: String, #[serde(rename = "nameLast")] pub name_last: String, #[serde(rename = "nameMiddle", default, skip_serializing_if = "Option::is_none")] pub name_middle: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub organization: Option<String>, pub phone: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Domain { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<domain::Properties>, } pub mod domain { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "contactAdmin")] pub contact_admin: Contact, #[serde(rename = "contactBilling")] pub contact_billing: Contact, #[serde(rename = "contactRegistrant")] pub contact_registrant: Contact, #[serde(rename = "contactTech")] pub contact_tech: Contact, #[serde(rename = "registrationStatus", default, skip_serializing_if = "Option::is_none")] pub registration_status: Option<properties::RegistrationStatus>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "nameServers", default, skip_serializing_if = "Vec::is_empty")] pub name_servers: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub privacy: Option<bool>, #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, #[serde(rename = "lastRenewedTime", default, skip_serializing_if = "Option::is_none")] pub last_renewed_time: Option<String>, #[serde(rename = "autoRenew", default, skip_serializing_if = "Option::is_none")] pub auto_renew: Option<bool>, #[serde(rename = "readyForDnsRecordManagement", default, skip_serializing_if = "Option::is_none")] pub ready_for_dns_record_management: Option<bool>, #[serde(rename = "managedHostNames", default, skip_serializing_if = "Vec::is_empty")] pub managed_host_names: Vec<HostName>, pub consent: DomainPurchaseConsent, #[serde(rename = "domainNotRenewableReasons", default, skip_serializing_if = "Vec::is_empty")] pub domain_not_renewable_reasons: Vec<String>, #[serde(rename = "dnsType", default, skip_serializing_if = "Option::is_none")] pub dns_type: Option<properties::DnsType>, #[serde(rename = "dnsZoneId", default, skip_serializing_if = "Option::is_none")] pub dns_zone_id: Option<String>, #[serde(rename = "targetDnsType", default, skip_serializing_if = "Option::is_none")] pub target_dns_type: Option<properties::TargetDnsType>, #[serde(rename = "authCode", default, skip_serializing_if = "Option::is_none")] pub auth_code: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RegistrationStatus { Active, Awaiting, Cancelled, Confiscated, Disabled, Excluded, Expired, Failed, Held, Locked, Parked, Pending, Reserved, Reverted, Suspended, Transferred, Unknown, Unlocked, Unparked, Updated, JsonConverterFailed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DnsType { AzureDns, DefaultDomainRegistrarDns, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TargetDnsType { AzureDns, DefaultDomainRegistrarDns, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainAvailabilityCheckResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub available: Option<bool>, #[serde(rename = "domainType", default, skip_serializing_if = "Option::is_none")] pub domain_type: Option<domain_availability_check_result::DomainType>, } pub mod domain_availability_check_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DomainType { Regular, SoftDeleted, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainCollection { pub value: Vec<Domain>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainControlCenterSsoRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(rename = "postParameterKey", default, skip_serializing_if = "Option::is_none")] pub post_parameter_key: Option<String>, #[serde(rename = "postParameterValue", default, skip_serializing_if = "Option::is_none")] pub post_parameter_value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainOwnershipIdentifier { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<domain_ownership_identifier::Properties>, } pub mod domain_ownership_identifier { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "ownershipId", default, skip_serializing_if = "Option::is_none")] pub ownership_id: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainOwnershipIdentifierCollection { pub value: Vec<DomainOwnershipIdentifier>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainPatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<domain_patch_resource::Properties>, } pub mod domain_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "contactAdmin")] pub contact_admin: Contact, #[serde(rename = "contactBilling")] pub contact_billing: Contact, #[serde(rename = "contactRegistrant")] pub contact_registrant: Contact, #[serde(rename = "contactTech")] pub contact_tech: Contact, #[serde(rename = "registrationStatus", default, skip_serializing_if = "Option::is_none")] pub registration_status: Option<properties::RegistrationStatus>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "nameServers", default, skip_serializing_if = "Vec::is_empty")] pub name_servers: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub privacy: Option<bool>, #[serde(rename = "createdTime", default, skip_serializing_if = "Option::is_none")] pub created_time: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, #[serde(rename = "lastRenewedTime", default, skip_serializing_if = "Option::is_none")] pub last_renewed_time: Option<String>, #[serde(rename = "autoRenew", default, skip_serializing_if = "Option::is_none")] pub auto_renew: Option<bool>, #[serde(rename = "readyForDnsRecordManagement", default, skip_serializing_if = "Option::is_none")] pub ready_for_dns_record_management: Option<bool>, #[serde(rename = "managedHostNames", default, skip_serializing_if = "Vec::is_empty")] pub managed_host_names: Vec<HostName>, pub consent: DomainPurchaseConsent, #[serde(rename = "domainNotRenewableReasons", default, skip_serializing_if = "Vec::is_empty")] pub domain_not_renewable_reasons: Vec<String>, #[serde(rename = "dnsType", default, skip_serializing_if = "Option::is_none")] pub dns_type: Option<properties::DnsType>, #[serde(rename = "dnsZoneId", default, skip_serializing_if = "Option::is_none")] pub dns_zone_id: Option<String>, #[serde(rename = "targetDnsType", default, skip_serializing_if = "Option::is_none")] pub target_dns_type: Option<properties::TargetDnsType>, #[serde(rename = "authCode", default, skip_serializing_if = "Option::is_none")] pub auth_code: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RegistrationStatus { Active, Awaiting, Cancelled, Confiscated, Disabled, Excluded, Expired, Failed, Held, Locked, Parked, Pending, Reserved, Reverted, Suspended, Transferred, Unknown, Unlocked, Unparked, Updated, JsonConverterFailed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DnsType { AzureDns, DefaultDomainRegistrarDns, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TargetDnsType { AzureDns, DefaultDomainRegistrarDns, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainPurchaseConsent { #[serde(rename = "agreementKeys", default, skip_serializing_if = "Vec::is_empty")] pub agreement_keys: Vec<String>, #[serde(rename = "agreedBy", default, skip_serializing_if = "Option::is_none")] pub agreed_by: Option<String>, #[serde(rename = "agreedAt", default, skip_serializing_if = "Option::is_none")] pub agreed_at: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DomainRecommendationSearchParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub keywords: Option<String>, #[serde(rename = "maxDomainRecommendations", default, skip_serializing_if = "Option::is_none")] pub max_domain_recommendations: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostName { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "siteNames", default, skip_serializing_if = "Vec::is_empty")] pub site_names: Vec<String>, #[serde(rename = "azureResourceName", default, skip_serializing_if = "Option::is_none")] pub azure_resource_name: Option<String>, #[serde(rename = "azureResourceType", default, skip_serializing_if = "Option::is_none")] pub azure_resource_type: Option<host_name::AzureResourceType>, #[serde(rename = "customHostNameDnsRecordType", default, skip_serializing_if = "Option::is_none")] pub custom_host_name_dns_record_type: Option<host_name::CustomHostNameDnsRecordType>, #[serde(rename = "hostNameType", default, skip_serializing_if = "Option::is_none")] pub host_name_type: Option<host_name::HostNameType>, } pub mod host_name { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AzureResourceType { Website, TrafficManager, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CustomHostNameDnsRecordType { CName, A, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum HostNameType { Verified, Managed, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NameIdentifierCollection { pub value: Vec<NameIdentifier>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TldLegalAgreement { #[serde(rename = "agreementKey")] pub agreement_key: String, pub title: String, pub content: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TldLegalAgreementCollection { pub value: Vec<TldLegalAgreement>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TopLevelDomain { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<top_level_domain::Properties>, } pub mod top_level_domain { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub privacy: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TopLevelDomainAgreementOption { #[serde(rename = "includePrivacy", default, skip_serializing_if = "Option::is_none")] pub include_privacy: Option<bool>, #[serde(rename = "forTransfer", default, skip_serializing_if = "Option::is_none")] pub for_transfer: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TopLevelDomainCollection { pub value: Vec<TopLevelDomain>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Certificate { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<certificate::Properties>, } pub mod certificate { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "subjectName", default, skip_serializing_if = "Option::is_none")] pub subject_name: Option<String>, #[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")] pub host_names: Vec<String>, #[serde(rename = "pfxBlob", default, skip_serializing_if = "Option::is_none")] pub pfx_blob: Option<String>, #[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")] pub site_name: Option<String>, #[serde(rename = "selfLink", default, skip_serializing_if = "Option::is_none")] pub self_link: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "issueDate", default, skip_serializing_if = "Option::is_none")] pub issue_date: Option<String>, #[serde(rename = "expirationDate", default, skip_serializing_if = "Option::is_none")] pub expiration_date: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub valid: Option<bool>, #[serde(rename = "cerBlob", default, skip_serializing_if = "Option::is_none")] pub cer_blob: Option<String>, #[serde(rename = "publicKeyHash", default, skip_serializing_if = "Option::is_none")] pub public_key_hash: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")] pub key_vault_id: Option<String>, #[serde(rename = "keyVaultSecretName", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_name: Option<String>, #[serde(rename = "keyVaultSecretStatus", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_status: Option<properties::KeyVaultSecretStatus>, #[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")] pub server_farm_id: Option<String>, #[serde(rename = "canonicalName", default, skip_serializing_if = "Option::is_none")] pub canonical_name: Option<String>, #[serde(rename = "domainValidationMethod", default, skip_serializing_if = "Option::is_none")] pub domain_validation_method: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeyVaultSecretStatus { Initialized, WaitingOnCertificateOrder, Succeeded, CertificateOrderFailed, OperationNotPermittedOnKeyVault, AzureServiceUnauthorizedToAccessKeyVault, KeyVaultDoesNotExist, KeyVaultSecretDoesNotExist, UnknownError, ExternalPrivateKey, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateCollection { pub value: Vec<Certificate>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificatePatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<certificate_patch_resource::Properties>, } pub mod certificate_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "subjectName", default, skip_serializing_if = "Option::is_none")] pub subject_name: Option<String>, #[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")] pub host_names: Vec<String>, #[serde(rename = "pfxBlob", default, skip_serializing_if = "Option::is_none")] pub pfx_blob: Option<String>, #[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")] pub site_name: Option<String>, #[serde(rename = "selfLink", default, skip_serializing_if = "Option::is_none")] pub self_link: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "issueDate", default, skip_serializing_if = "Option::is_none")] pub issue_date: Option<String>, #[serde(rename = "expirationDate", default, skip_serializing_if = "Option::is_none")] pub expiration_date: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub valid: Option<bool>, #[serde(rename = "cerBlob", default, skip_serializing_if = "Option::is_none")] pub cer_blob: Option<String>, #[serde(rename = "publicKeyHash", default, skip_serializing_if = "Option::is_none")] pub public_key_hash: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "keyVaultId", default, skip_serializing_if = "Option::is_none")] pub key_vault_id: Option<String>, #[serde(rename = "keyVaultSecretName", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_name: Option<String>, #[serde(rename = "keyVaultSecretStatus", default, skip_serializing_if = "Option::is_none")] pub key_vault_secret_status: Option<properties::KeyVaultSecretStatus>, #[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")] pub server_farm_id: Option<String>, #[serde(rename = "canonicalName", default, skip_serializing_if = "Option::is_none")] pub canonical_name: Option<String>, #[serde(rename = "domainValidationMethod", default, skip_serializing_if = "Option::is_none")] pub domain_validation_method: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum KeyVaultSecretStatus { Initialized, WaitingOnCertificateOrder, Succeeded, CertificateOrderFailed, OperationNotPermittedOnKeyVault, AzureServiceUnauthorizedToAccessKeyVault, KeyVaultDoesNotExist, KeyVaultSecretDoesNotExist, UnknownError, ExternalPrivateKey, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeletedWebAppCollection { pub value: Vec<DeletedSite>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AbnormalTimePeriod { #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub events: Vec<DetectorAbnormalTimePeriod>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub solutions: Vec<Solution>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalysisData { #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(rename = "detectorDefinition", default, skip_serializing_if = "Option::is_none")] pub detector_definition: Option<DetectorDefinition>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub metrics: Vec<DiagnosticMetricSet>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub data: Vec<Vec<NameValuePair>>, #[serde(rename = "detectorMetaData", default, skip_serializing_if = "Option::is_none")] pub detector_meta_data: Option<ResponseMetaData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AnalysisDefinition { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<analysis_definition::Properties>, } pub mod analysis_definition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DataSource { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub instructions: Vec<String>, #[serde(rename = "dataSourceUri", default, skip_serializing_if = "Vec::is_empty")] pub data_source_uri: Vec<NameValuePair>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DetectorAbnormalTimePeriod { #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub priority: Option<f64>, #[serde(rename = "metaData", default, skip_serializing_if = "Vec::is_empty")] pub meta_data: Vec<Vec<NameValuePair>>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<detector_abnormal_time_period::Type>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub solutions: Vec<Solution>, } pub mod detector_abnormal_time_period { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { ServiceIncident, AppDeployment, AppCrash, RuntimeIssueDetected, AseDeployment, UserIssue, PlatformIssue, Other, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DetectorDefinition { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<detector_definition::Properties>, } pub mod detector_definition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub rank: Option<f64>, #[serde(rename = "isEnabled", default, skip_serializing_if = "Option::is_none")] pub is_enabled: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticAnalysis { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<diagnostic_analysis::Properties>, } pub mod diagnostic_analysis { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "abnormalTimePeriods", default, skip_serializing_if = "Vec::is_empty")] pub abnormal_time_periods: Vec<AbnormalTimePeriod>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub payload: Vec<AnalysisData>, #[serde(rename = "nonCorrelatedDetectors", default, skip_serializing_if = "Vec::is_empty")] pub non_correlated_detectors: Vec<DetectorDefinition>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticAnalysisCollection { pub value: Vec<AnalysisDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticCategory { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<diagnostic_category::Properties>, } pub mod diagnostic_category { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticCategoryCollection { pub value: Vec<DiagnosticCategory>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticDetectorCollection { pub value: Vec<DetectorDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticDetectorResponse { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<diagnostic_detector_response::Properties>, } pub mod diagnostic_detector_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "issueDetected", default, skip_serializing_if = "Option::is_none")] pub issue_detected: Option<bool>, #[serde(rename = "detectorDefinition", default, skip_serializing_if = "Option::is_none")] pub detector_definition: Option<DetectorDefinition>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub metrics: Vec<DiagnosticMetricSet>, #[serde(rename = "abnormalTimePeriods", default, skip_serializing_if = "Vec::is_empty")] pub abnormal_time_periods: Vec<DetectorAbnormalTimePeriod>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub data: Vec<Vec<NameValuePair>>, #[serde(rename = "responseMetaData", default, skip_serializing_if = "Option::is_none")] pub response_meta_data: Option<ResponseMetaData>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticMetricSample { #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(rename = "roleInstance", default, skip_serializing_if = "Option::is_none")] pub role_instance: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub total: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub maximum: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub minimum: Option<f64>, #[serde(rename = "isAggregated", default, skip_serializing_if = "Option::is_none")] pub is_aggregated: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DiagnosticMetricSet { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<DiagnosticMetricSample>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResponseMetaData { #[serde(rename = "dataSource", default, skip_serializing_if = "Option::is_none")] pub data_source: Option<DataSource>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Solution { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<f64>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub order: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<solution::Type>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub data: Vec<Vec<NameValuePair>>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub metadata: Vec<Vec<NameValuePair>>, } pub mod solution { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { QuickSolution, DeepInvestigation, BestPractices, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppInsightsWebAppStackSettings { #[serde(rename = "isSupported", default, skip_serializing_if = "Option::is_none")] pub is_supported: Option<bool>, #[serde(rename = "isDefaultOff", default, skip_serializing_if = "Option::is_none")] pub is_default_off: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplicationStack { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub dependency: Option<String>, #[serde(rename = "majorVersions", default, skip_serializing_if = "Vec::is_empty")] pub major_versions: Vec<StackMajorVersion>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub frameworks: Vec<ApplicationStack>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Vec::is_empty")] pub is_deprecated: Vec<ApplicationStack>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplicationStackCollection { pub value: Vec<ApplicationStackResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplicationStackResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ApplicationStack>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppMajorVersion { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "minorVersions", default, skip_serializing_if = "Vec::is_empty")] pub minor_versions: Vec<FunctionAppMinorVersion>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppMinorVersion { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "stackSettings", default, skip_serializing_if = "Option::is_none")] pub stack_settings: Option<FunctionAppRuntimes>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppRuntimeSettings { #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "remoteDebuggingSupported", default, skip_serializing_if = "Option::is_none")] pub remote_debugging_supported: Option<bool>, #[serde(rename = "appInsightsSettings", default, skip_serializing_if = "Option::is_none")] pub app_insights_settings: Option<AppInsightsWebAppStackSettings>, #[serde(rename = "gitHubActionSettings", default, skip_serializing_if = "Option::is_none")] pub git_hub_action_settings: Option<GitHubActionWebAppStackSettings>, #[serde(rename = "appSettingsDictionary", default, skip_serializing_if = "Option::is_none")] pub app_settings_dictionary: Option<serde_json::Value>, #[serde(rename = "siteConfigPropertiesDictionary", default, skip_serializing_if = "Option::is_none")] pub site_config_properties_dictionary: Option<SiteConfigPropertiesDictionary>, #[serde(rename = "supportedFunctionsExtensionVersions", default, skip_serializing_if = "Vec::is_empty")] pub supported_functions_extension_versions: Vec<String>, #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Option::is_none")] pub is_deprecated: Option<bool>, #[serde(rename = "isHidden", default, skip_serializing_if = "Option::is_none")] pub is_hidden: Option<bool>, #[serde(rename = "endOfLifeDate", default, skip_serializing_if = "Option::is_none")] pub end_of_life_date: Option<String>, #[serde(rename = "isAutoUpdate", default, skip_serializing_if = "Option::is_none")] pub is_auto_update: Option<bool>, #[serde(rename = "isEarlyAccess", default, skip_serializing_if = "Option::is_none")] pub is_early_access: Option<bool>, #[serde(rename = "isDefault", default, skip_serializing_if = "Option::is_none")] pub is_default: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppRuntimes { #[serde(rename = "linuxRuntimeSettings", default, skip_serializing_if = "Option::is_none")] pub linux_runtime_settings: Option<FunctionAppRuntimeSettings>, #[serde(rename = "windowsRuntimeSettings", default, skip_serializing_if = "Option::is_none")] pub windows_runtime_settings: Option<FunctionAppRuntimeSettings>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppStack { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<function_app_stack::Properties>, } pub mod function_app_stack { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "majorVersions", default, skip_serializing_if = "Vec::is_empty")] pub major_versions: Vec<FunctionAppMajorVersion>, #[serde(rename = "preferredOs", default, skip_serializing_if = "Option::is_none")] pub preferred_os: Option<properties::PreferredOs>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PreferredOs { Windows, Linux, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionAppStackCollection { pub value: Vec<FunctionAppStack>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitHubActionWebAppStackSettings { #[serde(rename = "isSupported", default, skip_serializing_if = "Option::is_none")] pub is_supported: Option<bool>, #[serde(rename = "supportedVersion", default, skip_serializing_if = "Option::is_none")] pub supported_version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LinuxJavaContainerSettings { #[serde(rename = "java11Runtime", default, skip_serializing_if = "Option::is_none")] pub java11_runtime: Option<String>, #[serde(rename = "java8Runtime", default, skip_serializing_if = "Option::is_none")] pub java8_runtime: Option<String>, #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Option::is_none")] pub is_deprecated: Option<bool>, #[serde(rename = "isHidden", default, skip_serializing_if = "Option::is_none")] pub is_hidden: Option<bool>, #[serde(rename = "endOfLifeDate", default, skip_serializing_if = "Option::is_none")] pub end_of_life_date: Option<String>, #[serde(rename = "isAutoUpdate", default, skip_serializing_if = "Option::is_none")] pub is_auto_update: Option<bool>, #[serde(rename = "isEarlyAccess", default, skip_serializing_if = "Option::is_none")] pub is_early_access: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfigPropertiesDictionary { #[serde(rename = "use32BitWorkerProcess", default, skip_serializing_if = "Option::is_none")] pub use32_bit_worker_process: Option<bool>, #[serde(rename = "linuxFxVersion", default, skip_serializing_if = "Option::is_none")] pub linux_fx_version: Option<String>, #[serde(rename = "javaVersion", default, skip_serializing_if = "Option::is_none")] pub java_version: Option<String>, #[serde(rename = "powerShellVersion", default, skip_serializing_if = "Option::is_none")] pub power_shell_version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StackMajorVersion { #[serde(rename = "displayVersion", default, skip_serializing_if = "Option::is_none")] pub display_version: Option<String>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "isDefault", default, skip_serializing_if = "Option::is_none")] pub is_default: Option<bool>, #[serde(rename = "minorVersions", default, skip_serializing_if = "Vec::is_empty")] pub minor_versions: Vec<StackMinorVersion>, #[serde(rename = "applicationInsights", default, skip_serializing_if = "Option::is_none")] pub application_insights: Option<bool>, #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Option::is_none")] pub is_deprecated: Option<bool>, #[serde(rename = "isHidden", default, skip_serializing_if = "Option::is_none")] pub is_hidden: Option<bool>, #[serde(rename = "appSettingsDictionary", default, skip_serializing_if = "Option::is_none")] pub app_settings_dictionary: Option<serde_json::Value>, #[serde(rename = "siteConfigPropertiesDictionary", default, skip_serializing_if = "Option::is_none")] pub site_config_properties_dictionary: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StackMinorVersion { #[serde(rename = "displayVersion", default, skip_serializing_if = "Option::is_none")] pub display_version: Option<String>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "isDefault", default, skip_serializing_if = "Option::is_none")] pub is_default: Option<bool>, #[serde(rename = "isRemoteDebuggingEnabled", default, skip_serializing_if = "Option::is_none")] pub is_remote_debugging_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppMajorVersion { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "minorVersions", default, skip_serializing_if = "Vec::is_empty")] pub minor_versions: Vec<WebAppMinorVersion>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppMinorVersion { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "stackSettings", default, skip_serializing_if = "Option::is_none")] pub stack_settings: Option<WebAppRuntimes>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppRuntimeSettings { #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "remoteDebuggingSupported", default, skip_serializing_if = "Option::is_none")] pub remote_debugging_supported: Option<bool>, #[serde(rename = "appInsightsSettings", default, skip_serializing_if = "Option::is_none")] pub app_insights_settings: Option<AppInsightsWebAppStackSettings>, #[serde(rename = "gitHubActionSettings", default, skip_serializing_if = "Option::is_none")] pub git_hub_action_settings: Option<GitHubActionWebAppStackSettings>, #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Option::is_none")] pub is_deprecated: Option<bool>, #[serde(rename = "isHidden", default, skip_serializing_if = "Option::is_none")] pub is_hidden: Option<bool>, #[serde(rename = "endOfLifeDate", default, skip_serializing_if = "Option::is_none")] pub end_of_life_date: Option<String>, #[serde(rename = "isAutoUpdate", default, skip_serializing_if = "Option::is_none")] pub is_auto_update: Option<bool>, #[serde(rename = "isEarlyAccess", default, skip_serializing_if = "Option::is_none")] pub is_early_access: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppRuntimes { #[serde(rename = "linuxRuntimeSettings", default, skip_serializing_if = "Option::is_none")] pub linux_runtime_settings: Option<WebAppRuntimeSettings>, #[serde(rename = "windowsRuntimeSettings", default, skip_serializing_if = "Option::is_none")] pub windows_runtime_settings: Option<WebAppRuntimeSettings>, #[serde(rename = "linuxContainerSettings", default, skip_serializing_if = "Option::is_none")] pub linux_container_settings: Option<LinuxJavaContainerSettings>, #[serde(rename = "windowsContainerSettings", default, skip_serializing_if = "Option::is_none")] pub windows_container_settings: Option<WindowsJavaContainerSettings>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppStack { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<web_app_stack::Properties>, } pub mod web_app_stack { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "displayText", default, skip_serializing_if = "Option::is_none")] pub display_text: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "majorVersions", default, skip_serializing_if = "Vec::is_empty")] pub major_versions: Vec<WebAppMajorVersion>, #[serde(rename = "preferredOs", default, skip_serializing_if = "Option::is_none")] pub preferred_os: Option<properties::PreferredOs>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PreferredOs { Windows, Linux, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppStackCollection { pub value: Vec<WebAppStack>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WindowsJavaContainerSettings { #[serde(rename = "javaContainer", default, skip_serializing_if = "Option::is_none")] pub java_container: Option<String>, #[serde(rename = "javaContainerVersion", default, skip_serializing_if = "Option::is_none")] pub java_container_version: Option<String>, #[serde(rename = "isPreview", default, skip_serializing_if = "Option::is_none")] pub is_preview: Option<bool>, #[serde(rename = "isDeprecated", default, skip_serializing_if = "Option::is_none")] pub is_deprecated: Option<bool>, #[serde(rename = "isHidden", default, skip_serializing_if = "Option::is_none")] pub is_hidden: Option<bool>, #[serde(rename = "endOfLifeDate", default, skip_serializing_if = "Option::is_none")] pub end_of_life_date: Option<String>, #[serde(rename = "isAutoUpdate", default, skip_serializing_if = "Option::is_none")] pub is_auto_update: Option<bool>, #[serde(rename = "isEarlyAccess", default, skip_serializing_if = "Option::is_none")] pub is_early_access: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Recommendation { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<recommendation::Properties>, } pub mod recommendation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")] pub creation_time: Option<String>, #[serde(rename = "recommendationId", default, skip_serializing_if = "Option::is_none")] pub recommendation_id: Option<String>, #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(rename = "resourceScope", default, skip_serializing_if = "Option::is_none")] pub resource_scope: Option<properties::ResourceScope>, #[serde(rename = "ruleName", default, skip_serializing_if = "Option::is_none")] pub rule_name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<properties::Level>, #[serde(default, skip_serializing_if = "Option::is_none")] pub channels: Option<properties::Channels>, #[serde(rename = "categoryTags", default, skip_serializing_if = "Vec::is_empty")] pub category_tags: Vec<String>, #[serde(rename = "actionName", default, skip_serializing_if = "Option::is_none")] pub action_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<i32>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub states: Vec<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "nextNotificationTime", default, skip_serializing_if = "Option::is_none")] pub next_notification_time: Option<String>, #[serde(rename = "notificationExpirationTime", default, skip_serializing_if = "Option::is_none")] pub notification_expiration_time: Option<String>, #[serde(rename = "notifiedTime", default, skip_serializing_if = "Option::is_none")] pub notified_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub score: Option<f64>, #[serde(rename = "isDynamic", default, skip_serializing_if = "Option::is_none")] pub is_dynamic: Option<bool>, #[serde(rename = "extensionName", default, skip_serializing_if = "Option::is_none")] pub extension_name: Option<String>, #[serde(rename = "bladeName", default, skip_serializing_if = "Option::is_none")] pub blade_name: Option<String>, #[serde(rename = "forwardLink", default, skip_serializing_if = "Option::is_none")] pub forward_link: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ResourceScope { ServerFarm, Subscription, WebSite, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Level { Critical, Warning, Information, NonUrgentSuggestion, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Channels { Notification, Api, Email, Webhook, All, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RecommendationCollection { pub value: Vec<Recommendation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RecommendationRule { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<recommendation_rule::Properties>, } pub mod recommendation_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "recommendationName", default, skip_serializing_if = "Option::is_none")] pub recommendation_name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "recommendationId", default, skip_serializing_if = "Option::is_none")] pub recommendation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "actionName", default, skip_serializing_if = "Option::is_none")] pub action_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<properties::Level>, #[serde(default, skip_serializing_if = "Option::is_none")] pub channels: Option<properties::Channels>, #[serde(rename = "categoryTags", default, skip_serializing_if = "Vec::is_empty")] pub category_tags: Vec<String>, #[serde(rename = "isDynamic", default, skip_serializing_if = "Option::is_none")] pub is_dynamic: Option<bool>, #[serde(rename = "extensionName", default, skip_serializing_if = "Option::is_none")] pub extension_name: Option<String>, #[serde(rename = "bladeName", default, skip_serializing_if = "Option::is_none")] pub blade_name: Option<String>, #[serde(rename = "forwardLink", default, skip_serializing_if = "Option::is_none")] pub forward_link: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Level { Critical, Warning, Information, NonUrgentSuggestion, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Channels { Notification, Api, Email, Webhook, All, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppserviceGithubToken { #[serde(rename = "accessToken", default, skip_serializing_if = "Option::is_none")] pub access_token: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(rename = "tokenType", default, skip_serializing_if = "Option::is_none")] pub token_type: Option<String>, #[serde(rename = "gotToken", default, skip_serializing_if = "Option::is_none")] pub got_token: Option<bool>, #[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppserviceGithubTokenRequest { pub code: String, pub state: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BillingMeter { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<billing_meter::Properties>, } pub mod billing_meter { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "meterId", default, skip_serializing_if = "Option::is_none")] pub meter_id: Option<String>, #[serde(rename = "billingLocation", default, skip_serializing_if = "Option::is_none")] pub billing_location: Option<String>, #[serde(rename = "shortName", default, skip_serializing_if = "Option::is_none")] pub short_name: Option<String>, #[serde(rename = "friendlyName", default, skip_serializing_if = "Option::is_none")] pub friendly_name: Option<String>, #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(rename = "osType", default, skip_serializing_if = "Option::is_none")] pub os_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub multiplier: Option<f64>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BillingMeterCollection { pub value: Vec<BillingMeter>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmMoveResourceEnvelope { #[serde(rename = "targetResourceGroup", default, skip_serializing_if = "Option::is_none")] pub target_resource_group: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub resources: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentLocations { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<GeoRegion>, #[serde(rename = "hostingEnvironments", default, skip_serializing_if = "Vec::is_empty")] pub hosting_environments: Vec<AppServiceEnvironment>, #[serde(rename = "hostingEnvironmentDeploymentInfos", default, skip_serializing_if = "Vec::is_empty")] pub hosting_environment_deployment_infos: Vec<HostingEnvironmentDeploymentInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GeoRegion { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<geo_region::Properties>, } pub mod geo_region { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "orgDomain", default, skip_serializing_if = "Option::is_none")] pub org_domain: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GeoRegionCollection { pub value: Vec<GeoRegion>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GlobalCsmSkuDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub family: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<SkuCapacity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub capabilities: Vec<Capability>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostingEnvironmentDeploymentInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PremierAddOnOffer { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<premier_add_on_offer::Properties>, } pub mod premier_add_on_offer { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option<String>, #[serde(rename = "promoCodeRequired", default, skip_serializing_if = "Option::is_none")] pub promo_code_required: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quota: Option<i32>, #[serde(rename = "webHostingPlanRestrictions", default, skip_serializing_if = "Option::is_none")] pub web_hosting_plan_restrictions: Option<properties::WebHostingPlanRestrictions>, #[serde(rename = "privacyPolicyUrl", default, skip_serializing_if = "Option::is_none")] pub privacy_policy_url: Option<String>, #[serde(rename = "legalTermsUrl", default, skip_serializing_if = "Option::is_none")] pub legal_terms_url: Option<String>, #[serde(rename = "marketplacePublisher", default, skip_serializing_if = "Option::is_none")] pub marketplace_publisher: Option<String>, #[serde(rename = "marketplaceOffer", default, skip_serializing_if = "Option::is_none")] pub marketplace_offer: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WebHostingPlanRestrictions { None, Free, Shared, Basic, Standard, Premium, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PremierAddOnOfferCollection { pub value: Vec<PremierAddOnOffer>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceNameAvailability { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<resource_name_availability::Reason>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } pub mod resource_name_availability { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Reason { Invalid, AlreadyExists, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceNameAvailabilityRequest { pub name: String, #[serde(rename = "type")] pub type_: resource_name_availability_request::Type, #[serde(rename = "isFqdn", default, skip_serializing_if = "Option::is_none")] pub is_fqdn: Option<bool>, } pub mod resource_name_availability_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Site, Slot, HostingEnvironment, PublishingUser, #[serde(rename = "Microsoft.Web/sites")] MicrosoftWebSites, #[serde(rename = "Microsoft.Web/sites/slots")] MicrosoftWebSitesSlots, #[serde(rename = "Microsoft.Web/hostingEnvironments")] MicrosoftWebHostingEnvironments, #[serde(rename = "Microsoft.Web/publishingUsers")] MicrosoftWebPublishingUsers, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuInfos { #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub skus: Vec<GlobalCsmSkuDescription>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceControl { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<source_control::Properties>, } pub mod source_control { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub token: Option<String>, #[serde(rename = "tokenSecret", default, skip_serializing_if = "Option::is_none")] pub token_secret: Option<String>, #[serde(rename = "refreshToken", default, skip_serializing_if = "Option::is_none")] pub refresh_token: Option<String>, #[serde(rename = "expirationTime", default, skip_serializing_if = "Option::is_none")] pub expiration_time: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceControlCollection { pub value: Vec<SourceControl>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ValidateProperties { #[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")] pub server_farm_id: Option<String>, #[serde(rename = "skuName", default, skip_serializing_if = "Option::is_none")] pub sku_name: Option<String>, #[serde(rename = "needLinuxWorkers", default, skip_serializing_if = "Option::is_none")] pub need_linux_workers: Option<bool>, #[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")] pub is_spot: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i32>, #[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")] pub hosting_environment: Option<String>, #[serde(rename = "isXenon", default, skip_serializing_if = "Option::is_none")] pub is_xenon: Option<bool>, #[serde(rename = "containerRegistryBaseUrl", default, skip_serializing_if = "Option::is_none")] pub container_registry_base_url: Option<String>, #[serde(rename = "containerRegistryUsername", default, skip_serializing_if = "Option::is_none")] pub container_registry_username: Option<String>, #[serde(rename = "containerRegistryPassword", default, skip_serializing_if = "Option::is_none")] pub container_registry_password: Option<String>, #[serde(rename = "containerImageRepository", default, skip_serializing_if = "Option::is_none")] pub container_image_repository: Option<String>, #[serde(rename = "containerImageTag", default, skip_serializing_if = "Option::is_none")] pub container_image_tag: Option<String>, #[serde(rename = "containerImagePlatform", default, skip_serializing_if = "Option::is_none")] pub container_image_platform: Option<String>, #[serde(rename = "appServiceEnvironment", default, skip_serializing_if = "Option::is_none")] pub app_service_environment: Option<AppServiceEnvironment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ValidateRequest { pub name: String, #[serde(rename = "type")] pub type_: validate_request::Type, pub location: String, pub properties: ValidateProperties, } pub mod validate_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { ServerFarm, Site, #[serde(rename = "Microsoft.Web/hostingEnvironments")] MicrosoftWebHostingEnvironments, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ValidateResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ValidateResponseError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ValidateResponseError { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetParameters { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_parameters::Properties>, } pub mod vnet_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "vnetResourceGroup", default, skip_serializing_if = "Option::is_none")] pub vnet_resource_group: Option<String>, #[serde(rename = "vnetName", default, skip_serializing_if = "Option::is_none")] pub vnet_name: Option<String>, #[serde(rename = "vnetSubnetName", default, skip_serializing_if = "Option::is_none")] pub vnet_subnet_name: Option<String>, #[serde(rename = "subnetResourceId", default, skip_serializing_if = "Option::is_none")] pub subnet_resource_id: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetValidationFailureDetails { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_validation_failure_details::Properties>, } pub mod vnet_validation_failure_details { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub failed: Option<bool>, #[serde(rename = "failedTests", default, skip_serializing_if = "Vec::is_empty")] pub failed_tests: Vec<VnetValidationTestFailure>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub warnings: Vec<VnetValidationTestFailure>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VnetValidationTestFailure { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<vnet_validation_test_failure::Properties>, } pub mod vnet_validation_test_failure { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "testName", default, skip_serializing_if = "Option::is_none")] pub test_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AllowedAudiencesValidation { #[serde(rename = "allowedAudiences", default, skip_serializing_if = "Vec::is_empty")] pub allowed_audiences: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKvReference { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<api_kv_reference::Properties>, } pub mod api_kv_reference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub reference: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "vaultName", default, skip_serializing_if = "Option::is_none")] pub vault_name: Option<String>, #[serde(rename = "secretName", default, skip_serializing_if = "Option::is_none")] pub secret_name: Option<String>, #[serde(rename = "secretVersion", default, skip_serializing_if = "Option::is_none")] pub secret_version: Option<String>, #[serde(rename = "identityType", default, skip_serializing_if = "Option::is_none")] pub identity_type: Option<ManagedServiceIdentity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<properties::Source>, #[serde(rename = "activeVersion", default, skip_serializing_if = "Option::is_none")] pub active_version: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Initialized, Resolved, InvalidSyntax, #[serde(rename = "MSINotEnabled")] MsiNotEnabled, VaultNotFound, SecretNotFound, SecretVersionNotFound, AccessToKeyVaultDenied, OtherReasons, FetchTimedOut, UnauthorizedClient, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Source { KeyVault, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApiKvReferenceCollection { pub value: Vec<ApiKvReference>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppRegistration { #[serde(rename = "appId", default, skip_serializing_if = "Option::is_none")] pub app_id: Option<String>, #[serde(rename = "appSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub app_secret_setting_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Apple { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<AppleRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<LoginScopes>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppleRegistration { #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[serde(rename = "clientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub client_secret_setting_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ApplicationLogsConfig { #[serde(rename = "fileSystem", default, skip_serializing_if = "Option::is_none")] pub file_system: Option<FileSystemApplicationLogsConfig>, #[serde(rename = "azureTableStorage", default, skip_serializing_if = "Option::is_none")] pub azure_table_storage: Option<AzureTableStorageApplicationLogsConfig>, #[serde(rename = "azureBlobStorage", default, skip_serializing_if = "Option::is_none")] pub azure_blob_storage: Option<AzureBlobStorageApplicationLogsConfig>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthPlatform { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "configFilePath", default, skip_serializing_if = "Option::is_none")] pub config_file_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureActiveDirectory { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<AzureActiveDirectoryRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<AzureActiveDirectoryLogin>, #[serde(default, skip_serializing_if = "Option::is_none")] pub validation: Option<AzureActiveDirectoryValidation>, #[serde(rename = "isAutoProvisioned", default, skip_serializing_if = "Option::is_none")] pub is_auto_provisioned: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureActiveDirectoryLogin { #[serde(rename = "loginParameters", default, skip_serializing_if = "Vec::is_empty")] pub login_parameters: Vec<String>, #[serde(rename = "disableWWWAuthenticate", default, skip_serializing_if = "Option::is_none")] pub disable_www_authenticate: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureActiveDirectoryRegistration { #[serde(rename = "openIdIssuer", default, skip_serializing_if = "Option::is_none")] pub open_id_issuer: Option<String>, #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[serde(rename = "clientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub client_secret_setting_name: Option<String>, #[serde(rename = "clientSecretCertificateThumbprint", default, skip_serializing_if = "Option::is_none")] pub client_secret_certificate_thumbprint: Option<String>, #[serde( rename = "clientSecretCertificateSubjectAlternativeName", default, skip_serializing_if = "Option::is_none" )] pub client_secret_certificate_subject_alternative_name: Option<String>, #[serde(rename = "clientSecretCertificateIssuer", default, skip_serializing_if = "Option::is_none")] pub client_secret_certificate_issuer: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureActiveDirectoryValidation { #[serde(rename = "jwtClaimChecks", default, skip_serializing_if = "Option::is_none")] pub jwt_claim_checks: Option<JwtClaimChecks>, #[serde(rename = "allowedAudiences", default, skip_serializing_if = "Vec::is_empty")] pub allowed_audiences: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureBlobStorageApplicationLogsConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<azure_blob_storage_application_logs_config::Level>, #[serde(rename = "sasUrl", default, skip_serializing_if = "Option::is_none")] pub sas_url: Option<String>, #[serde(rename = "retentionInDays", default, skip_serializing_if = "Option::is_none")] pub retention_in_days: Option<i32>, } pub mod azure_blob_storage_application_logs_config { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Level { Off, Verbose, Information, Warning, Error, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureBlobStorageHttpLogsConfig { #[serde(rename = "sasUrl", default, skip_serializing_if = "Option::is_none")] pub sas_url: Option<String>, #[serde(rename = "retentionInDays", default, skip_serializing_if = "Option::is_none")] pub retention_in_days: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureStaticWebApps { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<AzureStaticWebAppsRegistration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureStaticWebAppsRegistration { #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureStoragePropertyDictionaryResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AzureTableStorageApplicationLogsConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<azure_table_storage_application_logs_config::Level>, #[serde(rename = "sasUrl")] pub sas_url: String, } pub mod azure_table_storage_application_logs_config { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Level { Off, Verbose, Information, Warning, Error, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BackupItem { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<backup_item::Properties>, } pub mod backup_item { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<i32>, #[serde(rename = "storageAccountUrl", default, skip_serializing_if = "Option::is_none")] pub storage_account_url: Option<String>, #[serde(rename = "blobName", default, skip_serializing_if = "Option::is_none")] pub blob_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "sizeInBytes", default, skip_serializing_if = "Option::is_none")] pub size_in_bytes: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub log: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub databases: Vec<DatabaseBackupSetting>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scheduled: Option<bool>, #[serde(rename = "lastRestoreTimeStamp", default, skip_serializing_if = "Option::is_none")] pub last_restore_time_stamp: Option<String>, #[serde(rename = "finishedTimeStamp", default, skip_serializing_if = "Option::is_none")] pub finished_time_stamp: Option<String>, #[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")] pub correlation_id: Option<String>, #[serde(rename = "websiteSizeInBytes", default, skip_serializing_if = "Option::is_none")] pub website_size_in_bytes: Option<i64>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { InProgress, Failed, Succeeded, TimedOut, Created, Skipped, PartiallySucceeded, DeleteInProgress, DeleteFailed, Deleted, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BackupItemCollection { pub value: Vec<BackupItem>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BackupRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<backup_request::Properties>, } pub mod backup_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "backupName", default, skip_serializing_if = "Option::is_none")] pub backup_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "storageAccountUrl")] pub storage_account_url: String, #[serde(rename = "backupSchedule", default, skip_serializing_if = "Option::is_none")] pub backup_schedule: Option<BackupSchedule>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub databases: Vec<DatabaseBackupSetting>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BackupSchedule { #[serde(rename = "frequencyInterval")] pub frequency_interval: i32, #[serde(rename = "frequencyUnit")] pub frequency_unit: backup_schedule::FrequencyUnit, #[serde(rename = "keepAtLeastOneBackup")] pub keep_at_least_one_backup: bool, #[serde(rename = "retentionPeriodInDays")] pub retention_period_in_days: i32, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "lastExecutionTime", default, skip_serializing_if = "Option::is_none")] pub last_execution_time: Option<String>, } pub mod backup_schedule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum FrequencyUnit { Day, Hour, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BlobStorageTokenStore { #[serde(rename = "sasUrlSettingName", default, skip_serializing_if = "Option::is_none")] pub sas_url_setting_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ClientRegistration { #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[serde(rename = "clientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub client_secret_setting_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnStringValueTypePair { pub value: String, #[serde(rename = "type")] pub type_: conn_string_value_type_pair::Type, } pub mod conn_string_value_type_pair { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { MySql, #[serde(rename = "SQLServer")] SqlServer, #[serde(rename = "SQLAzure")] SqlAzure, Custom, NotificationHub, ServiceBus, EventHub, ApiHub, DocDb, RedisCache, #[serde(rename = "PostgreSQL")] PostgreSql, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectionStringDictionary { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerCpuStatistics { #[serde(rename = "cpuUsage", default, skip_serializing_if = "Option::is_none")] pub cpu_usage: Option<ContainerCpuUsage>, #[serde(rename = "systemCpuUsage", default, skip_serializing_if = "Option::is_none")] pub system_cpu_usage: Option<i64>, #[serde(rename = "onlineCpuCount", default, skip_serializing_if = "Option::is_none")] pub online_cpu_count: Option<i32>, #[serde(rename = "throttlingData", default, skip_serializing_if = "Option::is_none")] pub throttling_data: Option<ContainerThrottlingData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerCpuUsage { #[serde(rename = "totalUsage", default, skip_serializing_if = "Option::is_none")] pub total_usage: Option<i64>, #[serde(rename = "perCpuUsage", default, skip_serializing_if = "Vec::is_empty")] pub per_cpu_usage: Vec<i64>, #[serde(rename = "kernelModeUsage", default, skip_serializing_if = "Option::is_none")] pub kernel_mode_usage: Option<i64>, #[serde(rename = "userModeUsage", default, skip_serializing_if = "Option::is_none")] pub user_mode_usage: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerInfo { #[serde(rename = "currentTimeStamp", default, skip_serializing_if = "Option::is_none")] pub current_time_stamp: Option<String>, #[serde(rename = "previousTimeStamp", default, skip_serializing_if = "Option::is_none")] pub previous_time_stamp: Option<String>, #[serde(rename = "currentCpuStats", default, skip_serializing_if = "Option::is_none")] pub current_cpu_stats: Option<ContainerCpuStatistics>, #[serde(rename = "previousCpuStats", default, skip_serializing_if = "Option::is_none")] pub previous_cpu_stats: Option<ContainerCpuStatistics>, #[serde(rename = "memoryStats", default, skip_serializing_if = "Option::is_none")] pub memory_stats: Option<ContainerMemoryStatistics>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub eth0: Option<ContainerNetworkInterfaceStatistics>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerMemoryStatistics { #[serde(default, skip_serializing_if = "Option::is_none")] pub usage: Option<i64>, #[serde(rename = "maxUsage", default, skip_serializing_if = "Option::is_none")] pub max_usage: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerNetworkInterfaceStatistics { #[serde(rename = "rxBytes", default, skip_serializing_if = "Option::is_none")] pub rx_bytes: Option<i64>, #[serde(rename = "rxPackets", default, skip_serializing_if = "Option::is_none")] pub rx_packets: Option<i64>, #[serde(rename = "rxErrors", default, skip_serializing_if = "Option::is_none")] pub rx_errors: Option<i64>, #[serde(rename = "rxDropped", default, skip_serializing_if = "Option::is_none")] pub rx_dropped: Option<i64>, #[serde(rename = "txBytes", default, skip_serializing_if = "Option::is_none")] pub tx_bytes: Option<i64>, #[serde(rename = "txPackets", default, skip_serializing_if = "Option::is_none")] pub tx_packets: Option<i64>, #[serde(rename = "txErrors", default, skip_serializing_if = "Option::is_none")] pub tx_errors: Option<i64>, #[serde(rename = "txDropped", default, skip_serializing_if = "Option::is_none")] pub tx_dropped: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContainerThrottlingData { #[serde(default, skip_serializing_if = "Option::is_none")] pub periods: Option<i32>, #[serde(rename = "throttledPeriods", default, skip_serializing_if = "Option::is_none")] pub throttled_periods: Option<i32>, #[serde(rename = "throttledTime", default, skip_serializing_if = "Option::is_none")] pub throttled_time: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContinuousWebJob { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<continuous_web_job::Properties>, } pub mod continuous_web_job { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub detailed_status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub log_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub run_command: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extra_info_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub web_job_type: Option<properties::WebJobType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub using_sdk: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub settings: Option<serde_json::Value>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Initializing, Starting, Running, PendingRestart, Stopped, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WebJobType { Continuous, Triggered, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ContinuousWebJobCollection { pub value: Vec<ContinuousWebJob>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CookieExpiration { #[serde(default, skip_serializing_if = "Option::is_none")] pub convention: Option<cookie_expiration::Convention>, #[serde(rename = "timeToExpiration", default, skip_serializing_if = "Option::is_none")] pub time_to_expiration: Option<String>, } pub mod cookie_expiration { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Convention { FixedTime, IdentityProviderDerived, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmPublishingCredentialsPoliciesCollection { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<csm_publishing_credentials_policies_collection::Properties>, } pub mod csm_publishing_credentials_policies_collection { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { pub ftp: CsmPublishingCredentialsPoliciesEntity, pub scm: CsmPublishingCredentialsPoliciesEntity, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmPublishingCredentialsPoliciesEntity { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<csm_publishing_credentials_policies_entity::Properties>, } pub mod csm_publishing_credentials_policies_entity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { pub allow: bool, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmPublishingProfileOptions { #[serde(default, skip_serializing_if = "Option::is_none")] pub format: Option<csm_publishing_profile_options::Format>, #[serde(rename = "includeDisasterRecoveryEndpoints", default, skip_serializing_if = "Option::is_none")] pub include_disaster_recovery_endpoints: Option<bool>, } pub mod csm_publishing_profile_options { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Format { FileZilla3, WebDeploy, Ftp, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CsmSlotEntity { #[serde(rename = "targetSlot")] pub target_slot: String, #[serde(rename = "preserveVnet")] pub preserve_vnet: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomHostnameAnalysisResult { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<custom_hostname_analysis_result::Properties>, } pub mod custom_hostname_analysis_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "isHostnameAlreadyVerified", default, skip_serializing_if = "Option::is_none")] pub is_hostname_already_verified: Option<bool>, #[serde(rename = "customDomainVerificationTest", default, skip_serializing_if = "Option::is_none")] pub custom_domain_verification_test: Option<properties::CustomDomainVerificationTest>, #[serde(rename = "customDomainVerificationFailureInfo", default, skip_serializing_if = "Option::is_none")] pub custom_domain_verification_failure_info: Option<ErrorEntity>, #[serde(rename = "hasConflictOnScaleUnit", default, skip_serializing_if = "Option::is_none")] pub has_conflict_on_scale_unit: Option<bool>, #[serde(rename = "hasConflictAcrossSubscription", default, skip_serializing_if = "Option::is_none")] pub has_conflict_across_subscription: Option<bool>, #[serde(rename = "conflictingAppResourceId", default, skip_serializing_if = "Option::is_none")] pub conflicting_app_resource_id: Option<String>, #[serde(rename = "cNameRecords", default, skip_serializing_if = "Vec::is_empty")] pub c_name_records: Vec<String>, #[serde(rename = "txtRecords", default, skip_serializing_if = "Vec::is_empty")] pub txt_records: Vec<String>, #[serde(rename = "aRecords", default, skip_serializing_if = "Vec::is_empty")] pub a_records: Vec<String>, #[serde(rename = "alternateCNameRecords", default, skip_serializing_if = "Vec::is_empty")] pub alternate_c_name_records: Vec<String>, #[serde(rename = "alternateTxtRecords", default, skip_serializing_if = "Vec::is_empty")] pub alternate_txt_records: Vec<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CustomDomainVerificationTest { Passed, Failed, Skipped, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomOpenIdConnectProvider { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<OpenIdConnectRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<OpenIdConnectLogin>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DatabaseBackupSetting { #[serde(rename = "databaseType")] pub database_type: database_backup_setting::DatabaseType, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "connectionStringName", default, skip_serializing_if = "Option::is_none")] pub connection_string_name: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, } pub mod database_backup_setting { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DatabaseType { SqlAzure, MySql, LocalMySql, PostgreSql, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeletedAppRestoreRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<deleted_app_restore_request::Properties>, } pub mod deleted_app_restore_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "deletedSiteId", default, skip_serializing_if = "Option::is_none")] pub deleted_site_id: Option<String>, #[serde(rename = "recoverConfiguration", default, skip_serializing_if = "Option::is_none")] pub recover_configuration: Option<bool>, #[serde(rename = "snapshotTime", default, skip_serializing_if = "Option::is_none")] pub snapshot_time: Option<String>, #[serde(rename = "useDRSecondary", default, skip_serializing_if = "Option::is_none")] pub use_dr_secondary: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Deployment { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<deployment::Properties>, } pub mod deployment { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub author: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub deployer: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub author_email: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub active: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeploymentCollection { pub value: Vec<Deployment>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnabledConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Facebook { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<AppRegistration>, #[serde(rename = "graphApiVersion", default, skip_serializing_if = "Option::is_none")] pub graph_api_version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<LoginScopes>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileSystemApplicationLogsConfig { #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<file_system_application_logs_config::Level>, } pub mod file_system_application_logs_config { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Level { Off, Verbose, Information, Warning, Error, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileSystemHttpLogsConfig { #[serde(rename = "retentionInMb", default, skip_serializing_if = "Option::is_none")] pub retention_in_mb: Option<i32>, #[serde(rename = "retentionInDays", default, skip_serializing_if = "Option::is_none")] pub retention_in_days: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileSystemTokenStore { #[serde(default, skip_serializing_if = "Option::is_none")] pub directory: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ForwardProxy { #[serde(default, skip_serializing_if = "Option::is_none")] pub convention: Option<forward_proxy::Convention>, #[serde(rename = "customHostHeaderName", default, skip_serializing_if = "Option::is_none")] pub custom_host_header_name: Option<String>, #[serde(rename = "customProtoHeaderName", default, skip_serializing_if = "Option::is_none")] pub custom_proto_header_name: Option<String>, } pub mod forward_proxy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Convention { NoProxy, Standard, Custom, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionEnvelope { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<function_envelope::Properties>, } pub mod function_envelope { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub function_app_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub script_root_path_href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub script_href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub config_href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub test_data_href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub secrets_file_href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub config: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub files: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub test_data: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub invoke_url_template: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option<String>, #[serde(rename = "isDisabled", default, skip_serializing_if = "Option::is_none")] pub is_disabled: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionEnvelopeCollection { pub value: Vec<FunctionEnvelope>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FunctionSecrets { #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger_url: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitHub { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<ClientRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<LoginScopes>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitHubActionCodeConfiguration { #[serde(rename = "runtimeStack", default, skip_serializing_if = "Option::is_none")] pub runtime_stack: Option<String>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitHubActionConfiguration { #[serde(rename = "codeConfiguration", default, skip_serializing_if = "Option::is_none")] pub code_configuration: Option<GitHubActionCodeConfiguration>, #[serde(rename = "containerConfiguration", default, skip_serializing_if = "Option::is_none")] pub container_configuration: Option<GitHubActionContainerConfiguration>, #[serde(rename = "isLinux", default, skip_serializing_if = "Option::is_none")] pub is_linux: Option<bool>, #[serde(rename = "generateWorkflowFile", default, skip_serializing_if = "Option::is_none")] pub generate_workflow_file: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GitHubActionContainerConfiguration { #[serde(rename = "serverUrl", default, skip_serializing_if = "Option::is_none")] pub server_url: Option<String>, #[serde(rename = "imageName", default, skip_serializing_if = "Option::is_none")] pub image_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GlobalValidation { #[serde(rename = "requireAuthentication", default, skip_serializing_if = "Option::is_none")] pub require_authentication: Option<bool>, #[serde(rename = "unauthenticatedClientAction", default, skip_serializing_if = "Option::is_none")] pub unauthenticated_client_action: Option<global_validation::UnauthenticatedClientAction>, #[serde(rename = "redirectToProvider", default, skip_serializing_if = "Option::is_none")] pub redirect_to_provider: Option<String>, #[serde(rename = "excludedPaths", default, skip_serializing_if = "Vec::is_empty")] pub excluded_paths: Vec<String>, } pub mod global_validation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UnauthenticatedClientAction { RedirectToLoginPage, AllowAnonymous, Return401, Return403, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Google { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<ClientRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<LoginScopes>, #[serde(default, skip_serializing_if = "Option::is_none")] pub validation: Option<AllowedAudiencesValidation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostKeys { #[serde(rename = "masterKey", default, skip_serializing_if = "Option::is_none")] pub master_key: Option<String>, #[serde(rename = "functionKeys", default, skip_serializing_if = "Option::is_none")] pub function_keys: Option<serde_json::Value>, #[serde(rename = "systemKeys", default, skip_serializing_if = "Option::is_none")] pub system_keys: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostNameBinding { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<host_name_binding::Properties>, } pub mod host_name_binding { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")] pub site_name: Option<String>, #[serde(rename = "domainId", default, skip_serializing_if = "Option::is_none")] pub domain_id: Option<String>, #[serde(rename = "azureResourceName", default, skip_serializing_if = "Option::is_none")] pub azure_resource_name: Option<String>, #[serde(rename = "azureResourceType", default, skip_serializing_if = "Option::is_none")] pub azure_resource_type: Option<properties::AzureResourceType>, #[serde(rename = "customHostNameDnsRecordType", default, skip_serializing_if = "Option::is_none")] pub custom_host_name_dns_record_type: Option<properties::CustomHostNameDnsRecordType>, #[serde(rename = "hostNameType", default, skip_serializing_if = "Option::is_none")] pub host_name_type: Option<properties::HostNameType>, #[serde(rename = "sslState", default, skip_serializing_if = "Option::is_none")] pub ssl_state: Option<properties::SslState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")] pub virtual_ip: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AzureResourceType { Website, TrafficManager, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CustomHostNameDnsRecordType { CName, A, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum HostNameType { Verified, Managed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SslState { Disabled, SniEnabled, IpBasedEnabled, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostNameBindingCollection { pub value: Vec<HostNameBinding>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HttpLogsConfig { #[serde(rename = "fileSystem", default, skip_serializing_if = "Option::is_none")] pub file_system: Option<FileSystemHttpLogsConfig>, #[serde(rename = "azureBlobStorage", default, skip_serializing_if = "Option::is_none")] pub azure_blob_storage: Option<AzureBlobStorageHttpLogsConfig>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HttpSettings { #[serde(rename = "requireHttps", default, skip_serializing_if = "Option::is_none")] pub require_https: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub routes: Option<HttpSettingsRoutes>, #[serde(rename = "forwardProxy", default, skip_serializing_if = "Option::is_none")] pub forward_proxy: Option<ForwardProxy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HttpSettingsRoutes { #[serde(rename = "apiPrefix", default, skip_serializing_if = "Option::is_none")] pub api_prefix: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IdentityProviders { #[serde(rename = "azureActiveDirectory", default, skip_serializing_if = "Option::is_none")] pub azure_active_directory: Option<AzureActiveDirectory>, #[serde(default, skip_serializing_if = "Option::is_none")] pub facebook: Option<Facebook>, #[serde(rename = "gitHub", default, skip_serializing_if = "Option::is_none")] pub git_hub: Option<GitHub>, #[serde(default, skip_serializing_if = "Option::is_none")] pub google: Option<Google>, #[serde(rename = "legacyMicrosoftAccount", default, skip_serializing_if = "Option::is_none")] pub legacy_microsoft_account: Option<LegacyMicrosoftAccount>, #[serde(default, skip_serializing_if = "Option::is_none")] pub twitter: Option<Twitter>, #[serde(default, skip_serializing_if = "Option::is_none")] pub apple: Option<Apple>, #[serde(rename = "azureStaticWebApps", default, skip_serializing_if = "Option::is_none")] pub azure_static_web_apps: Option<AzureStaticWebApps>, #[serde(rename = "customOpenIdConnectProviders", default, skip_serializing_if = "Option::is_none")] pub custom_open_id_connect_providers: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JwtClaimChecks { #[serde(rename = "allowedGroups", default, skip_serializing_if = "Vec::is_empty")] pub allowed_groups: Vec<String>, #[serde(rename = "allowedClientApplications", default, skip_serializing_if = "Vec::is_empty")] pub allowed_client_applications: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LegacyMicrosoftAccount { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<ClientRegistration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<LoginScopes>, #[serde(default, skip_serializing_if = "Option::is_none")] pub validation: Option<AllowedAudiencesValidation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Login { #[serde(default, skip_serializing_if = "Option::is_none")] pub routes: Option<LoginRoutes>, #[serde(rename = "tokenStore", default, skip_serializing_if = "Option::is_none")] pub token_store: Option<TokenStore>, #[serde(rename = "preserveUrlFragmentsForLogins", default, skip_serializing_if = "Option::is_none")] pub preserve_url_fragments_for_logins: Option<bool>, #[serde(rename = "allowedExternalRedirectUrls", default, skip_serializing_if = "Vec::is_empty")] pub allowed_external_redirect_urls: Vec<String>, #[serde(rename = "cookieExpiration", default, skip_serializing_if = "Option::is_none")] pub cookie_expiration: Option<CookieExpiration>, #[serde(default, skip_serializing_if = "Option::is_none")] pub nonce: Option<Nonce>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LoginRoutes { #[serde(rename = "logoutEndpoint", default, skip_serializing_if = "Option::is_none")] pub logout_endpoint: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LoginScopes { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub scopes: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MsDeploy { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MsDeployCore>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MsDeployCore { #[serde(rename = "packageUri", default, skip_serializing_if = "Option::is_none")] pub package_uri: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "dbType", default, skip_serializing_if = "Option::is_none")] pub db_type: Option<String>, #[serde(rename = "setParametersXmlFileUri", default, skip_serializing_if = "Option::is_none")] pub set_parameters_xml_file_uri: Option<String>, #[serde(rename = "setParameters", default, skip_serializing_if = "Option::is_none")] pub set_parameters: Option<serde_json::Value>, #[serde(rename = "skipAppData", default, skip_serializing_if = "Option::is_none")] pub skip_app_data: Option<bool>, #[serde(rename = "appOffline", default, skip_serializing_if = "Option::is_none")] pub app_offline: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MsDeployLog { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ms_deploy_log::Properties>, } pub mod ms_deploy_log { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub entries: Vec<MsDeployLogEntry>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MsDeployLogEntry { #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<ms_deploy_log_entry::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } pub mod ms_deploy_log_entry { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Message, Warning, Error, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MsDeployStatus { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ms_deploy_status::Properties>, } pub mod ms_deploy_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub deployer: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub complete: Option<bool>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { #[serde(rename = "accepted")] Accepted, #[serde(rename = "running")] Running, #[serde(rename = "succeeded")] Succeeded, #[serde(rename = "failed")] Failed, #[serde(rename = "canceled")] Canceled, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MigrateMySqlRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<migrate_my_sql_request::Properties>, } pub mod migrate_my_sql_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "connectionString")] pub connection_string: String, #[serde(rename = "migrationType")] pub migration_type: properties::MigrationType, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum MigrationType { LocalToRemote, RemoteToLocal, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MigrateMySqlStatus { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<migrate_my_sql_status::Properties>, } pub mod migrate_my_sql_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "migrationOperationStatus", default, skip_serializing_if = "Option::is_none")] pub migration_operation_status: Option<properties::MigrationOperationStatus>, #[serde(rename = "operationId", default, skip_serializing_if = "Option::is_none")] pub operation_id: Option<String>, #[serde(rename = "localMySqlEnabled", default, skip_serializing_if = "Option::is_none")] pub local_my_sql_enabled: Option<bool>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum MigrationOperationStatus { InProgress, Failed, Succeeded, TimedOut, Created, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkFeatures { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<network_features::Properties>, } pub mod network_features { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "virtualNetworkName", default, skip_serializing_if = "Option::is_none")] pub virtual_network_name: Option<String>, #[serde(rename = "virtualNetworkConnection", default, skip_serializing_if = "Option::is_none")] pub virtual_network_connection: Option<VnetInfo>, #[serde(rename = "hybridConnections", default, skip_serializing_if = "Vec::is_empty")] pub hybrid_connections: Vec<RelayServiceConnectionEntity>, #[serde(rename = "hybridConnectionsV2", default, skip_serializing_if = "Vec::is_empty")] pub hybrid_connections_v2: Vec<HybridConnection>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkTrace { #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Nonce { #[serde(rename = "validateNonce", default, skip_serializing_if = "Option::is_none")] pub validate_nonce: Option<bool>, #[serde(rename = "nonceExpirationInterval", default, skip_serializing_if = "Option::is_none")] pub nonce_expiration_interval: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenIdConnectClientCredential { #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<open_id_connect_client_credential::Method>, #[serde(rename = "clientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub client_secret_setting_name: Option<String>, } pub mod open_id_connect_client_credential { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Method { ClientSecretPost, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenIdConnectConfig { #[serde(rename = "authorizationEndpoint", default, skip_serializing_if = "Option::is_none")] pub authorization_endpoint: Option<String>, #[serde(rename = "tokenEndpoint", default, skip_serializing_if = "Option::is_none")] pub token_endpoint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "certificationUri", default, skip_serializing_if = "Option::is_none")] pub certification_uri: Option<String>, #[serde(rename = "wellKnownOpenIdConfiguration", default, skip_serializing_if = "Option::is_none")] pub well_known_open_id_configuration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenIdConnectLogin { #[serde(rename = "nameClaimType", default, skip_serializing_if = "Option::is_none")] pub name_claim_type: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub scopes: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OpenIdConnectRegistration { #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[serde(rename = "clientCredential", default, skip_serializing_if = "Option::is_none")] pub client_credential: Option<OpenIdConnectClientCredential>, #[serde(rename = "openIdConnectConfiguration", default, skip_serializing_if = "Option::is_none")] pub open_id_connect_configuration: Option<OpenIdConnectConfig>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PerfMonCounterCollection { pub value: Vec<PerfMonResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PerfMonResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub data: Option<PerfMonSet>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PerfMonSample { #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option<String>, #[serde(rename = "instanceName", default, skip_serializing_if = "Option::is_none")] pub instance_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<f64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PerfMonSet { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "endTime", default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<PerfMonSample>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PremierAddOn { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<premier_add_on::Properties>, } pub mod premier_add_on { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option<String>, #[serde(rename = "marketplacePublisher", default, skip_serializing_if = "Option::is_none")] pub marketplace_publisher: Option<String>, #[serde(rename = "marketplaceOffer", default, skip_serializing_if = "Option::is_none")] pub marketplace_offer: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PremierAddOnPatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<premier_add_on_patch_resource::Properties>, } pub mod premier_add_on_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub vendor: Option<String>, #[serde(rename = "marketplacePublisher", default, skip_serializing_if = "Option::is_none")] pub marketplace_publisher: Option<String>, #[serde(rename = "marketplaceOffer", default, skip_serializing_if = "Option::is_none")] pub marketplace_offer: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateAccess { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<private_access::Properties>, } pub mod private_access { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "virtualNetworks", default, skip_serializing_if = "Vec::is_empty")] pub virtual_networks: Vec<PrivateAccessVirtualNetwork>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateAccessSubnet { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateAccessVirtualNetwork { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub key: Option<i32>, #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub subnets: Vec<PrivateAccessSubnet>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<process_info::Properties>, } pub mod process_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub identifier: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub deployment_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub minidump: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub is_profile_running: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub is_iis_profile_running: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub iis_profile_timeout_in_seconds: Option<f64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub parent: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub children: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub threads: Vec<ProcessThreadInfo>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub open_file_handles: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub modules: Vec<ProcessModuleInfo>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub command_line: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub user_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub handle_count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub module_count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thread_count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub total_cpu_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub user_cpu_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub privileged_cpu_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub working_set: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub peak_working_set: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub private_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub virtual_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub peak_virtual_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub paged_system_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub non_paged_system_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub paged_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub peak_paged_memory: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub time_stamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub environment_variables: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub is_scm_site: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub is_webjob: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessInfoCollection { pub value: Vec<ProcessInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessModuleInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<process_module_info::Properties>, } pub mod process_module_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub base_address: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub module_memory_size: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product_version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub is_debug: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub language: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessModuleInfoCollection { pub value: Vec<ProcessModuleInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessThreadInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<process_thread_info::Properties>, } pub mod process_thread_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub identifier: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub href: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub process: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub start_address: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub current_priority: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub priority_level: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub base_priority: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub total_processor_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub user_processor_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub wait_reason: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProcessThreadInfoCollection { pub value: Vec<ProcessThreadInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PublicCertificate { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<public_certificate::Properties>, } pub mod public_certificate { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub blob: Option<String>, #[serde(rename = "publicCertificateLocation", default, skip_serializing_if = "Option::is_none")] pub public_certificate_location: Option<properties::PublicCertificateLocation>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicCertificateLocation { CurrentUserMy, LocalMachineMy, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PublicCertificateCollection { pub value: Vec<PublicCertificate>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RelayServiceConnectionEntity { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<relay_service_connection_entity::Properties>, } pub mod relay_service_connection_entity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "entityName", default, skip_serializing_if = "Option::is_none")] pub entity_name: Option<String>, #[serde(rename = "entityConnectionString", default, skip_serializing_if = "Option::is_none")] pub entity_connection_string: Option<String>, #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(rename = "resourceConnectionString", default, skip_serializing_if = "Option::is_none")] pub resource_connection_string: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub hostname: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option<i32>, #[serde(rename = "biztalkUri", default, skip_serializing_if = "Option::is_none")] pub biztalk_uri: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RestoreRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<restore_request::Properties>, } pub mod restore_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "storageAccountUrl")] pub storage_account_url: String, #[serde(rename = "blobName", default, skip_serializing_if = "Option::is_none")] pub blob_name: Option<String>, pub overwrite: bool, #[serde(rename = "siteName", default, skip_serializing_if = "Option::is_none")] pub site_name: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub databases: Vec<DatabaseBackupSetting>, #[serde(rename = "ignoreConflictingHostNames", default, skip_serializing_if = "Option::is_none")] pub ignore_conflicting_host_names: Option<bool>, #[serde(rename = "ignoreDatabases", default, skip_serializing_if = "Option::is_none")] pub ignore_databases: Option<bool>, #[serde(rename = "appServicePlan", default, skip_serializing_if = "Option::is_none")] pub app_service_plan: Option<String>, #[serde(rename = "operationType", default, skip_serializing_if = "Option::is_none")] pub operation_type: Option<properties::OperationType>, #[serde(rename = "adjustConnectionStrings", default, skip_serializing_if = "Option::is_none")] pub adjust_connection_strings: Option<bool>, #[serde(rename = "hostingEnvironment", default, skip_serializing_if = "Option::is_none")] pub hosting_environment: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OperationType { Default, Clone, Relocation, Snapshot, #[serde(rename = "CloudFS")] CloudFs, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteAuthSettings { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_auth_settings::Properties>, } pub mod site_auth_settings { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "runtimeVersion", default, skip_serializing_if = "Option::is_none")] pub runtime_version: Option<String>, #[serde(rename = "unauthenticatedClientAction", default, skip_serializing_if = "Option::is_none")] pub unauthenticated_client_action: Option<properties::UnauthenticatedClientAction>, #[serde(rename = "tokenStoreEnabled", default, skip_serializing_if = "Option::is_none")] pub token_store_enabled: Option<bool>, #[serde(rename = "allowedExternalRedirectUrls", default, skip_serializing_if = "Vec::is_empty")] pub allowed_external_redirect_urls: Vec<String>, #[serde(rename = "defaultProvider", default, skip_serializing_if = "Option::is_none")] pub default_provider: Option<properties::DefaultProvider>, #[serde(rename = "tokenRefreshExtensionHours", default, skip_serializing_if = "Option::is_none")] pub token_refresh_extension_hours: Option<f64>, #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, #[serde(rename = "clientSecret", default, skip_serializing_if = "Option::is_none")] pub client_secret: Option<String>, #[serde(rename = "clientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub client_secret_setting_name: Option<String>, #[serde(rename = "clientSecretCertificateThumbprint", default, skip_serializing_if = "Option::is_none")] pub client_secret_certificate_thumbprint: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub issuer: Option<String>, #[serde(rename = "validateIssuer", default, skip_serializing_if = "Option::is_none")] pub validate_issuer: Option<bool>, #[serde(rename = "allowedAudiences", default, skip_serializing_if = "Vec::is_empty")] pub allowed_audiences: Vec<String>, #[serde(rename = "additionalLoginParams", default, skip_serializing_if = "Vec::is_empty")] pub additional_login_params: Vec<String>, #[serde(rename = "aadClaimsAuthorization", default, skip_serializing_if = "Option::is_none")] pub aad_claims_authorization: Option<String>, #[serde(rename = "googleClientId", default, skip_serializing_if = "Option::is_none")] pub google_client_id: Option<String>, #[serde(rename = "googleClientSecret", default, skip_serializing_if = "Option::is_none")] pub google_client_secret: Option<String>, #[serde(rename = "googleClientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub google_client_secret_setting_name: Option<String>, #[serde(rename = "googleOAuthScopes", default, skip_serializing_if = "Vec::is_empty")] pub google_o_auth_scopes: Vec<String>, #[serde(rename = "facebookAppId", default, skip_serializing_if = "Option::is_none")] pub facebook_app_id: Option<String>, #[serde(rename = "facebookAppSecret", default, skip_serializing_if = "Option::is_none")] pub facebook_app_secret: Option<String>, #[serde(rename = "facebookAppSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub facebook_app_secret_setting_name: Option<String>, #[serde(rename = "facebookOAuthScopes", default, skip_serializing_if = "Vec::is_empty")] pub facebook_o_auth_scopes: Vec<String>, #[serde(rename = "gitHubClientId", default, skip_serializing_if = "Option::is_none")] pub git_hub_client_id: Option<String>, #[serde(rename = "gitHubClientSecret", default, skip_serializing_if = "Option::is_none")] pub git_hub_client_secret: Option<String>, #[serde(rename = "gitHubClientSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub git_hub_client_secret_setting_name: Option<String>, #[serde(rename = "gitHubOAuthScopes", default, skip_serializing_if = "Vec::is_empty")] pub git_hub_o_auth_scopes: Vec<String>, #[serde(rename = "twitterConsumerKey", default, skip_serializing_if = "Option::is_none")] pub twitter_consumer_key: Option<String>, #[serde(rename = "twitterConsumerSecret", default, skip_serializing_if = "Option::is_none")] pub twitter_consumer_secret: Option<String>, #[serde(rename = "twitterConsumerSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub twitter_consumer_secret_setting_name: Option<String>, #[serde(rename = "microsoftAccountClientId", default, skip_serializing_if = "Option::is_none")] pub microsoft_account_client_id: Option<String>, #[serde(rename = "microsoftAccountClientSecret", default, skip_serializing_if = "Option::is_none")] pub microsoft_account_client_secret: Option<String>, #[serde( rename = "microsoftAccountClientSecretSettingName", default, skip_serializing_if = "Option::is_none" )] pub microsoft_account_client_secret_setting_name: Option<String>, #[serde(rename = "microsoftAccountOAuthScopes", default, skip_serializing_if = "Vec::is_empty")] pub microsoft_account_o_auth_scopes: Vec<String>, #[serde(rename = "isAuthFromFile", default, skip_serializing_if = "Option::is_none")] pub is_auth_from_file: Option<String>, #[serde(rename = "authFilePath", default, skip_serializing_if = "Option::is_none")] pub auth_file_path: Option<String>, #[serde(rename = "configVersion", default, skip_serializing_if = "Option::is_none")] pub config_version: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UnauthenticatedClientAction { RedirectToLoginPage, AllowAnonymous, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DefaultProvider { AzureActiveDirectory, Facebook, Google, MicrosoftAccount, Twitter, Github, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteAuthSettingsV2 { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_auth_settings_v2::Properties>, } pub mod site_auth_settings_v2 { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub platform: Option<AuthPlatform>, #[serde(rename = "globalValidation", default, skip_serializing_if = "Option::is_none")] pub global_validation: Option<GlobalValidation>, #[serde(rename = "identityProviders", default, skip_serializing_if = "Option::is_none")] pub identity_providers: Option<IdentityProviders>, #[serde(default, skip_serializing_if = "Option::is_none")] pub login: Option<Login>, #[serde(rename = "httpSettings", default, skip_serializing_if = "Option::is_none")] pub http_settings: Option<HttpSettings>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteCloneability { #[serde(default, skip_serializing_if = "Option::is_none")] pub result: Option<site_cloneability::Result>, #[serde(rename = "blockingFeatures", default, skip_serializing_if = "Vec::is_empty")] pub blocking_features: Vec<SiteCloneabilityCriterion>, #[serde(rename = "unsupportedFeatures", default, skip_serializing_if = "Vec::is_empty")] pub unsupported_features: Vec<SiteCloneabilityCriterion>, #[serde(rename = "blockingCharacteristics", default, skip_serializing_if = "Vec::is_empty")] pub blocking_characteristics: Vec<SiteCloneabilityCriterion>, } pub mod site_cloneability { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Result { Cloneable, PartiallyCloneable, NotCloneable, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteCloneabilityCriterion { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfigResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SiteConfig>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfigResourceCollection { pub value: Vec<SiteConfigResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfigurationSnapshotInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_configuration_snapshot_info::Properties>, } pub mod site_configuration_snapshot_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub time: Option<String>, #[serde(rename = "snapshotId", default, skip_serializing_if = "Option::is_none")] pub snapshot_id: Option<i32>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteConfigurationSnapshotInfoCollection { pub value: Vec<SiteConfigurationSnapshotInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteExtensionInfo { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_extension_info::Properties>, } pub mod site_extension_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub extension_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extension_type: Option<properties::ExtensionType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub summary: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extension_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub project_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub icon_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub license_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub feed_url: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub authors: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub installer_command_line_params: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub published_date_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub download_count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub local_is_latest_version: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub local_path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub installed_date_time: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub comment: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ExtensionType { Gallery, WebRoot, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteExtensionInfoCollection { pub value: Vec<SiteExtensionInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteLogsConfig { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_logs_config::Properties>, } pub mod site_logs_config { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "applicationLogs", default, skip_serializing_if = "Option::is_none")] pub application_logs: Option<ApplicationLogsConfig>, #[serde(rename = "httpLogs", default, skip_serializing_if = "Option::is_none")] pub http_logs: Option<HttpLogsConfig>, #[serde(rename = "failedRequestsTracing", default, skip_serializing_if = "Option::is_none")] pub failed_requests_tracing: Option<EnabledConfig>, #[serde(rename = "detailedErrorMessages", default, skip_serializing_if = "Option::is_none")] pub detailed_error_messages: Option<EnabledConfig>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SitePatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_patch_resource::Properties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, } pub mod site_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(rename = "hostNames", default, skip_serializing_if = "Vec::is_empty")] pub host_names: Vec<String>, #[serde(rename = "repositorySiteName", default, skip_serializing_if = "Option::is_none")] pub repository_site_name: Option<String>, #[serde(rename = "usageState", default, skip_serializing_if = "Option::is_none")] pub usage_state: Option<properties::UsageState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "enabledHostNames", default, skip_serializing_if = "Vec::is_empty")] pub enabled_host_names: Vec<String>, #[serde(rename = "availabilityState", default, skip_serializing_if = "Option::is_none")] pub availability_state: Option<properties::AvailabilityState>, #[serde(rename = "hostNameSslStates", default, skip_serializing_if = "Vec::is_empty")] pub host_name_ssl_states: Vec<HostNameSslState>, #[serde(rename = "serverFarmId", default, skip_serializing_if = "Option::is_none")] pub server_farm_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reserved: Option<bool>, #[serde(rename = "isXenon", default, skip_serializing_if = "Option::is_none")] pub is_xenon: Option<bool>, #[serde(rename = "hyperV", default, skip_serializing_if = "Option::is_none")] pub hyper_v: Option<bool>, #[serde(rename = "lastModifiedTimeUtc", default, skip_serializing_if = "Option::is_none")] pub last_modified_time_utc: Option<String>, #[serde(rename = "siteConfig", default, skip_serializing_if = "Option::is_none")] pub site_config: Option<SiteConfig>, #[serde(rename = "trafficManagerHostNames", default, skip_serializing_if = "Vec::is_empty")] pub traffic_manager_host_names: Vec<String>, #[serde(rename = "scmSiteAlsoStopped", default, skip_serializing_if = "Option::is_none")] pub scm_site_also_stopped: Option<bool>, #[serde(rename = "targetSwapSlot", default, skip_serializing_if = "Option::is_none")] pub target_swap_slot: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "clientAffinityEnabled", default, skip_serializing_if = "Option::is_none")] pub client_affinity_enabled: Option<bool>, #[serde(rename = "clientCertEnabled", default, skip_serializing_if = "Option::is_none")] pub client_cert_enabled: Option<bool>, #[serde(rename = "clientCertMode", default, skip_serializing_if = "Option::is_none")] pub client_cert_mode: Option<properties::ClientCertMode>, #[serde(rename = "clientCertExclusionPaths", default, skip_serializing_if = "Option::is_none")] pub client_cert_exclusion_paths: Option<String>, #[serde(rename = "hostNamesDisabled", default, skip_serializing_if = "Option::is_none")] pub host_names_disabled: Option<bool>, #[serde(rename = "customDomainVerificationId", default, skip_serializing_if = "Option::is_none")] pub custom_domain_verification_id: Option<String>, #[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Option::is_none")] pub outbound_ip_addresses: Option<String>, #[serde(rename = "possibleOutboundIpAddresses", default, skip_serializing_if = "Option::is_none")] pub possible_outbound_ip_addresses: Option<String>, #[serde(rename = "containerSize", default, skip_serializing_if = "Option::is_none")] pub container_size: Option<i32>, #[serde(rename = "dailyMemoryTimeQuota", default, skip_serializing_if = "Option::is_none")] pub daily_memory_time_quota: Option<i32>, #[serde(rename = "suspendedTill", default, skip_serializing_if = "Option::is_none")] pub suspended_till: Option<String>, #[serde(rename = "maxNumberOfWorkers", default, skip_serializing_if = "Option::is_none")] pub max_number_of_workers: Option<i32>, #[serde(rename = "cloningInfo", default, skip_serializing_if = "Option::is_none")] pub cloning_info: Option<CloningInfo>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(rename = "isDefaultContainer", default, skip_serializing_if = "Option::is_none")] pub is_default_container: Option<bool>, #[serde(rename = "defaultHostName", default, skip_serializing_if = "Option::is_none")] pub default_host_name: Option<String>, #[serde(rename = "slotSwapStatus", default, skip_serializing_if = "Option::is_none")] pub slot_swap_status: Option<SlotSwapStatus>, #[serde(rename = "httpsOnly", default, skip_serializing_if = "Option::is_none")] pub https_only: Option<bool>, #[serde(rename = "redundancyMode", default, skip_serializing_if = "Option::is_none")] pub redundancy_mode: Option<properties::RedundancyMode>, #[serde(rename = "inProgressOperationId", default, skip_serializing_if = "Option::is_none")] pub in_progress_operation_id: Option<String>, #[serde(rename = "storageAccountRequired", default, skip_serializing_if = "Option::is_none")] pub storage_account_required: Option<bool>, #[serde(rename = "keyVaultReferenceIdentity", default, skip_serializing_if = "Option::is_none")] pub key_vault_reference_identity: Option<String>, #[serde(rename = "virtualNetworkSubnetId", default, skip_serializing_if = "Option::is_none")] pub virtual_network_subnet_id: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UsageState { Normal, Exceeded, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AvailabilityState { Normal, Limited, DisasterRecoveryMode, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ClientCertMode { Required, Optional, OptionalInteractiveUser, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RedundancyMode { None, Manual, Failover, ActiveActive, GeoRedundant, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SitePhpErrorLogFlag { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_php_error_log_flag::Properties>, } pub mod site_php_error_log_flag { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "localLogErrors", default, skip_serializing_if = "Option::is_none")] pub local_log_errors: Option<String>, #[serde(rename = "masterLogErrors", default, skip_serializing_if = "Option::is_none")] pub master_log_errors: Option<String>, #[serde(rename = "localLogErrorsMaxLength", default, skip_serializing_if = "Option::is_none")] pub local_log_errors_max_length: Option<String>, #[serde(rename = "masterLogErrorsMaxLength", default, skip_serializing_if = "Option::is_none")] pub master_log_errors_max_length: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SiteSourceControl { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<site_source_control::Properties>, } pub mod site_source_control { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "repoUrl", default, skip_serializing_if = "Option::is_none")] pub repo_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option<String>, #[serde(rename = "isManualIntegration", default, skip_serializing_if = "Option::is_none")] pub is_manual_integration: Option<bool>, #[serde(rename = "isGitHubAction", default, skip_serializing_if = "Option::is_none")] pub is_git_hub_action: Option<bool>, #[serde(rename = "deploymentRollbackEnabled", default, skip_serializing_if = "Option::is_none")] pub deployment_rollback_enabled: Option<bool>, #[serde(rename = "isMercurial", default, skip_serializing_if = "Option::is_none")] pub is_mercurial: Option<bool>, #[serde(rename = "gitHubActionConfiguration", default, skip_serializing_if = "Option::is_none")] pub git_hub_action_configuration: Option<GitHubActionConfiguration>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlotConfigNames { #[serde(rename = "connectionStringNames", default, skip_serializing_if = "Vec::is_empty")] pub connection_string_names: Vec<String>, #[serde(rename = "appSettingNames", default, skip_serializing_if = "Vec::is_empty")] pub app_setting_names: Vec<String>, #[serde(rename = "azureStorageConfigNames", default, skip_serializing_if = "Vec::is_empty")] pub azure_storage_config_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlotConfigNamesResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SlotConfigNames>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlotDifference { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<slot_difference::Properties>, } pub mod slot_difference { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub level: Option<String>, #[serde(rename = "settingType", default, skip_serializing_if = "Option::is_none")] pub setting_type: Option<String>, #[serde(rename = "diffRule", default, skip_serializing_if = "Option::is_none")] pub diff_rule: Option<String>, #[serde(rename = "settingName", default, skip_serializing_if = "Option::is_none")] pub setting_name: Option<String>, #[serde(rename = "valueInCurrentSlot", default, skip_serializing_if = "Option::is_none")] pub value_in_current_slot: Option<String>, #[serde(rename = "valueInTargetSlot", default, skip_serializing_if = "Option::is_none")] pub value_in_target_slot: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SlotDifferenceCollection { pub value: Vec<SlotDifference>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SnapshotCollection { pub value: Vec<Snapshot>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SnapshotRecoverySource { #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SnapshotRestoreRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<snapshot_restore_request::Properties>, } pub mod snapshot_restore_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "snapshotTime", default, skip_serializing_if = "Option::is_none")] pub snapshot_time: Option<String>, #[serde(rename = "recoverySource", default, skip_serializing_if = "Option::is_none")] pub recovery_source: Option<SnapshotRecoverySource>, pub overwrite: bool, #[serde(rename = "recoverConfiguration", default, skip_serializing_if = "Option::is_none")] pub recover_configuration: Option<bool>, #[serde(rename = "ignoreConflictingHostNames", default, skip_serializing_if = "Option::is_none")] pub ignore_conflicting_host_names: Option<bool>, #[serde(rename = "useDRSecondary", default, skip_serializing_if = "Option::is_none")] pub use_dr_secondary: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageMigrationOptions { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<storage_migration_options::Properties>, } pub mod storage_migration_options { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "azurefilesConnectionString")] pub azurefiles_connection_string: String, #[serde(rename = "azurefilesShare")] pub azurefiles_share: String, #[serde(rename = "switchSiteAfterMigration", default, skip_serializing_if = "Option::is_none")] pub switch_site_after_migration: Option<bool>, #[serde(rename = "blockWriteAccessToSite", default, skip_serializing_if = "Option::is_none")] pub block_write_access_to_site: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageMigrationResponse { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<storage_migration_response::Properties>, } pub mod storage_migration_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "operationId", default, skip_serializing_if = "Option::is_none")] pub operation_id: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SwiftVirtualNetwork { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<swift_virtual_network::Properties>, } pub mod swift_virtual_network { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "subnetResourceId", default, skip_serializing_if = "Option::is_none")] pub subnet_resource_id: Option<String>, #[serde(rename = "swiftSupported", default, skip_serializing_if = "Option::is_none")] pub swift_supported: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenStore { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(rename = "tokenRefreshExtensionHours", default, skip_serializing_if = "Option::is_none")] pub token_refresh_extension_hours: Option<f64>, #[serde(rename = "fileSystem", default, skip_serializing_if = "Option::is_none")] pub file_system: Option<FileSystemTokenStore>, #[serde(rename = "azureBlobStorage", default, skip_serializing_if = "Option::is_none")] pub azure_blob_storage: Option<BlobStorageTokenStore>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggeredJobHistory { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<triggered_job_history::Properties>, } pub mod triggered_job_history { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub runs: Vec<TriggeredJobRun>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggeredJobHistoryCollection { pub value: Vec<TriggeredJobHistory>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggeredJobRun { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<triggered_job_run::Properties>, } pub mod triggered_job_run { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub web_job_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub web_job_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub end_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub duration: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub output_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub job_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Success, Failed, Error, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggeredWebJob { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<triggered_web_job::Properties>, } pub mod triggered_web_job { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub latest_run: Option<TriggeredJobRun>, #[serde(default, skip_serializing_if = "Option::is_none")] pub history_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scheduler_logs_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub run_command: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extra_info_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub web_job_type: Option<properties::WebJobType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub using_sdk: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub settings: Option<serde_json::Value>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WebJobType { Continuous, Triggered, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggeredWebJobCollection { pub value: Vec<TriggeredWebJob>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Twitter { #[serde(default, skip_serializing_if = "Option::is_none")] pub enabled: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registration: Option<TwitterRegistration>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TwitterRegistration { #[serde(rename = "consumerKey", default, skip_serializing_if = "Option::is_none")] pub consumer_key: Option<String>, #[serde(rename = "consumerSecretSettingName", default, skip_serializing_if = "Option::is_none")] pub consumer_secret_setting_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebAppInstanceStatusCollection { pub value: Vec<WebSiteInstanceStatus>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebJob { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<web_job::Properties>, } pub mod web_job { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub run_command: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub extra_info_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub web_job_type: Option<properties::WebJobType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub using_sdk: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub settings: Option<serde_json::Value>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WebJobType { Continuous, Triggered, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebJobCollection { pub value: Vec<WebJob>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebSiteInstanceStatus { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<web_site_instance_status::Properties>, } pub mod web_site_instance_status { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<properties::State>, #[serde(rename = "statusUrl", default, skip_serializing_if = "Option::is_none")] pub status_url: Option<String>, #[serde(rename = "detectorUrl", default, skip_serializing_if = "Option::is_none")] pub detector_url: Option<String>, #[serde(rename = "consoleUrl", default, skip_serializing_if = "Option::is_none")] pub console_url: Option<String>, #[serde(rename = "healthCheckUrl", default, skip_serializing_if = "Option::is_none")] pub health_check_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub containers: Option<serde_json::Value>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum State { #[serde(rename = "READY")] Ready, #[serde(rename = "STOPPED")] Stopped, #[serde(rename = "UNKNOWN")] Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ArmPlan { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub publisher: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub product: Option<String>, #[serde(rename = "promotionCode", default, skip_serializing_if = "Option::is_none")] pub promotion_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RemotePrivateEndpointConnection { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<remote_private_endpoint_connection::Properties>, } pub mod remote_private_endpoint_connection { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")] pub private_endpoint: Option<ArmIdWrapper>, #[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")] pub private_link_service_connection_state: Option<PrivateLinkConnectionState>, #[serde(rename = "ipAddresses", default, skip_serializing_if = "Vec::is_empty")] pub ip_addresses: Vec<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResponseMessageEnvelopeRemotePrivateEndpointConnection { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub plan: Option<ArmPlan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RemotePrivateEndpointConnection>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuDescription>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorEntity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub zones: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSite { #[serde(rename = "defaultHostname", default, skip_serializing_if = "Option::is_none")] pub default_hostname: Option<String>, #[serde(rename = "repositoryUrl", default, skip_serializing_if = "Option::is_none")] pub repository_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option<String>, #[serde(rename = "customDomains", default, skip_serializing_if = "Vec::is_empty")] pub custom_domains: Vec<String>, #[serde(rename = "repositoryToken", default, skip_serializing_if = "Option::is_none")] pub repository_token: Option<String>, #[serde(rename = "buildProperties", default, skip_serializing_if = "Option::is_none")] pub build_properties: Option<StaticSiteBuildProperties>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<ResponseMessageEnvelopeRemotePrivateEndpointConnection>, #[serde(rename = "stagingEnvironmentPolicy", default, skip_serializing_if = "Option::is_none")] pub staging_environment_policy: Option<static_site::StagingEnvironmentPolicy>, #[serde(rename = "allowConfigFileUpdates", default, skip_serializing_if = "Option::is_none")] pub allow_config_file_updates: Option<bool>, #[serde(rename = "templateProperties", default, skip_serializing_if = "Option::is_none")] pub template_properties: Option<StaticSiteTemplateOptions>, #[serde(rename = "contentDistributionEndpoint", default, skip_serializing_if = "Option::is_none")] pub content_distribution_endpoint: Option<String>, #[serde(rename = "keyVaultReferenceIdentity", default, skip_serializing_if = "Option::is_none")] pub key_vault_reference_identity: Option<String>, #[serde(rename = "userProvidedFunctionApps", default, skip_serializing_if = "Vec::is_empty")] pub user_provided_function_apps: Vec<StaticSiteUserProvidedFunctionApp>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, } pub mod static_site { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum StagingEnvironmentPolicy { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteArmResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<StaticSite>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuDescription>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ManagedServiceIdentity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteBuildArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_build_arm_resource::Properties>, } pub mod static_site_build_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "buildId", default, skip_serializing_if = "Option::is_none")] pub build_id: Option<String>, #[serde(rename = "sourceBranch", default, skip_serializing_if = "Option::is_none")] pub source_branch: Option<String>, #[serde(rename = "pullRequestTitle", default, skip_serializing_if = "Option::is_none")] pub pull_request_title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub hostname: Option<String>, #[serde(rename = "createdTimeUtc", default, skip_serializing_if = "Option::is_none")] pub created_time_utc: Option<String>, #[serde(rename = "lastUpdatedOn", default, skip_serializing_if = "Option::is_none")] pub last_updated_on: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "userProvidedFunctionApps", default, skip_serializing_if = "Vec::is_empty")] pub user_provided_function_apps: Vec<StaticSiteUserProvidedFunctionApp>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { WaitingForDeployment, Uploading, Deploying, Ready, Failed, Deleting, Detached, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteBuildCollection { pub value: Vec<StaticSiteBuildArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteBuildProperties { #[serde(rename = "appLocation", default, skip_serializing_if = "Option::is_none")] pub app_location: Option<String>, #[serde(rename = "apiLocation", default, skip_serializing_if = "Option::is_none")] pub api_location: Option<String>, #[serde(rename = "appArtifactLocation", default, skip_serializing_if = "Option::is_none")] pub app_artifact_location: Option<String>, #[serde(rename = "outputLocation", default, skip_serializing_if = "Option::is_none")] pub output_location: Option<String>, #[serde(rename = "appBuildCommand", default, skip_serializing_if = "Option::is_none")] pub app_build_command: Option<String>, #[serde(rename = "apiBuildCommand", default, skip_serializing_if = "Option::is_none")] pub api_build_command: Option<String>, #[serde(rename = "skipGithubActionWorkflowGeneration", default, skip_serializing_if = "Option::is_none")] pub skip_github_action_workflow_generation: Option<bool>, #[serde(rename = "githubActionSecretNameOverride", default, skip_serializing_if = "Option::is_none")] pub github_action_secret_name_override: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteCollection { pub value: Vec<StaticSiteArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteCustomDomainOverviewArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_custom_domain_overview_arm_resource::Properties>, } pub mod static_site_custom_domain_overview_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "domainName", default, skip_serializing_if = "Option::is_none")] pub domain_name: Option<String>, #[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")] pub created_on: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(rename = "validationToken", default, skip_serializing_if = "Option::is_none")] pub validation_token: Option<String>, #[serde(rename = "errorMessage", default, skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { RetrievingValidationToken, Validating, Adding, Ready, Failed, Deleting, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteCustomDomainOverviewCollection { pub value: Vec<StaticSiteCustomDomainOverviewArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteCustomDomainRequestPropertiesArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_custom_domain_request_properties_arm_resource::Properties>, } pub mod static_site_custom_domain_request_properties_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "validationMethod", default, skip_serializing_if = "Option::is_none")] pub validation_method: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteFunctionOverviewArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_function_overview_arm_resource::Properties>, } pub mod static_site_function_overview_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "functionName", default, skip_serializing_if = "Option::is_none")] pub function_name: Option<String>, #[serde(rename = "triggerType", default, skip_serializing_if = "Option::is_none")] pub trigger_type: Option<properties::TriggerType>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TriggerType { HttpTrigger, Unknown, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteFunctionOverviewCollection { pub value: Vec<StaticSiteFunctionOverviewArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSitePatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<StaticSite>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteResetPropertiesArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_reset_properties_arm_resource::Properties>, } pub mod static_site_reset_properties_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "repositoryToken", default, skip_serializing_if = "Option::is_none")] pub repository_token: Option<String>, #[serde(rename = "shouldUpdateRepository", default, skip_serializing_if = "Option::is_none")] pub should_update_repository: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteTemplateOptions { #[serde(rename = "templateRepositoryUrl", default, skip_serializing_if = "Option::is_none")] pub template_repository_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub owner: Option<String>, #[serde(rename = "repositoryName", default, skip_serializing_if = "Option::is_none")] pub repository_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "isPrivate", default, skip_serializing_if = "Option::is_none")] pub is_private: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_user_arm_resource::Properties>, } pub mod static_site_user_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(rename = "userId", default, skip_serializing_if = "Option::is_none")] pub user_id: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub roles: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserCollection { pub value: Vec<StaticSiteUserArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserInvitationRequestResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_user_invitation_request_resource::Properties>, } pub mod static_site_user_invitation_request_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub domain: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(rename = "userDetails", default, skip_serializing_if = "Option::is_none")] pub user_details: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub roles: Option<String>, #[serde(rename = "numHoursToExpiration", default, skip_serializing_if = "Option::is_none")] pub num_hours_to_expiration: Option<i32>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserInvitationResponseResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_user_invitation_response_resource::Properties>, } pub mod static_site_user_invitation_response_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "expiresOn", default, skip_serializing_if = "Option::is_none")] pub expires_on: Option<String>, #[serde(rename = "invitationUrl", default, skip_serializing_if = "Option::is_none")] pub invitation_url: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserProvidedFunctionApp { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_user_provided_function_app::Properties>, } pub mod static_site_user_provided_function_app { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "functionAppResourceId", default, skip_serializing_if = "Option::is_none")] pub function_app_resource_id: Option<String>, #[serde(rename = "functionAppRegion", default, skip_serializing_if = "Option::is_none")] pub function_app_region: Option<String>, #[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")] pub created_on: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserProvidedFunctionAppArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_site_user_provided_function_app_arm_resource::Properties>, } pub mod static_site_user_provided_function_app_arm_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "functionAppResourceId", default, skip_serializing_if = "Option::is_none")] pub function_app_resource_id: Option<String>, #[serde(rename = "functionAppRegion", default, skip_serializing_if = "Option::is_none")] pub function_app_region: Option<String>, #[serde(rename = "createdOn", default, skip_serializing_if = "Option::is_none")] pub created_on: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteUserProvidedFunctionAppsCollection { pub value: Vec<StaticSiteUserProvidedFunctionAppArmResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteZipDeployment { #[serde(rename = "appZipUrl", default, skip_serializing_if = "Option::is_none")] pub app_zip_url: Option<String>, #[serde(rename = "apiZipUrl", default, skip_serializing_if = "Option::is_none")] pub api_zip_url: Option<String>, #[serde(rename = "deploymentTitle", default, skip_serializing_if = "Option::is_none")] pub deployment_title: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(rename = "functionLanguage", default, skip_serializing_if = "Option::is_none")] pub function_language: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSiteZipDeploymentArmResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<StaticSiteZipDeployment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSitesWorkflowPreview { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_sites_workflow_preview::Properties>, } pub mod static_sites_workflow_preview { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub contents: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StaticSitesWorkflowPreviewRequest { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<static_sites_workflow_preview_request::Properties>, } pub mod static_sites_workflow_preview_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "repositoryUrl", default, skip_serializing_if = "Option::is_none")] pub repository_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option<String>, #[serde(rename = "buildProperties", default, skip_serializing_if = "Option::is_none")] pub build_properties: Option<StaticSiteBuildProperties>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StringList { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub properties: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AddressResponse { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<address_response::Properties>, } pub mod address_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "serviceIpAddress", default, skip_serializing_if = "Option::is_none")] pub service_ip_address: Option<String>, #[serde(rename = "internalIpAddress", default, skip_serializing_if = "Option::is_none")] pub internal_ip_address: Option<String>, #[serde(rename = "outboundIpAddresses", default, skip_serializing_if = "Vec::is_empty")] pub outbound_ip_addresses: Vec<String>, #[serde(rename = "vipMappings", default, skip_serializing_if = "Vec::is_empty")] pub vip_mappings: Vec<VirtualIpMapping>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceEnvironmentCollection { pub value: Vec<AppServiceEnvironmentResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceEnvironmentPatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppServiceEnvironment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServiceEnvironmentResource { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AppServiceEnvironment>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AseV3NetworkingConfiguration { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ase_v3_networking_configuration::Properties>, } pub mod ase_v3_networking_configuration { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "windowsOutboundIpAddresses", default, skip_serializing_if = "Vec::is_empty")] pub windows_outbound_ip_addresses: Vec<String>, #[serde(rename = "linuxOutboundIpAddresses", default, skip_serializing_if = "Vec::is_empty")] pub linux_outbound_ip_addresses: Vec<String>, #[serde(rename = "allowNewPrivateEndpointConnections", default, skip_serializing_if = "Option::is_none")] pub allow_new_private_endpoint_connections: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EndpointDependency { #[serde(rename = "domainName", default, skip_serializing_if = "Option::is_none")] pub domain_name: Option<String>, #[serde(rename = "endpointDetails", default, skip_serializing_if = "Vec::is_empty")] pub endpoint_details: Vec<EndpointDetail>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EndpointDetail { #[serde(rename = "ipAddress", default, skip_serializing_if = "Option::is_none")] pub ip_address: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub port: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub latency: Option<f64>, #[serde(rename = "isAccessible", default, skip_serializing_if = "Option::is_none")] pub is_accessible: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HostingEnvironmentDiagnostics { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "diagnosticsOutput", default, skip_serializing_if = "Option::is_none")] pub diagnostics_output: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InboundEnvironmentEndpoint { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub endpoints: Vec<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub ports: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InboundEnvironmentEndpointCollection { pub value: Vec<InboundEnvironmentEndpoint>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OutboundEnvironmentEndpoint { #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub endpoints: Vec<EndpointDependency>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OutboundEnvironmentEndpointCollection { pub value: Vec<OutboundEnvironmentEndpoint>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceMetricAvailability { #[serde(rename = "timeGrain", default, skip_serializing_if = "Option::is_none")] pub time_grain: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub retention: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceMetricDefinition { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<resource_metric_definition::Properties>, } pub mod resource_metric_definition { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "primaryAggregationType", default, skip_serializing_if = "Option::is_none")] pub primary_aggregation_type: Option<String>, #[serde(rename = "metricAvailabilities", default, skip_serializing_if = "Vec::is_empty")] pub metric_availabilities: Vec<ResourceMetricAvailability>, #[serde(rename = "resourceUri", default, skip_serializing_if = "Option::is_none")] pub resource_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceMetricDefinitionCollection { pub value: Vec<ResourceMetricDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuInfo { #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuDescription>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<SkuCapacity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuInfoCollection { pub value: Vec<SkuInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StampCapacity { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "availableCapacity", default, skip_serializing_if = "Option::is_none")] pub available_capacity: Option<i64>, #[serde(rename = "totalCapacity", default, skip_serializing_if = "Option::is_none")] pub total_capacity: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")] pub compute_mode: Option<stamp_capacity::ComputeMode>, #[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")] pub worker_size: Option<stamp_capacity::WorkerSize>, #[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")] pub worker_size_id: Option<i32>, #[serde(rename = "excludeFromCapacityAllocation", default, skip_serializing_if = "Option::is_none")] pub exclude_from_capacity_allocation: Option<bool>, #[serde(rename = "isApplicableForAllComputeModes", default, skip_serializing_if = "Option::is_none")] pub is_applicable_for_all_compute_modes: Option<bool>, #[serde(rename = "siteMode", default, skip_serializing_if = "Option::is_none")] pub site_mode: Option<String>, #[serde(rename = "isLinux", default, skip_serializing_if = "Option::is_none")] pub is_linux: Option<bool>, } pub mod stamp_capacity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ComputeMode { Shared, Dedicated, Dynamic, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum WorkerSize { Small, Medium, Large, D1, D2, D3, SmallV3, MediumV3, LargeV3, NestedSmall, NestedSmallLinux, Default, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StampCapacityCollection { pub value: Vec<StampCapacity>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Usage { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<usage::Properties>, } pub mod usage { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "resourceName", default, skip_serializing_if = "Option::is_none")] pub resource_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(rename = "nextResetTime", default, skip_serializing_if = "Option::is_none")] pub next_reset_time: Option<String>, #[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")] pub compute_mode: Option<properties::ComputeMode>, #[serde(rename = "siteMode", default, skip_serializing_if = "Option::is_none")] pub site_mode: Option<String>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ComputeMode { Shared, Dedicated, Dynamic, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UsageCollection { pub value: Vec<Usage>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualIpMapping { #[serde(rename = "virtualIP", default, skip_serializing_if = "Option::is_none")] pub virtual_ip: Option<String>, #[serde(rename = "internalHttpPort", default, skip_serializing_if = "Option::is_none")] pub internal_http_port: Option<i32>, #[serde(rename = "internalHttpsPort", default, skip_serializing_if = "Option::is_none")] pub internal_https_port: Option<i32>, #[serde(rename = "inUse", default, skip_serializing_if = "Option::is_none")] pub in_use: Option<bool>, #[serde(rename = "serviceName", default, skip_serializing_if = "Option::is_none")] pub service_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WorkerPool { #[serde(rename = "workerSizeId", default, skip_serializing_if = "Option::is_none")] pub worker_size_id: Option<i32>, #[serde(rename = "computeMode", default, skip_serializing_if = "Option::is_none")] pub compute_mode: Option<worker_pool::ComputeMode>, #[serde(rename = "workerSize", default, skip_serializing_if = "Option::is_none")] pub worker_size: Option<String>, #[serde(rename = "workerCount", default, skip_serializing_if = "Option::is_none")] pub worker_count: Option<i32>, #[serde(rename = "instanceNames", default, skip_serializing_if = "Vec::is_empty")] pub instance_names: Vec<String>, } pub mod worker_pool { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ComputeMode { Shared, Dedicated, Dynamic, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WorkerPoolCollection { pub value: Vec<WorkerPoolResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WorkerPoolResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WorkerPool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuDescription>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppServicePlanPatchResource { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<app_service_plan_patch_resource::Properties>, } pub mod app_service_plan_patch_resource { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "workerTierName", default, skip_serializing_if = "Option::is_none")] pub worker_tier_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub subscription: Option<String>, #[serde(rename = "hostingEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub hosting_environment_profile: Option<HostingEnvironmentProfile>, #[serde(rename = "maximumNumberOfWorkers", default, skip_serializing_if = "Option::is_none")] pub maximum_number_of_workers: Option<i32>, #[serde(rename = "geoRegion", default, skip_serializing_if = "Option::is_none")] pub geo_region: Option<String>, #[serde(rename = "perSiteScaling", default, skip_serializing_if = "Option::is_none")] pub per_site_scaling: Option<bool>, #[serde(rename = "maximumElasticWorkerCount", default, skip_serializing_if = "Option::is_none")] pub maximum_elastic_worker_count: Option<i32>, #[serde(rename = "numberOfSites", default, skip_serializing_if = "Option::is_none")] pub number_of_sites: Option<i32>, #[serde(rename = "isSpot", default, skip_serializing_if = "Option::is_none")] pub is_spot: Option<bool>, #[serde(rename = "spotExpirationTime", default, skip_serializing_if = "Option::is_none")] pub spot_expiration_time: Option<String>, #[serde(rename = "freeOfferExpirationTime", default, skip_serializing_if = "Option::is_none")] pub free_offer_expiration_time: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reserved: Option<bool>, #[serde(rename = "isXenon", default, skip_serializing_if = "Option::is_none")] pub is_xenon: Option<bool>, #[serde(rename = "hyperV", default, skip_serializing_if = "Option::is_none")] pub hyper_v: Option<bool>, #[serde(rename = "targetWorkerCount", default, skip_serializing_if = "Option::is_none")] pub target_worker_count: Option<i32>, #[serde(rename = "targetWorkerSizeId", default, skip_serializing_if = "Option::is_none")] pub target_worker_size_id: Option<i32>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<properties::ProvisioningState>, #[serde(rename = "kubeEnvironmentProfile", default, skip_serializing_if = "Option::is_none")] pub kube_environment_profile: Option<KubeEnvironmentProfile>, } pub mod properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Ready, Pending, Creating, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Succeeded, Failed, Canceled, InProgress, Deleting, } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HybridConnectionCollection { pub value: Vec<HybridConnection>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HybridConnectionKey { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<hybrid_connection_key::Properties>, } pub mod hybrid_connection_key { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(rename = "sendKeyName", default, skip_serializing_if = "Option::is_none")] pub send_key_name: Option<String>, #[serde(rename = "sendKeyValue", default, skip_serializing_if = "Option::is_none")] pub send_key_value: Option<String>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct HybridConnectionLimits { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<hybrid_connection_limits::Properties>, } pub mod hybrid_connection_limits { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub current: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub maximum: Option<i32>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceCollection { pub value: Vec<String>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceHealthMetadata { #[serde(flatten)] pub proxy_only_resource: ProxyOnlyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<resource_health_metadata::Properties>, } pub mod resource_health_metadata { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub category: Option<String>, #[serde(rename = "signalAvailability", default, skip_serializing_if = "Option::is_none")] pub signal_availability: Option<bool>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceHealthMetadataCollection { pub value: Vec<ResourceHealthMetadata>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, }
#[doc = "Register `OAR2` reader"] pub type R = crate::R<OAR2_SPEC>; #[doc = "Register `OAR2` writer"] pub type W = crate::W<OAR2_SPEC>; #[doc = "Field `OA2` reader - Interface address"] pub type OA2_R = crate::FieldReader; #[doc = "Field `OA2` writer - Interface address"] pub type OA2_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 7, O>; #[doc = "Field `OA2MSK` reader - Own Address 2 masks"] pub type OA2MSK_R = crate::FieldReader<OA2MSK_A>; #[doc = "Own Address 2 masks\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum OA2MSK_A { #[doc = "0: No mask"] NoMask = 0, #[doc = "1: OA2\\[1\\] is masked and don’t care. Only OA2\\[7:2\\] are compared"] Mask1 = 1, #[doc = "2: OA2\\[2:1\\] are masked and don’t care. Only OA2\\[7:3\\] are compared"] Mask2 = 2, #[doc = "3: OA2\\[3:1\\] are masked and don’t care. Only OA2\\[7:4\\] are compared"] Mask3 = 3, #[doc = "4: OA2\\[4:1\\] are masked and don’t care. Only OA2\\[7:5\\] are compared"] Mask4 = 4, #[doc = "5: OA2\\[5:1\\] are masked and don’t care. Only OA2\\[7:6\\] are compared"] Mask5 = 5, #[doc = "6: OA2\\[6:1\\] are masked and don’t care. Only OA2\\[7\\] is compared."] Mask6 = 6, #[doc = "7: OA2\\[7:1\\] are masked and don’t care. No comparison is done, and all (except reserved) 7-bit received addresses are acknowledged"] Mask7 = 7, } impl From<OA2MSK_A> for u8 { #[inline(always)] fn from(variant: OA2MSK_A) -> Self { variant as _ } } impl crate::FieldSpec for OA2MSK_A { type Ux = u8; } impl OA2MSK_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OA2MSK_A { match self.bits { 0 => OA2MSK_A::NoMask, 1 => OA2MSK_A::Mask1, 2 => OA2MSK_A::Mask2, 3 => OA2MSK_A::Mask3, 4 => OA2MSK_A::Mask4, 5 => OA2MSK_A::Mask5, 6 => OA2MSK_A::Mask6, 7 => OA2MSK_A::Mask7, _ => unreachable!(), } } #[doc = "No mask"] #[inline(always)] pub fn is_no_mask(&self) -> bool { *self == OA2MSK_A::NoMask } #[doc = "OA2\\[1\\] is masked and don’t care. Only OA2\\[7:2\\] are compared"] #[inline(always)] pub fn is_mask1(&self) -> bool { *self == OA2MSK_A::Mask1 } #[doc = "OA2\\[2:1\\] are masked and don’t care. Only OA2\\[7:3\\] are compared"] #[inline(always)] pub fn is_mask2(&self) -> bool { *self == OA2MSK_A::Mask2 } #[doc = "OA2\\[3:1\\] are masked and don’t care. Only OA2\\[7:4\\] are compared"] #[inline(always)] pub fn is_mask3(&self) -> bool { *self == OA2MSK_A::Mask3 } #[doc = "OA2\\[4:1\\] are masked and don’t care. Only OA2\\[7:5\\] are compared"] #[inline(always)] pub fn is_mask4(&self) -> bool { *self == OA2MSK_A::Mask4 } #[doc = "OA2\\[5:1\\] are masked and don’t care. Only OA2\\[7:6\\] are compared"] #[inline(always)] pub fn is_mask5(&self) -> bool { *self == OA2MSK_A::Mask5 } #[doc = "OA2\\[6:1\\] are masked and don’t care. Only OA2\\[7\\] is compared."] #[inline(always)] pub fn is_mask6(&self) -> bool { *self == OA2MSK_A::Mask6 } #[doc = "OA2\\[7:1\\] are masked and don’t care. No comparison is done, and all (except reserved) 7-bit received addresses are acknowledged"] #[inline(always)] pub fn is_mask7(&self) -> bool { *self == OA2MSK_A::Mask7 } } #[doc = "Field `OA2MSK` writer - Own Address 2 masks"] pub type OA2MSK_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 3, O, OA2MSK_A>; impl<'a, REG, const O: u8> OA2MSK_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "No mask"] #[inline(always)] pub fn no_mask(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::NoMask) } #[doc = "OA2\\[1\\] is masked and don’t care. Only OA2\\[7:2\\] are compared"] #[inline(always)] pub fn mask1(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask1) } #[doc = "OA2\\[2:1\\] are masked and don’t care. Only OA2\\[7:3\\] are compared"] #[inline(always)] pub fn mask2(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask2) } #[doc = "OA2\\[3:1\\] are masked and don’t care. Only OA2\\[7:4\\] are compared"] #[inline(always)] pub fn mask3(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask3) } #[doc = "OA2\\[4:1\\] are masked and don’t care. Only OA2\\[7:5\\] are compared"] #[inline(always)] pub fn mask4(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask4) } #[doc = "OA2\\[5:1\\] are masked and don’t care. Only OA2\\[7:6\\] are compared"] #[inline(always)] pub fn mask5(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask5) } #[doc = "OA2\\[6:1\\] are masked and don’t care. Only OA2\\[7\\] is compared."] #[inline(always)] pub fn mask6(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask6) } #[doc = "OA2\\[7:1\\] are masked and don’t care. No comparison is done, and all (except reserved) 7-bit received addresses are acknowledged"] #[inline(always)] pub fn mask7(self) -> &'a mut crate::W<REG> { self.variant(OA2MSK_A::Mask7) } } #[doc = "Field `OA2EN` reader - Own Address 2 enable"] pub type OA2EN_R = crate::BitReader<OA2EN_A>; #[doc = "Own Address 2 enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum OA2EN_A { #[doc = "0: Own address 2 disabled. The received slave address OA2 is NACKed"] Disabled = 0, #[doc = "1: Own address 2 enabled. The received slave address OA2 is ACKed"] Enabled = 1, } impl From<OA2EN_A> for bool { #[inline(always)] fn from(variant: OA2EN_A) -> Self { variant as u8 != 0 } } impl OA2EN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> OA2EN_A { match self.bits { false => OA2EN_A::Disabled, true => OA2EN_A::Enabled, } } #[doc = "Own address 2 disabled. The received slave address OA2 is NACKed"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == OA2EN_A::Disabled } #[doc = "Own address 2 enabled. The received slave address OA2 is ACKed"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == OA2EN_A::Enabled } } #[doc = "Field `OA2EN` writer - Own Address 2 enable"] pub type OA2EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, OA2EN_A>; impl<'a, REG, const O: u8> OA2EN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Own address 2 disabled. The received slave address OA2 is NACKed"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(OA2EN_A::Disabled) } #[doc = "Own address 2 enabled. The received slave address OA2 is ACKed"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(OA2EN_A::Enabled) } } impl R { #[doc = "Bits 1:7 - Interface address"] #[inline(always)] pub fn oa2(&self) -> OA2_R { OA2_R::new(((self.bits >> 1) & 0x7f) as u8) } #[doc = "Bits 8:10 - Own Address 2 masks"] #[inline(always)] pub fn oa2msk(&self) -> OA2MSK_R { OA2MSK_R::new(((self.bits >> 8) & 7) as u8) } #[doc = "Bit 15 - Own Address 2 enable"] #[inline(always)] pub fn oa2en(&self) -> OA2EN_R { OA2EN_R::new(((self.bits >> 15) & 1) != 0) } } impl W { #[doc = "Bits 1:7 - Interface address"] #[inline(always)] #[must_use] pub fn oa2(&mut self) -> OA2_W<OAR2_SPEC, 1> { OA2_W::new(self) } #[doc = "Bits 8:10 - Own Address 2 masks"] #[inline(always)] #[must_use] pub fn oa2msk(&mut self) -> OA2MSK_W<OAR2_SPEC, 8> { OA2MSK_W::new(self) } #[doc = "Bit 15 - Own Address 2 enable"] #[inline(always)] #[must_use] pub fn oa2en(&mut self) -> OA2EN_W<OAR2_SPEC, 15> { OA2EN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Own address register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`oar2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`oar2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct OAR2_SPEC; impl crate::RegisterSpec for OAR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`oar2::R`](R) reader structure"] impl crate::Readable for OAR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`oar2::W`](W) writer structure"] impl crate::Writable for OAR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets OAR2 to value 0"] impl crate::Resettable for OAR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
fn main() { type I32 = i32; let a_i32:i32 = 5; let b_i32:I32 = 5; if a_i32 == b_i32 { println!("a is equal to b"); } else { println!("no"); } }
pub trait OpenapiSerialization { fn serialize(&self) -> Option<String>; } impl OpenapiSerialization for i32 { fn serialize(&self) -> Option<String> { Some(format!("{:?}", self)) } } impl OpenapiSerialization for i64 { fn serialize(&self) -> Option<String> { Some(format!("{:?}", self)) } } impl OpenapiSerialization for f32 { fn serialize(&self) -> Option<String> { Some(format!("{:?}", self)) } } impl OpenapiSerialization for f64 { fn serialize(&self) -> Option<String> { Some(format!("{:?}", self)) } } impl OpenapiSerialization for String { fn serialize(&self) -> Option<String> { Some(self.clone()) } } impl<T: OpenapiSerialization> OpenapiSerialization for Option<T> { fn serialize(&self) -> Option<String> { self.as_ref().map(|n| match n.serialize() { Some(n) => n, None => "".to_string(), }) } }
mod behaviour; mod compress; mod config; pub mod errors; pub mod network; mod network_group; mod peer; pub mod peer_registry; pub mod peer_store; mod protocols; mod services; #[cfg(test)] mod tests; pub use crate::{ behaviour::Behaviour, config::NetworkConfig, errors::Error, network::{NetworkController, NetworkService, NetworkState}, peer::{Peer, PeerIdentifyInfo}, peer_registry::PeerRegistry, peer_store::{types::MultiaddrExt, Score}, protocols::{CKBProtocol, CKBProtocolContext, CKBProtocolHandler, PeerIndex}, }; pub use p2p::{ multiaddr, secio::{PeerId, PublicKey}, service::{ServiceControl, SessionType, TargetSession}, traits::ServiceProtocol, ProtocolId, }; // Max message frame length for sync protocol: 2MB // NOTE: update this value when block size limit changed pub const MAX_FRAME_LENGTH_SYNC: usize = 2 * 1024 * 1024; // Max message frame length for relay protocol: 4MB // NOTE: update this value when block size limit changed pub const MAX_FRAME_LENGTH_RELAY: usize = 4 * 1024 * 1024; // Max message frame length for time protocol: 1KB pub const MAX_FRAME_LENGTH_TIME: usize = 1024; // Max message frame length for alert protocol: 128KB pub const MAX_FRAME_LENGTH_ALERT: usize = 128 * 1024; // Max message frame length for discovery protocol: 512KB pub const MAX_FRAME_LENGTH_DISCOVERY: usize = 512 * 1024; // Max message frame length for ping protocol: 1KB pub const MAX_FRAME_LENGTH_PING: usize = 1024; // Max message frame length for identify protocol: 2KB pub const MAX_FRAME_LENGTH_IDENTIFY: usize = 2 * 1024; // Max message frame length for disconnectmsg protocol: 1KB pub const MAX_FRAME_LENGTH_DISCONNECTMSG: usize = 1024; // Max message frame length for feeler protocol: 1KB pub const MAX_FRAME_LENGTH_FEELER: usize = 1024; // Max data size in send buffer: 24MB (a little larger than max frame length) pub const DEFAULT_SEND_BUFFER: usize = 24 * 1024 * 1024; pub type ProtocolVersion = String;
use crate::shapes::calculable::AreaCalculable; pub struct Triangle { pub bot_edge: f32, pub height: f32, } impl AreaCalculable for Triangle { fn area(&self) -> f32 { self.bot_edge * self.height * 0.5 } } pub struct Rectangle { pub width: f32, pub height: f32, } impl AreaCalculable for Rectangle { fn area(&self) -> f32 { self.width * self.height } } pub struct Round { pub radius: f32, } impl AreaCalculable for Round { fn area(&self) -> f32 { self.radius * self.radius * 3.1415926 } }
#[doc = "Reader of register MCWDT_INTR_SET"] pub type R = crate::R<u32, super::MCWDT_INTR_SET>; #[doc = "Writer for register MCWDT_INTR_SET"] pub type W = crate::W<u32, super::MCWDT_INTR_SET>; #[doc = "Register MCWDT_INTR_SET `reset()`'s with value 0"] impl crate::ResetValue for super::MCWDT_INTR_SET { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `MCWDT_INT0`"] pub type MCWDT_INT0_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MCWDT_INT0`"] pub struct MCWDT_INT0_W<'a> { w: &'a mut W, } impl<'a> MCWDT_INT0_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `MCWDT_INT1`"] pub type MCWDT_INT1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MCWDT_INT1`"] pub struct MCWDT_INT1_W<'a> { w: &'a mut W, } impl<'a> MCWDT_INT1_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 = "Reader of field `MCWDT_INT2`"] pub type MCWDT_INT2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MCWDT_INT2`"] pub struct MCWDT_INT2_W<'a> { w: &'a mut W, } impl<'a> MCWDT_INT2_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 } } impl R { #[doc = "Bit 0 - Set interrupt for MCWDT_INT0"] #[inline(always)] pub fn mcwdt_int0(&self) -> MCWDT_INT0_R { MCWDT_INT0_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Set interrupt for MCWDT_INT1"] #[inline(always)] pub fn mcwdt_int1(&self) -> MCWDT_INT1_R { MCWDT_INT1_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Set interrupt for MCWDT_INT2"] #[inline(always)] pub fn mcwdt_int2(&self) -> MCWDT_INT2_R { MCWDT_INT2_R::new(((self.bits >> 2) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Set interrupt for MCWDT_INT0"] #[inline(always)] pub fn mcwdt_int0(&mut self) -> MCWDT_INT0_W { MCWDT_INT0_W { w: self } } #[doc = "Bit 1 - Set interrupt for MCWDT_INT1"] #[inline(always)] pub fn mcwdt_int1(&mut self) -> MCWDT_INT1_W { MCWDT_INT1_W { w: self } } #[doc = "Bit 2 - Set interrupt for MCWDT_INT2"] #[inline(always)] pub fn mcwdt_int2(&mut self) -> MCWDT_INT2_W { MCWDT_INT2_W { w: self } } }
use crate::{error::ProcessingError, fuzzers, metadata, search::read_runs}; use indicatif::ParallelProgressIterator; use rayon::prelude::*; use std::{fs, path::Path, time::Instant}; /// Process raw artifacts. pub fn process( in_directory: &Path, out_directory: &Path, fuzzers: &[fuzzers::Fuzzer], targets: &[String], indices: &[String], ) -> Result<(), ProcessingError> { let start = Instant::now(); let paths = read_runs(in_directory, fuzzers, targets, indices)?; let results: Vec<_> = paths .par_iter() .progress_count(paths.len() as u64) .map(|entry| process_entry(entry, out_directory)) .collect(); for result in &results { if let Err(err) = result { eprintln!("Error: {}", err); } } println!( "FUZZERS: Processed {} runs in {:.3} seconds", results.len(), Instant::now().duration_since(start).as_secs_f32() ); Ok(()) } /// Handle individual test runs fn process_entry(entry: &fs::DirEntry, out_directory: &Path) -> Result<(), ProcessingError> { let out_directory = out_directory.join(entry.path().file_name().expect("Missing directory name")); fs::create_dir_all(&out_directory).expect("Failed to create output directory"); let metadata_path = entry.path().join("metadata.json"); let metadata = metadata::read_metadata(&metadata_path)?; let data_path = entry.path().join("fuzzer"); fuzzers::process(metadata.fuzzer, &data_path, &out_directory)?; fs::copy(metadata_path, out_directory.join("metadata.json"))?; Ok(()) }
use lazy_static::lazy_static; use spin::Mutex; use uart_16550::SerialPort; lazy_static! { pub static ref SERIAL1: Mutex<SerialPort> = { let mut serial_port = unsafe { SerialPort::new(0x3F8) }; serial_port.init(); Mutex::new(serial_port) }; } #[doc(hidden)] pub fn _print(args: ::core::fmt::Arguments) { use core::fmt::Write; SERIAL1 .lock() .write_fmt(args) .expect("Printing to serial failed"); } /// Prints to the host through the serial interface. #[macro_export] macro_rules! print { ($($arg:tt)*) => { $crate::serial::_print(format_args!($($arg)*)); }; } /// Prints to the host through the serial interface, appending a newline. #[macro_export] macro_rules! println { () => ($crate::print!("\nUser Info\n")); ($fmt:expr) => ($crate::print!(concat!("User Info: ", $fmt, "\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::print!( concat!("User Info: ", $fmt, "\n"), $($arg)*)); } #[macro_export] macro_rules! warningln { () => ($crate::print!("\x1B[33mUser Warning \x1B[0m\n")); ($fmt:expr) => ($crate::print!(concat!("\x1B[33mUser Warning: ", $fmt, "\x1B[0m\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::print!( concat!("\x1B[33mUser Warning: ", $fmt, "\x1B[0m\n"), $($arg)*)); } #[macro_export] macro_rules! errorln { () => ($crate::print!("\x1B[91mUser ERROR \x1B[0m\n")); ($fmt:expr) => ($crate::print!(concat!("\x1B[91mUser ERROR: ", $fmt, "\x1B[0m\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::print!( concat!("\x1B[91mUser ERROR: ", $fmt, "\x1B[0m\n"), $($arg)*)); } #[macro_export] macro_rules! debug { () => ($crate::print!("\x1B[92mUser Debug \x1B[0m\n")); ($fmt:expr) => ($crate::print!(concat!("\x1B[92mUser Debug: ", $fmt, "\x1B[0m\n"))); ($fmt:expr, $($arg:tt)*) => ($crate::print!( concat!("\x1B[92mUser Debug: ", $fmt, "\x1B[0m\n"), $($arg)*)); } #[macro_export] macro_rules! initdebugln { () => { $crate::print!("\n ===== User FerrOS debug interface =====\n") }; }
use tower::{filter::AsyncFilterLayer, util::Either}; #[cfg(any(feature = "native-tls", feature = "rustls-tls", feature = "openssl-tls"))] use super::tls; use super::{ auth::Auth, middleware::{AddAuthorizationLayer, AuthLayer, BaseUriLayer}, }; use crate::{Config, Error, Result}; /// Extensions to [`Config`](crate::Config) for custom [`Client`](crate::Client). /// /// See [`Client::new`](crate::Client::new) for an example. /// /// This trait is sealed and cannot be implemented. pub trait ConfigExt: private::Sealed { /// Layer to set the base URI of requests to the configured server. fn base_uri_layer(&self) -> BaseUriLayer; /// Optional layer to set up `Authorization` header depending on the config. fn auth_layer(&self) -> Result<Option<AuthLayer>>; /// Create [`hyper_tls::HttpsConnector`] based on config. /// /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use kube::{client::ConfigExt, Config}; /// let config = Config::infer().await?; /// let https = config.native_tls_https_connector()?; /// let hyper_client: hyper::Client<_, hyper::Body> = hyper::Client::builder().build(https); /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "native-tls")))] #[cfg(feature = "native-tls")] fn native_tls_https_connector(&self) -> Result<hyper_tls::HttpsConnector<hyper::client::HttpConnector>>; /// Create [`hyper_rustls::HttpsConnector`] based on config. /// /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use kube::{client::ConfigExt, Config}; /// let config = Config::infer().await?; /// let https = config.rustls_https_connector()?; /// let hyper_client: hyper::Client<_, hyper::Body> = hyper::Client::builder().build(https); /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls")))] #[cfg(feature = "rustls-tls")] fn rustls_https_connector(&self) -> Result<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>>; /// Create [`native_tls::TlsConnector`](tokio_native_tls::native_tls::TlsConnector) based on config. /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use hyper::client::HttpConnector; /// # use kube::{client::ConfigExt, Client, Config}; /// let config = Config::infer().await?; /// let https = { /// let tls = tokio_native_tls::TlsConnector::from( /// config.native_tls_connector()? /// ); /// let mut http = HttpConnector::new(); /// http.enforce_http(false); /// hyper_tls::HttpsConnector::from((http, tls)) /// }; /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "native-tls")))] #[cfg(feature = "native-tls")] fn native_tls_connector(&self) -> Result<tokio_native_tls::native_tls::TlsConnector>; /// Create [`rustls::ClientConfig`] based on config. /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use hyper::client::HttpConnector; /// # use kube::{client::ConfigExt, Config}; /// let config = Config::infer().await?; /// let https = { /// let rustls_config = std::sync::Arc::new(config.rustls_client_config()?); /// let mut http = HttpConnector::new(); /// http.enforce_http(false); /// hyper_rustls::HttpsConnector::from((http, rustls_config)) /// }; /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "rustls-tls")))] #[cfg(feature = "rustls-tls")] fn rustls_client_config(&self) -> Result<rustls::ClientConfig>; /// Create [`hyper_openssl::HttpsConnector`] based on config. /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use kube::{client::ConfigExt, Config}; /// let config = Config::infer().await?; /// let https = config.openssl_https_connector()?; /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "openssl-tls")))] #[cfg(feature = "openssl-tls")] fn openssl_https_connector(&self) -> Result<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>; /// Create [`hyper_openssl::HttpsConnector`] based on config and `connector`. /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use hyper::client::HttpConnector; /// # use kube::{client::ConfigExt, Config}; /// let mut http = HttpConnector::new(); /// http.enforce_http(false); /// let config = Config::infer().await?; /// let https = config.openssl_https_connector_with_connector(http)?; /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "openssl-tls")))] #[cfg(feature = "openssl-tls")] fn openssl_https_connector_with_connector( &self, connector: hyper::client::HttpConnector, ) -> Result<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>>; /// Create [`openssl::ssl::SslConnectorBuilder`] based on config. /// # Example /// /// ```rust /// # async fn doc() -> Result<(), Box<dyn std::error::Error>> { /// # use hyper::client::HttpConnector; /// # use kube::{client::ConfigExt, Client, Config}; /// let config = Config::infer().await?; /// let https = { /// let mut http = HttpConnector::new(); /// http.enforce_http(false); /// let ssl = config.openssl_ssl_connector_builder()?; /// hyper_openssl::HttpsConnector::with_connector(http, ssl)? /// }; /// # Ok(()) /// # } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "openssl-tls")))] #[cfg(feature = "openssl-tls")] fn openssl_ssl_connector_builder(&self) -> Result<openssl::ssl::SslConnectorBuilder>; } mod private { pub trait Sealed {} impl Sealed for super::Config {} } impl ConfigExt for Config { fn base_uri_layer(&self) -> BaseUriLayer { BaseUriLayer::new(self.cluster_url.clone()) } fn auth_layer(&self) -> Result<Option<AuthLayer>> { Ok(match Auth::try_from(&self.auth_info).map_err(Error::Auth)? { Auth::None => None, Auth::Basic(user, pass) => Some(AuthLayer(Either::A( AddAuthorizationLayer::basic(&user, &pass).as_sensitive(true), ))), Auth::Bearer(token) => Some(AuthLayer(Either::A( AddAuthorizationLayer::bearer(&token).as_sensitive(true), ))), Auth::RefreshableToken(refreshable) => { Some(AuthLayer(Either::B(AsyncFilterLayer::new(refreshable)))) } }) } #[cfg(feature = "native-tls")] fn native_tls_connector(&self) -> Result<tokio_native_tls::native_tls::TlsConnector> { tls::native_tls::native_tls_connector( self.identity_pem.as_ref(), self.root_cert.as_ref(), self.accept_invalid_certs, ) .map_err(Error::NativeTls) } #[cfg(feature = "native-tls")] fn native_tls_https_connector(&self) -> Result<hyper_tls::HttpsConnector<hyper::client::HttpConnector>> { let tls = tokio_native_tls::TlsConnector::from(self.native_tls_connector()?); let mut http = hyper::client::HttpConnector::new(); http.enforce_http(false); Ok(hyper_tls::HttpsConnector::from((http, tls))) } #[cfg(feature = "rustls-tls")] fn rustls_client_config(&self) -> Result<rustls::ClientConfig> { tls::rustls_tls::rustls_client_config( self.identity_pem.as_deref(), self.root_cert.as_deref(), self.accept_invalid_certs, ) .map_err(Error::RustlsTls) } #[cfg(feature = "rustls-tls")] fn rustls_https_connector(&self) -> Result<hyper_rustls::HttpsConnector<hyper::client::HttpConnector>> { let rustls_config = std::sync::Arc::new(self.rustls_client_config()?); let mut http = hyper::client::HttpConnector::new(); http.enforce_http(false); Ok(hyper_rustls::HttpsConnector::from((http, rustls_config))) } #[cfg(feature = "openssl-tls")] fn openssl_ssl_connector_builder(&self) -> Result<openssl::ssl::SslConnectorBuilder> { tls::openssl_tls::ssl_connector_builder(self.identity_pem.as_ref(), self.root_cert.as_ref()) .map_err(|e| Error::OpensslTls(tls::openssl_tls::Error::CreateSslConnector(e))) } #[cfg(feature = "openssl-tls")] fn openssl_https_connector(&self) -> Result<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>> { let mut connector = hyper::client::HttpConnector::new(); connector.enforce_http(false); self.openssl_https_connector_with_connector(connector) } #[cfg(feature = "openssl-tls")] fn openssl_https_connector_with_connector( &self, connector: hyper::client::HttpConnector, ) -> Result<hyper_openssl::HttpsConnector<hyper::client::HttpConnector>> { let mut https = hyper_openssl::HttpsConnector::with_connector(connector, self.openssl_ssl_connector_builder()?) .map_err(|e| Error::OpensslTls(tls::openssl_tls::Error::CreateHttpsConnector(e)))?; if self.accept_invalid_certs { https.set_callback(|ssl, _uri| { ssl.set_verify(openssl::ssl::SslVerifyMode::NONE); Ok(()) }); } Ok(https) } }
use super::prelude::*; #[derive(Debug, Clone, PartialEq)] pub enum Stmt { ExprStmt(ExprStmt), Let(Let), Return(Return), Block(Block), } impl Display for Stmt { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match self { Self::ExprStmt(s) => write!(f, "{}", s), Self::Let(s) => write!(f, "{}", s), Self::Block(s) => write!(f, "{}", s), Self::Return(s) => write!(f, "{}", s), } } } impl From<ExprStmt> for Stmt { fn from(stmt: ExprStmt) -> Self { Stmt::ExprStmt(stmt) } } impl From<Let> for Stmt { fn from(stmt: Let) -> Self { Stmt::Let(stmt) } } impl From<Return> for Stmt { fn from(stmt: Return) -> Self { Stmt::Return(stmt) } } impl From<Block> for Stmt { fn from(stmt: Block) -> Self { Stmt::Block(stmt) } } impl TryFrom<Node> for Stmt { type Error = Error; fn try_from(value: Node) -> Result<Self> { match value { Node::Stmt(stmt) => Ok(stmt), Node::Program(program) => { Err(ParserError::Convert(format!("{:?}", program), "Stmt".into()).into()) } Node::Expr(expr) => Ok(Stmt::ExprStmt(ExprStmt { expr })), } } }
// 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<<7cfaf3a38d82c49f41cd1840dcff5620>> // // To regenerate this file, run: // hphp/hack/src/oxidized_by_ref/regen.sh use arena_trait::TrivialDrop; use no_pos_hash::NoPosHash; use ocamlrep_derive::FromOcamlRepIn; use ocamlrep_derive::ToOcamlRep; use serde::Serialize; #[allow(unused_imports)] use crate::*; pub use aast_defs::*; pub use doc_comment::DocComment; /// Aast.program represents the top-level definitions in a Hack program. /// ex: Expression annotation type (when typechecking, the inferred dtype) /// fb: Function body tag (e.g. has naming occurred) /// en: Environment (tracking state inside functions and classes) /// hi: Hint annotation (when typechecking it will be the localized type hint or the /// inferred missing type if the hint is missing) pub type Program<'a, Ex, Fb, En, Hi> = [Def<'a, Ex, Fb, En, Hi>]; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Stmt<'a, Ex, Fb, En, Hi>(pub &'a Pos<'a>, pub Stmt_<'a, Ex, Fb, En, Hi>); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Stmt<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Stmt_<'a, Ex, Fb, En, Hi> { Fallthrough, Expr(&'a Expr<'a, Ex, Fb, En, Hi>), Break, Continue, Throw(&'a Expr<'a, Ex, Fb, En, Hi>), Return(Option<&'a Expr<'a, Ex, Fb, En, Hi>>), GotoLabel(&'a Pstring<'a>), Goto(&'a Pstring<'a>), Awaitall( &'a ( &'a [(Option<&'a Lid<'a>>, &'a Expr<'a, Ex, Fb, En, Hi>)], &'a Block<'a, Ex, Fb, En, Hi>, ), ), If( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>, ), ), Do(&'a (&'a Block<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>)), While(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>)), Using(&'a UsingStmt<'a, Ex, Fb, En, Hi>), For( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>, ), ), Switch(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a [Case<'a, Ex, Fb, En, Hi>])), Foreach( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, AsExpr<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>, ), ), Try( &'a ( &'a Block<'a, Ex, Fb, En, Hi>, &'a [&'a Catch<'a, Ex, Fb, En, Hi>], &'a Block<'a, Ex, Fb, En, Hi>, ), ), Noop, Block(&'a Block<'a, Ex, Fb, En, Hi>), Markup(&'a Pstring<'a>), AssertEnv(&'a (oxidized::aast::EnvAnnot, &'a LocalIdMap<'a, Ex>)), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Stmt_<'a, Ex, Fb, En, Hi> { } pub use oxidized::aast::EnvAnnot; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UsingStmt<'a, Ex, Fb, En, Hi> { pub is_block_scoped: bool, pub has_await: bool, pub expr: &'a Expr<'a, Ex, Fb, En, Hi>, pub block: &'a Block<'a, Ex, Fb, En, Hi>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for UsingStmt<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum AsExpr<'a, Ex, Fb, En, Hi> { AsV(&'a Expr<'a, Ex, Fb, En, Hi>), AsKv(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>)), AwaitAsV(&'a (&'a Pos<'a>, &'a Expr<'a, Ex, Fb, En, Hi>)), AwaitAsKv( &'a ( &'a Pos<'a>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, ), ), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for AsExpr<'a, Ex, Fb, En, Hi> { } pub type Block<'a, Ex, Fb, En, Hi> = [&'a Stmt<'a, Ex, Fb, En, Hi>]; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassId<'a, Ex, Fb, En, Hi>(pub Ex, pub ClassId_<'a, Ex, Fb, En, Hi>); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassId<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassId_<'a, Ex, Fb, En, Hi> { CIparent, CIself, CIstatic, CIexpr(&'a Expr<'a, Ex, Fb, En, Hi>), CI(&'a Sid<'a>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassId_<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Expr<'a, Ex, Fb, En, Hi>(pub Ex, pub Expr_<'a, Ex, Fb, En, Hi>); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Expr<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum CollectionTarg<'a, Hi> { CollectionTV(&'a Targ<'a, Hi>), CollectionTKV(&'a (&'a Targ<'a, Hi>, &'a Targ<'a, Hi>)), } impl<'a, Hi: TrivialDrop> TrivialDrop for CollectionTarg<'a, Hi> {} #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum FunctionPtrId<'a, Ex, Fb, En, Hi> { FPId(&'a Sid<'a>), FPClassConst(&'a (&'a ClassId<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>)), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for FunctionPtrId<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Expr_<'a, Ex, Fb, En, Hi> { Darray( &'a ( Option<&'a (&'a Targ<'a, Hi>, &'a Targ<'a, Hi>)>, &'a [(&'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>)], ), ), Varray(&'a (Option<&'a Targ<'a, Hi>>, &'a [&'a Expr<'a, Ex, Fb, En, Hi>])), Shape(&'a [(ast_defs::ShapeFieldName<'a>, &'a Expr<'a, Ex, Fb, En, Hi>)]), /// TODO: T38184446 Consolidate collections in AAST ValCollection( &'a ( oxidized::aast::VcKind, Option<&'a Targ<'a, Hi>>, &'a [&'a Expr<'a, Ex, Fb, En, Hi>], ), ), /// TODO: T38184446 Consolidate collections in AAST KeyValCollection( &'a ( oxidized::aast::KvcKind, Option<&'a (&'a Targ<'a, Hi>, &'a Targ<'a, Hi>)>, &'a [&'a Field<'a, Ex, Fb, En, Hi>], ), ), Null, This, True, False, Omitted, Id(&'a Sid<'a>), Lvar(&'a Lid<'a>), Dollardollar(&'a Lid<'a>), Clone(&'a Expr<'a, Ex, Fb, En, Hi>), ObjGet( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, oxidized::aast::OgNullFlavor, ), ), ArrayGet( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, Option<&'a Expr<'a, Ex, Fb, En, Hi>>, ), ), ClassGet( &'a ( &'a ClassId<'a, Ex, Fb, En, Hi>, ClassGetExpr<'a, Ex, Fb, En, Hi>, ), ), ClassConst(&'a (&'a ClassId<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>)), Call( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, &'a [&'a Targ<'a, Hi>], &'a [&'a Expr<'a, Ex, Fb, En, Hi>], Option<&'a Expr<'a, Ex, Fb, En, Hi>>, ), ), FunctionPointer(&'a (FunctionPtrId<'a, Ex, Fb, En, Hi>, &'a [&'a Targ<'a, Hi>])), Int(&'a str), Float(&'a str), String(&'a bstr::BStr), String2(&'a [&'a Expr<'a, Ex, Fb, En, Hi>]), PrefixedString(&'a (&'a str, &'a Expr<'a, Ex, Fb, En, Hi>)), Yield(&'a Afield<'a, Ex, Fb, En, Hi>), YieldBreak, Await(&'a Expr<'a, Ex, Fb, En, Hi>), Suspend(&'a Expr<'a, Ex, Fb, En, Hi>), List(&'a [&'a Expr<'a, Ex, Fb, En, Hi>]), ExprList(&'a [&'a Expr<'a, Ex, Fb, En, Hi>]), Cast(&'a (&'a Hint<'a>, &'a Expr<'a, Ex, Fb, En, Hi>)), Unop(&'a (oxidized::ast_defs::Uop, &'a Expr<'a, Ex, Fb, En, Hi>)), Binop( &'a ( ast_defs::Bop<'a>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, ), ), /// The lid is the ID of the $$ that is implicitly declared by this pipe. Pipe( &'a ( &'a Lid<'a>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, ), ), Eif( &'a ( &'a Expr<'a, Ex, Fb, En, Hi>, Option<&'a Expr<'a, Ex, Fb, En, Hi>>, &'a Expr<'a, Ex, Fb, En, Hi>, ), ), Is(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Hint<'a>)), As(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Hint<'a>, bool)), New( &'a ( &'a ClassId<'a, Ex, Fb, En, Hi>, &'a [&'a Targ<'a, Hi>], &'a [&'a Expr<'a, Ex, Fb, En, Hi>], Option<&'a Expr<'a, Ex, Fb, En, Hi>>, Ex, ), ), Record( &'a ( Sid<'a>, &'a [(&'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>)], ), ), Efun(&'a (&'a Fun_<'a, Ex, Fb, En, Hi>, &'a [&'a Lid<'a>])), Lfun(&'a (&'a Fun_<'a, Ex, Fb, En, Hi>, &'a [&'a Lid<'a>])), Xml( &'a ( Sid<'a>, &'a [XhpAttribute<'a, Ex, Fb, En, Hi>], &'a [&'a Expr<'a, Ex, Fb, En, Hi>], ), ), Callconv(&'a (oxidized::ast_defs::ParamKind, &'a Expr<'a, Ex, Fb, En, Hi>)), Import(&'a (oxidized::aast::ImportFlavor, &'a Expr<'a, Ex, Fb, En, Hi>)), /// TODO: T38184446 Consolidate collections in AAST Collection( &'a ( Sid<'a>, Option<CollectionTarg<'a, Hi>>, &'a [Afield<'a, Ex, Fb, En, Hi>], ), ), BracedExpr(&'a Expr<'a, Ex, Fb, En, Hi>), ParenthesizedExpr(&'a Expr<'a, Ex, Fb, En, Hi>), ExpressionTree( &'a ( &'a Hint<'a>, &'a Expr<'a, Ex, Fb, En, Hi>, Option<&'a Expr<'a, Ex, Fb, En, Hi>>, ), ), Lplaceholder(&'a Pos<'a>), FunId(&'a Sid<'a>), MethodId(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>)), /// meth_caller('Class name', 'method name') MethodCaller(&'a (Sid<'a>, &'a Pstring<'a>)), SmethodId(&'a (&'a ClassId<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>)), Pair( &'a ( Option<&'a (&'a Targ<'a, Hi>, &'a Targ<'a, Hi>)>, &'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>, ), ), Assert(&'a AssertExpr<'a, Ex, Fb, En, Hi>), PUAtom(&'a str), PUIdentifier( &'a ( &'a ClassId<'a, Ex, Fb, En, Hi>, &'a Pstring<'a>, &'a Pstring<'a>, ), ), ETSplice(&'a Expr<'a, Ex, Fb, En, Hi>), Any, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Expr_<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassGetExpr<'a, Ex, Fb, En, Hi> { CGstring(&'a Pstring<'a>), CGexpr(&'a Expr<'a, Ex, Fb, En, Hi>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassGetExpr<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum AssertExpr<'a, Ex, Fb, En, Hi> { AEAssert(&'a Expr<'a, Ex, Fb, En, Hi>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for AssertExpr<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Case<'a, Ex, Fb, En, Hi> { Default(&'a (&'a Pos<'a>, &'a Block<'a, Ex, Fb, En, Hi>)), Case(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Block<'a, Ex, Fb, En, Hi>)), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Case<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Catch<'a, Ex, Fb, En, Hi>( pub Sid<'a>, pub &'a Lid<'a>, pub &'a Block<'a, Ex, Fb, En, Hi>, ); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Catch<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Field<'a, Ex, Fb, En, Hi>( pub &'a Expr<'a, Ex, Fb, En, Hi>, pub &'a Expr<'a, Ex, Fb, En, Hi>, ); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Field<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Afield<'a, Ex, Fb, En, Hi> { AFvalue(&'a Expr<'a, Ex, Fb, En, Hi>), AFkvalue(&'a (&'a Expr<'a, Ex, Fb, En, Hi>, &'a Expr<'a, Ex, Fb, En, Hi>)), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Afield<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum XhpAttribute<'a, Ex, Fb, En, Hi> { XhpSimple(&'a (&'a Pstring<'a>, &'a Expr<'a, Ex, Fb, En, Hi>)), XhpSpread(&'a Expr<'a, Ex, Fb, En, Hi>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for XhpAttribute<'a, Ex, Fb, En, Hi> { } pub use oxidized::aast::IsVariadic; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FunParam<'a, Ex, Fb, En, Hi> { pub annotation: Ex, pub type_hint: &'a TypeHint<'a, Hi>, pub is_variadic: &'a oxidized::aast::IsVariadic, pub pos: &'a Pos<'a>, pub name: &'a str, pub expr: Option<&'a Expr<'a, Ex, Fb, En, Hi>>, pub callconv: Option<oxidized::ast_defs::ParamKind>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub visibility: Option<oxidized::aast::Visibility>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for FunParam<'a, Ex, Fb, En, Hi> { } /// does function take varying number of args? #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum FunVariadicity<'a, Ex, Fb, En, Hi> { /// PHP5.6 ...$args finishes the func declaration FVvariadicArg(&'a FunParam<'a, Ex, Fb, En, Hi>), /// HH ... finishes the declaration; deprecate for ...$args? FVellipsis(&'a Pos<'a>), /// standard non variadic function FVnonVariadic, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for FunVariadicity<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Fun_<'a, Ex, Fb, En, Hi> { pub span: &'a Pos<'a>, pub annotation: En, pub mode: oxidized::file_info::Mode, pub ret: &'a TypeHint<'a, Hi>, pub name: Sid<'a>, pub tparams: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub where_constraints: &'a [&'a WhereConstraintHint<'a>], pub variadic: FunVariadicity<'a, Ex, Fb, En, Hi>, pub params: &'a [&'a FunParam<'a, Ex, Fb, En, Hi>], pub cap: &'a TypeHint<'a, Hi>, pub unsafe_cap: &'a TypeHint<'a, Hi>, pub body: &'a FuncBody<'a, Ex, Fb, En, Hi>, pub fun_kind: oxidized::ast_defs::FunKind, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub file_attributes: &'a [&'a FileAttribute<'a, Ex, Fb, En, Hi>], /// true if this declaration has no body because it is an /// external function declaration (e.g. from an HHI file) pub external: bool, pub namespace: &'a Nsenv<'a>, pub doc_comment: Option<&'a DocComment<'a>>, pub static_: bool, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Fun_<'a, Ex, Fb, En, Hi> { } /// Naming has two phases and the annotation helps to indicate the phase. /// In the first pass, it will perform naming on everything except for function /// and method bodies and collect information needed. Then, another round of /// naming is performed where function bodies are named. Thus, naming will /// have named and unnamed variants of the annotation. /// See BodyNamingAnnotation in nast.ml and the comment in naming.ml #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FuncBody<'a, Ex, Fb, En, Hi> { pub ast: &'a Block<'a, Ex, Fb, En, Hi>, pub annotation: Fb, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for FuncBody<'a, Ex, Fb, En, Hi> { } /// A type annotation is two things: /// - the localized hint, or if the hint is missing, the inferred type /// - The typehint associated to this expression if it exists #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct TypeHint<'a, Hi>(pub Hi, pub &'a TypeHint_<'a>); impl<'a, Hi: TrivialDrop> TrivialDrop for TypeHint<'a, Hi> {} /// Explicit type argument to function, constructor, or collection literal. /// 'hi = unit in NAST /// 'hi = Typing_defs.(locl ty) in TAST, /// and is used to record inferred type arguments, with wildcard hint. #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Targ<'a, Hi>(pub Hi, pub &'a Hint<'a>); impl<'a, Hi: TrivialDrop> TrivialDrop for Targ<'a, Hi> {} pub type TypeHint_<'a> = Option<&'a Hint<'a>>; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UserAttribute<'a, Ex, Fb, En, Hi> { pub name: Sid<'a>, /// user attributes are restricted to scalar values pub params: &'a [&'a Expr<'a, Ex, Fb, En, Hi>], } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for UserAttribute<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct FileAttribute<'a, Ex, Fb, En, Hi> { pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub namespace: &'a Nsenv<'a>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for FileAttribute<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Tparam<'a, Ex, Fb, En, Hi> { pub variance: oxidized::ast_defs::Variance, pub name: Sid<'a>, pub parameters: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub constraints: &'a [(oxidized::ast_defs::ConstraintKind, &'a Hint<'a>)], pub reified: oxidized::aast::ReifyKind, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Tparam<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct UseAsAlias<'a>( pub Option<Sid<'a>>, pub &'a Pstring<'a>, pub Option<Sid<'a>>, pub &'a [oxidized::aast::UseAsVisibility], ); impl<'a> TrivialDrop for UseAsAlias<'a> {} #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct InsteadofAlias<'a>(pub Sid<'a>, pub &'a Pstring<'a>, pub &'a [Sid<'a>]); impl<'a> TrivialDrop for InsteadofAlias<'a> {} pub use oxidized::aast::IsExtends; pub use oxidized::aast::EmitId; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Class_<'a, Ex, Fb, En, Hi> { pub span: &'a Pos<'a>, pub annotation: En, pub mode: oxidized::file_info::Mode, pub final_: bool, pub is_xhp: bool, pub has_xhp_keyword: bool, pub kind: oxidized::ast_defs::ClassKind, pub name: Sid<'a>, /// The type parameters of a class A<T> (T is the parameter) pub tparams: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub extends: &'a [&'a ClassHint<'a>], pub uses: &'a [&'a TraitHint<'a>], pub use_as_alias: &'a [&'a UseAsAlias<'a>], pub insteadof_alias: &'a [&'a InsteadofAlias<'a>], pub xhp_attr_uses: &'a [&'a XhpAttrHint<'a>], pub xhp_category: Option<&'a (&'a Pos<'a>, &'a [&'a Pstring<'a>])>, pub reqs: &'a [(&'a ClassHint<'a>, &'a oxidized::aast::IsExtends)], pub implements: &'a [&'a ClassHint<'a>], pub where_constraints: &'a [&'a WhereConstraintHint<'a>], pub consts: &'a [&'a ClassConst<'a, Ex, Fb, En, Hi>], pub typeconsts: &'a [&'a ClassTypeconst<'a, Ex, Fb, En, Hi>], pub vars: &'a [&'a ClassVar<'a, Ex, Fb, En, Hi>], pub methods: &'a [&'a Method_<'a, Ex, Fb, En, Hi>], pub attributes: &'a [ClassAttr<'a, Ex, Fb, En, Hi>], pub xhp_children: &'a [(&'a Pos<'a>, &'a XhpChild<'a>)], pub xhp_attrs: &'a [&'a XhpAttr<'a, Ex, Fb, En, Hi>], pub namespace: &'a Nsenv<'a>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub file_attributes: &'a [&'a FileAttribute<'a, Ex, Fb, En, Hi>], pub enum_: Option<&'a Enum_<'a>>, pub pu_enums: &'a [&'a PuEnum<'a, Ex, Fb, En, Hi>], pub doc_comment: Option<&'a DocComment<'a>>, pub emit_id: Option<&'a oxidized::aast::EmitId>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Class_<'a, Ex, Fb, En, Hi> { } pub type ClassHint<'a> = Hint<'a>; pub type TraitHint<'a> = Hint<'a>; pub type XhpAttrHint<'a> = Hint<'a>; pub use oxidized::aast::XhpAttrTag; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct XhpAttr<'a, Ex, Fb, En, Hi>( pub &'a TypeHint<'a, Hi>, pub &'a ClassVar<'a, Ex, Fb, En, Hi>, pub Option<oxidized::aast::XhpAttrTag>, pub Option<&'a (&'a Pos<'a>, &'a [&'a Expr<'a, Ex, Fb, En, Hi>])>, ); impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for XhpAttr<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum ClassAttr<'a, Ex, Fb, En, Hi> { CAName(&'a Sid<'a>), CAField(&'a CaField<'a, Ex, Fb, En, Hi>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassAttr<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct CaField<'a, Ex, Fb, En, Hi> { pub type_: CaType<'a>, pub id: Sid<'a>, pub value: Option<&'a Expr<'a, Ex, Fb, En, Hi>>, pub required: bool, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for CaField<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum CaType<'a> { CAHint(&'a Hint<'a>), CAEnum(&'a [&'a str]), } impl<'a> TrivialDrop for CaType<'a> {} #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassConst<'a, Ex, Fb, En, Hi> { pub type_: Option<&'a Hint<'a>>, pub id: Sid<'a>, /// expr = None indicates an abstract const pub expr: Option<&'a Expr<'a, Ex, Fb, En, Hi>>, pub doc_comment: Option<&'a DocComment<'a>>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassConst<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum TypeconstAbstractKind<'a> { TCAbstract(Option<&'a Hint<'a>>), TCPartiallyAbstract, TCConcrete, } impl<'a> TrivialDrop for TypeconstAbstractKind<'a> {} /// This represents a type const definition. If a type const is abstract then /// then the type hint acts as a constraint. Any concrete definition of the /// type const must satisfy the constraint. /// /// If the type const is not abstract then a type must be specified. #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassTypeconst<'a, Ex, Fb, En, Hi> { pub abstract_: TypeconstAbstractKind<'a>, pub name: Sid<'a>, pub constraint: Option<&'a Hint<'a>>, pub type_: Option<&'a Hint<'a>>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub span: &'a Pos<'a>, pub doc_comment: Option<&'a DocComment<'a>>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassTypeconst<'a, Ex, Fb, En, Hi> { } pub use oxidized::aast::XhpAttrInfo; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct ClassVar<'a, Ex, Fb, En, Hi> { pub final_: bool, pub xhp_attr: Option<&'a oxidized::aast::XhpAttrInfo>, pub abstract_: bool, pub visibility: oxidized::aast::Visibility, pub type_: &'a TypeHint<'a, Hi>, pub id: Sid<'a>, pub expr: Option<&'a Expr<'a, Ex, Fb, En, Hi>>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub doc_comment: Option<&'a DocComment<'a>>, pub is_promoted_variadic: bool, pub is_static: bool, pub span: &'a Pos<'a>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for ClassVar<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Method_<'a, Ex, Fb, En, Hi> { pub span: &'a Pos<'a>, pub annotation: En, pub final_: bool, pub abstract_: bool, pub static_: bool, pub visibility: oxidized::aast::Visibility, pub name: Sid<'a>, pub tparams: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub where_constraints: &'a [&'a WhereConstraintHint<'a>], pub variadic: FunVariadicity<'a, Ex, Fb, En, Hi>, pub params: &'a [&'a FunParam<'a, Ex, Fb, En, Hi>], pub cap: &'a TypeHint<'a, Hi>, pub unsafe_cap: &'a TypeHint<'a, Hi>, pub body: &'a FuncBody<'a, Ex, Fb, En, Hi>, pub fun_kind: oxidized::ast_defs::FunKind, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub ret: &'a TypeHint<'a, Hi>, /// true if this declaration has no body because it is an external method /// declaration (e.g. from an HHI file) pub external: bool, pub doc_comment: Option<&'a DocComment<'a>>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Method_<'a, Ex, Fb, En, Hi> { } pub type Nsenv<'a> = namespace_env::Env<'a>; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Typedef<'a, Ex, Fb, En, Hi> { pub annotation: En, pub name: Sid<'a>, pub tparams: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub constraint: Option<&'a Hint<'a>>, pub kind: &'a Hint<'a>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub mode: oxidized::file_info::Mode, pub vis: oxidized::aast::TypedefVisibility, pub namespace: &'a Nsenv<'a>, pub span: &'a Pos<'a>, pub emit_id: Option<&'a oxidized::aast::EmitId>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Typedef<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Gconst<'a, Ex, Fb, En, Hi> { pub annotation: En, pub mode: oxidized::file_info::Mode, pub name: Sid<'a>, pub type_: Option<&'a Hint<'a>>, pub value: &'a Expr<'a, Ex, Fb, En, Hi>, pub namespace: &'a Nsenv<'a>, pub span: &'a Pos<'a>, pub emit_id: Option<&'a oxidized::aast::EmitId>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Gconst<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct RecordDef<'a, Ex, Fb, En, Hi> { pub annotation: En, pub name: Sid<'a>, pub extends: Option<&'a RecordHint<'a>>, pub abstract_: bool, pub fields: &'a [(Sid<'a>, &'a Hint<'a>, Option<&'a Expr<'a, Ex, Fb, En, Hi>>)], pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub namespace: &'a Nsenv<'a>, pub span: &'a Pos<'a>, pub doc_comment: Option<&'a DocComment<'a>>, pub emit_id: Option<&'a oxidized::aast::EmitId>, } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for RecordDef<'a, Ex, Fb, En, Hi> { } pub type RecordHint<'a> = Hint<'a>; /// Pocket Universe Enumeration, e.g. /// /// ``` /// enum Foo { // pu_name /// // pu_case_types /// case type T0; /// case type T1; /// /// // pu_case_values /// case ?T0 default_value; /// case T1 foo; /// /// // pu_members /// :@A( // pum_atom /// // pum_types /// type T0 = string, /// type T1 = int, /// /// // pum_exprs /// default_value = null, /// foo = 42, /// ); /// :@B( ... ) /// ... /// } /// ``` #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct PuEnum<'a, Ex, Fb, En, Hi> { pub annotation: En, pub name: Sid<'a>, pub user_attributes: &'a [&'a UserAttribute<'a, Ex, Fb, En, Hi>], pub is_final: bool, pub case_types: &'a [&'a Tparam<'a, Ex, Fb, En, Hi>], pub case_values: &'a [&'a PuCaseValue<'a>], pub members: &'a [&'a PuMember<'a, Ex, Fb, En, Hi>], } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for PuEnum<'a, Ex, Fb, En, Hi> { } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct PuCaseValue<'a>(pub Sid<'a>, pub &'a Hint<'a>); impl<'a> TrivialDrop for PuCaseValue<'a> {} #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct PuMember<'a, Ex, Fb, En, Hi> { pub atom: Sid<'a>, pub types: &'a [(Sid<'a>, &'a Hint<'a>)], pub exprs: &'a [(Sid<'a>, &'a Expr<'a, Ex, Fb, En, Hi>)], } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for PuMember<'a, Ex, Fb, En, Hi> { } pub type FunDef<'a, Ex, Fb, En, Hi> = Fun_<'a, Ex, Fb, En, Hi>; #[derive( Clone, Copy, Debug, Eq, FromOcamlRepIn, Hash, NoPosHash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub enum Def<'a, Ex, Fb, En, Hi> { Fun(&'a FunDef<'a, Ex, Fb, En, Hi>), Class(&'a Class_<'a, Ex, Fb, En, Hi>), RecordDef(&'a RecordDef<'a, Ex, Fb, En, Hi>), Stmt(&'a Stmt<'a, Ex, Fb, En, Hi>), Typedef(&'a Typedef<'a, Ex, Fb, En, Hi>), Constant(&'a Gconst<'a, Ex, Fb, En, Hi>), Namespace(&'a (Sid<'a>, &'a Program<'a, Ex, Fb, En, Hi>)), NamespaceUse(&'a [(oxidized::aast::NsKind, Sid<'a>, Sid<'a>)]), SetNamespaceEnv(&'a Nsenv<'a>), FileAttributes(&'a FileAttribute<'a, Ex, Fb, En, Hi>), } impl<'a, Ex: TrivialDrop, Fb: TrivialDrop, En: TrivialDrop, Hi: TrivialDrop> TrivialDrop for Def<'a, Ex, Fb, En, Hi> { } pub use oxidized::aast::NsKind; pub use oxidized::aast::BreakContinueLevel;
use crate::error::{CellbaseError, CommitError, Error, UnclesError}; use crate::header_verifier::HeaderResolver; use crate::{TransactionVerifier, Verifier}; use ckb_core::cell::ResolvedTransaction; use ckb_core::header::Header; use ckb_core::transaction::{Capacity, CellInput, CellOutput, Transaction}; use ckb_core::Cycle; use ckb_core::{block::Block, BlockNumber}; use ckb_store::ChainStore; use ckb_traits::{BlockMedianTimeContext, ChainProvider}; use fnv::FnvHashSet; use log::error; use numext_fixed_uint::U256; use rayon::iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator}; use std::collections::HashSet; use std::sync::Arc; //TODO: cellbase, witness #[derive(Clone)] pub struct BlockVerifier<P> { // Verify if the committed and proposed transactions contains duplicate duplicate: DuplicateVerifier, // Verify the cellbase cellbase: CellbaseVerifier, // Verify the the committed and proposed transactions merkle root match header's announce merkle_root: MerkleRootVerifier, // Verify the the uncle uncles: UnclesVerifier<P>, // Verify the the propose-then-commit consensus rule commit: CommitVerifier<P>, // Verify the amount of proposals does not exceed the limit. block_proposals_limit: BlockProposalsLimitVerifier, // Verify the size of the block does not exceed the limit. block_bytes: BlockBytesVerifier, } impl<P> BlockVerifier<P> where P: ChainProvider + Clone, { pub fn new(provider: P) -> Self { let proof_size = provider.consensus().pow_engine().proof_size(); let max_block_proposals_limit = provider.consensus().max_block_proposals_limit(); let max_block_bytes = provider.consensus().max_block_bytes(); BlockVerifier { // TODO change all new fn's chain to reference duplicate: DuplicateVerifier::new(), cellbase: CellbaseVerifier::new(), merkle_root: MerkleRootVerifier::new(), uncles: UnclesVerifier::new(provider.clone()), commit: CommitVerifier::new(provider), block_proposals_limit: BlockProposalsLimitVerifier::new(max_block_proposals_limit), block_bytes: BlockBytesVerifier::new(max_block_bytes, proof_size), } } } impl<P: ChainProvider + Clone> Verifier for BlockVerifier<P> { type Target = Block; fn verify(&self, target: &Block) -> Result<(), Error> { self.block_proposals_limit.verify(target)?; self.block_bytes.verify(target)?; self.cellbase.verify(target)?; self.duplicate.verify(target)?; self.merkle_root.verify(target)?; self.commit.verify(target)?; self.uncles.verify(target) } } #[derive(Clone)] pub struct CellbaseVerifier {} impl CellbaseVerifier { pub fn new() -> Self { CellbaseVerifier {} } pub fn verify(&self, block: &Block) -> Result<(), Error> { let cellbase_len = block .transactions() .iter() .filter(|tx| tx.is_cellbase()) .count(); // empty checked, block must contain cellbase if cellbase_len != 1 { return Err(Error::Cellbase(CellbaseError::InvalidQuantity)); } let cellbase_transaction = &block.transactions()[0]; if !cellbase_transaction.is_cellbase() { return Err(Error::Cellbase(CellbaseError::InvalidPosition)); } let cellbase_input = &cellbase_transaction.inputs()[0]; if cellbase_input != &CellInput::new_cellbase_input(block.header().number()) { return Err(Error::Cellbase(CellbaseError::InvalidInput)); } // currently, we enforce`type` field of a cellbase output cell must be absent if cellbase_transaction .outputs() .iter() .any(|op| op.type_.is_some()) { return Err(Error::Cellbase(CellbaseError::InvalidOutput)); } if cellbase_transaction .outputs() .iter() .any(CellOutput::is_occupied_capacity_overflow) { return Err(Error::CapacityOverflow); }; Ok(()) } } #[derive(Clone)] pub struct DuplicateVerifier {} impl DuplicateVerifier { pub fn new() -> Self { DuplicateVerifier {} } pub fn verify(&self, block: &Block) -> Result<(), Error> { let mut seen = HashSet::with_capacity(block.transactions().len()); if !block.transactions().iter().all(|tx| seen.insert(tx.hash())) { return Err(Error::CommitTransactionDuplicate); } let mut seen = HashSet::with_capacity(block.proposals().len()); if !block.proposals().iter().all(|id| seen.insert(id)) { return Err(Error::ProposalTransactionDuplicate); } Ok(()) } } #[derive(Clone, Default)] pub struct MerkleRootVerifier {} impl MerkleRootVerifier { pub fn new() -> Self { MerkleRootVerifier::default() } pub fn verify(&self, block: &Block) -> Result<(), Error> { if block.header().transactions_root() != &block.cal_transactions_root() { return Err(Error::CommitTransactionsRoot); } if block.header().witnesses_root() != &block.cal_witnesses_root() { return Err(Error::WitnessesMerkleRoot); } if block.header().proposals_root() != &block.cal_proposals_root() { return Err(Error::ProposalTransactionsRoot); } Ok(()) } } pub struct HeaderResolverWrapper<'a, CP> { provider: CP, header: &'a Header, parent: Option<Header>, } impl<'a, CP: ChainProvider> HeaderResolverWrapper<'a, CP> { pub fn new(header: &'a Header, provider: CP) -> Self { let parent = provider.block_header(&header.parent_hash()); HeaderResolverWrapper { parent, header, provider, } } } impl<'a, CP: ChainProvider> HeaderResolver for HeaderResolverWrapper<'a, CP> { fn header(&self) -> &Header { self.header } fn parent(&self) -> Option<&Header> { self.parent.as_ref() } fn calculate_difficulty(&self) -> Option<U256> { self.parent() .and_then(|parent| self.provider.calculate_difficulty(parent)) } } // TODO redo uncle verifier, check uncle proposal duplicate #[derive(Clone)] pub struct UnclesVerifier<CP> { provider: CP, } impl<CP: ChainProvider + Clone> UnclesVerifier<CP> { pub fn new(provider: CP) -> Self { UnclesVerifier { provider } } // - uncles_hash // - uncles_num // - depth // - uncle not in main chain // - uncle duplicate pub fn verify(&self, block: &Block) -> Result<(), Error> { // verify uncles_count let uncles_count = block.uncles().len() as u32; if uncles_count != block.header().uncles_count() { return Err(Error::Uncles(UnclesError::MissMatchCount { expected: block.header().uncles_count(), actual: uncles_count, })); } // verify uncles_hash let actual_uncles_hash = block.cal_uncles_hash(); if &actual_uncles_hash != block.header().uncles_hash() { return Err(Error::Uncles(UnclesError::InvalidHash { expected: block.header().uncles_hash().to_owned(), actual: actual_uncles_hash, })); } // if block.uncles is empty, return if uncles_count == 0 { return Ok(()); } // if block is genesis, which is expected with zero uncles, return error if block.is_genesis() { return Err(Error::Uncles(UnclesError::OverCount { max: 0, actual: uncles_count, })); } // verify uncles length =< max_uncles_num let max_uncles_num = self.provider.consensus().max_uncles_num() as u32; if uncles_count > max_uncles_num { return Err(Error::Uncles(UnclesError::OverCount { max: max_uncles_num, actual: uncles_count, })); } // verify uncles age let max_uncles_age = self.provider.consensus().max_uncles_age() as u64; for uncle in block.uncles() { let depth = block.header().number().saturating_sub(uncle.number()); if depth > max_uncles_age || depth < 1 { return Err(Error::Uncles(UnclesError::InvalidDepth { min: block.header().number().saturating_sub(max_uncles_age), max: block.header().number().saturating_sub(1), actual: uncle.number(), })); } } // cB // cB.p^0 1 depth, valid uncle // cB.p^1 ---/ 2 // cB.p^2 -----/ 3 // cB.p^3 -------/ 4 // cB.p^4 ---------/ 5 // cB.p^5 -----------/ 6 // cB.p^6 -------------/ // cB.p^7 // verify uncles is not included in main chain // TODO: cache context let mut excluded = FnvHashSet::default(); let mut included = FnvHashSet::default(); excluded.insert(block.header().hash()); let mut block_hash = block.header().parent_hash().to_owned(); excluded.insert(block_hash.clone()); for _ in 0..max_uncles_age { if let Some(header) = self.provider.block_header(&block_hash) { let parent_hash = header.parent_hash().to_owned(); excluded.insert(parent_hash.clone()); if let Some(uncles) = self.provider.uncles(&block_hash) { uncles.iter().for_each(|uncle| { excluded.insert(uncle.header.hash()); }); }; block_hash = parent_hash; } else { break; } } let block_difficulty_epoch = block.header().number() / self.provider.consensus().difficulty_adjustment_interval(); for uncle in block.uncles() { let uncle_difficulty_epoch = uncle.header().number() / self.provider.consensus().difficulty_adjustment_interval(); if uncle.header().difficulty() != block.header().difficulty() { return Err(Error::Uncles(UnclesError::InvalidDifficulty)); } if block_difficulty_epoch != uncle_difficulty_epoch { return Err(Error::Uncles(UnclesError::InvalidDifficultyEpoch)); } let uncle_header = uncle.header.clone(); let uncle_hash = uncle_header.hash(); if included.contains(&uncle_hash) { return Err(Error::Uncles(UnclesError::Duplicate(uncle_hash))); } if excluded.contains(&uncle_hash) { return Err(Error::Uncles(UnclesError::InvalidInclude(uncle_hash))); } if uncle_header.proposals_root() != &uncle.cal_proposals_root() { return Err(Error::Uncles(UnclesError::ProposalTransactionsRoot)); } let mut seen = HashSet::with_capacity(uncle.proposals().len()); if !uncle.proposals().iter().all(|id| seen.insert(id)) { return Err(Error::Uncles(UnclesError::ProposalTransactionDuplicate)); } if !self .provider .consensus() .pow_engine() .verify_header(&uncle_header) { return Err(Error::Uncles(UnclesError::InvalidProof)); } included.insert(uncle_hash); } Ok(()) } } #[derive(Clone)] pub struct TransactionsVerifier { max_cycles: Cycle, } impl TransactionsVerifier { pub fn new(max_cycles: Cycle) -> Self { TransactionsVerifier { max_cycles } } pub fn verify<M, CS: ChainStore>( &self, resolved: &[ResolvedTransaction], store: Arc<CS>, block_reward: Capacity, block_median_time_context: M, tip_number: BlockNumber, cellbase_maturity: BlockNumber, ) -> Result<(), Error> where M: BlockMedianTimeContext + Sync, { // verify cellbase reward let cellbase = &resolved[0]; let fee: Capacity = resolved .iter() .skip(1) .map(ResolvedTransaction::fee) .try_fold(Capacity::zero(), |acc, rhs| { rhs.and_then(|x| acc.safe_add(x)) })?; if cellbase.transaction.outputs_capacity()? > block_reward.safe_add(fee)? { return Err(Error::Cellbase(CellbaseError::InvalidReward)); } // make verifiers orthogonal let cycles_set = resolved .par_iter() .skip(1) .enumerate() .map(|(index, tx)| { TransactionVerifier::new( &tx, Arc::clone(&store), &block_median_time_context, tip_number, cellbase_maturity, ) .verify(self.max_cycles) .map_err(|e| Error::Transactions((index, e))) .map(|cycles| cycles) }) .collect::<Result<Vec<_>, _>>()?; let sum: Cycle = cycles_set.iter().sum(); if sum > self.max_cycles { Err(Error::ExceededMaximumCycles) } else { Ok(()) } } } #[derive(Clone)] pub struct CommitVerifier<CP> { provider: CP, } impl<CP: ChainProvider + Clone> CommitVerifier<CP> { pub fn new(provider: CP) -> Self { CommitVerifier { provider } } pub fn verify(&self, block: &Block) -> Result<(), Error> { if block.is_genesis() { return Ok(()); } let block_number = block.header().number(); let proposal_window = self.provider.consensus().tx_proposal_window(); let proposal_start = block_number.saturating_sub(proposal_window.start()); let mut proposal_end = block_number.saturating_sub(proposal_window.end()); let mut block_hash = self .provider .get_ancestor(&block.header().parent_hash(), proposal_end) .map(|h| h.hash()) .ok_or_else(|| Error::Commit(CommitError::AncestorNotFound))?; let mut proposal_txs_ids = FnvHashSet::default(); while proposal_end >= proposal_start { let header = self .provider .block_header(&block_hash) .ok_or_else(|| Error::Commit(CommitError::AncestorNotFound))?; if header.is_genesis() { break; } if let Some(ids) = self.provider.block_proposal_txs_ids(&block_hash) { proposal_txs_ids.extend(ids); } if let Some(uncles) = self.provider.uncles(&block_hash) { uncles .iter() .for_each(|uncle| proposal_txs_ids.extend(uncle.proposals())); } block_hash = header.parent_hash().to_owned(); proposal_end -= 1; } let committed_ids: FnvHashSet<_> = block .transactions() .par_iter() .skip(1) .map(Transaction::proposal_short_id) .collect(); let difference: Vec<_> = committed_ids.difference(&proposal_txs_ids).collect(); if !difference.is_empty() { error!(target: "chain", "Block {} {:x}", block.header().number(), block.header().hash()); error!(target: "chain", "proposal_window proposal_start {}", proposal_start); error!(target: "chain", "committed_ids {} ", serde_json::to_string(&committed_ids).unwrap()); error!(target: "chain", "proposal_txs_ids {} ", serde_json::to_string(&proposal_txs_ids).unwrap()); return Err(Error::Commit(CommitError::Invalid)); } Ok(()) } } #[derive(Clone)] pub struct BlockProposalsLimitVerifier { block_proposals_limit: u64, } impl BlockProposalsLimitVerifier { pub fn new(block_proposals_limit: u64) -> Self { BlockProposalsLimitVerifier { block_proposals_limit, } } pub fn verify(&self, block: &Block) -> Result<(), Error> { let proposals_len = block.proposals().len() as u64; if proposals_len <= self.block_proposals_limit { Ok(()) } else { Err(Error::ExceededMaximumProposalsLimit) } } } #[derive(Clone)] pub struct BlockBytesVerifier { block_bytes_limit: u64, proof_size: usize, } impl BlockBytesVerifier { pub fn new(block_bytes_limit: u64, proof_size: usize) -> Self { BlockBytesVerifier { block_bytes_limit, proof_size, } } pub fn verify(&self, block: &Block) -> Result<(), Error> { let block_bytes = block.serialized_size(self.proof_size) as u64; if block_bytes <= self.block_bytes_limit { Ok(()) } else { Err(Error::ExceededMaximumBlockBytes) } } }
#![allow(clippy::identity_op)] #![allow(clippy::large_enum_variant)] use crate::utils::to_u8_slice; #[derive(Copy, Clone, Debug)] pub enum XGbePortOp { TurnOn, TurnOff, } impl XGbePortOp { pub fn get_raw_data(self) -> Vec<u8> { match self { XGbePortOp::TurnOn => vec![0x01, 0, 0, 0], XGbePortOp::TurnOff => vec![0; 4], } } } #[derive(Copy, Clone, Debug, Default)] pub struct XGbePortParam { pub src_mac: [u8; 6], pub src_ip: [u8; 4], pub src_port: u16, pub dst_mac: [u8; 6], pub dst_ip: [u8; 4], pub dst_port: u16, pub pkt_len: u32, } impl XGbePortParam { pub fn get_raw_data(&self) -> Vec<u8> { let mut result = Vec::new(); result.append(&mut self.src_mac.iter().rev().cloned().collect::<Vec<_>>()); result.append(&mut self.src_ip.iter().rev().cloned().collect::<Vec<_>>()); result.push(((self.src_port >> 0) & 0xff_u16) as u8); result.push(((self.src_port >> 8) & 0xff_u16) as u8); result.append(&mut self.dst_mac.iter().rev().cloned().collect::<Vec<_>>()); result.append(&mut self.dst_ip.iter().rev().cloned().collect::<Vec<_>>()); result.push(((self.dst_port >> 0) & 0xff_u16) as u8); result.push(((self.dst_port >> 8) & 0xff_u16) as u8); for i in 0..4 { result.push(((self.pkt_len >> (8 * i)) & 0xff_u32) as u8); } result } } #[derive(Copy, Clone, Debug)] pub struct AppParam { pub mode_sel: u32, pub test_mode_streams: [u64; 8], pub num_of_streams_sel: u32, pub first_ch: u32, pub last_ch: u32, } #[derive(Copy, Clone, Debug)] pub enum Snap2Msg { XGbePortParams([XGbePortParam; 9]), AppParam(AppParam), XGbePortOp(XGbePortOp), } impl Snap2Msg { pub fn msg_type_code(&self) -> u8 { match self { Snap2Msg::XGbePortParams(..) => 0xf1, Snap2Msg::AppParam { .. } => 0xf2, Snap2Msg::XGbePortOp(..) => 0xfb, } } pub fn get_raw_data(&self) -> Vec<u8> { let mut result = Vec::new(); result.push(self.msg_type_code()); result.push(0); match *self { Snap2Msg::XGbePortParams(ref x) => { for i in x { result.append(&mut i.get_raw_data()); } } Snap2Msg::AppParam(AppParam { mode_sel, ref test_mode_streams, num_of_streams_sel, first_ch, last_ch, }) => { result.extend_from_slice(to_u8_slice(&mode_sel)); test_mode_streams .iter() .for_each(|x| result.extend_from_slice(to_u8_slice(x))); result.extend_from_slice(to_u8_slice(&num_of_streams_sel)); result.extend_from_slice(to_u8_slice(&first_ch)); result.extend_from_slice(to_u8_slice(&last_ch)); } Snap2Msg::XGbePortOp(x) => result.append(&mut x.get_raw_data()), } result } }
use auto_impl::auto_impl; #[auto_impl(&)] trait Foo { fn foo<const I: i32>(&self); } fn main() {}
use std::borrow::Cow; use std::io::Write; use quick_xml::events::attributes::Attribute; use quick_xml::events::{BytesEnd, BytesStart, BytesText, Event}; use quick_xml::name::QName; use quick_xml::Writer; use crate::encoding_type::EncodingType; use crate::error::KbinError; use crate::node::NodeCollection; use crate::node_types::StandardType; use crate::to_text_xml::ToTextXml; impl ToTextXml for NodeCollection { /// At the moment, decoding the value of a `NodeDefinition` will decode /// strings into UTF-8. fn encoding(&self) -> EncodingType { EncodingType::UTF_8 } fn write<W: Write>(&self, writer: &mut Writer<W>) -> Result<(), KbinError> { let base = self.base(); let key = base.key()?.ok_or(KbinError::InvalidState)?; let value = match base.value() { Ok(value) => Some(value), Err(e) => match e { KbinError::InvalidNodeType { .. } => None, _ => return Err(e), }, }; let mut elem = BytesStart::new(key.clone()); if base.is_array { let values = value.as_ref().ok_or(KbinError::InvalidState)?.as_array()?; elem.push_attribute(Attribute { key: QName(b"__count"), value: Cow::Owned(values.len().to_string().into_bytes()), }); } if base.node_type == StandardType::Binary { let value = value.as_ref().ok_or(KbinError::InvalidState)?.as_slice()?; elem.push_attribute(Attribute { key: QName(b"__size"), value: Cow::Owned(value.len().to_string().into_bytes()), }); } // Only add a `__type` attribute if this is not a `NodeStart` node if base.node_type != StandardType::NodeStart { elem.push_attribute(Attribute { key: QName(b"__type"), value: Cow::Borrowed(base.node_type.name.as_bytes()), }); } for attribute in self.attributes() { let key = attribute .key()? .ok_or(KbinError::InvalidState)? .into_bytes(); let value = attribute.value()?.to_string(); elem.push_attribute(Attribute { key: QName(&key), value: Cow::Borrowed(value.as_bytes()), }); } let start_elem = match value { Some(value) => { writer.write_event(Event::Start(elem))?; let value = value.to_string(); let elem = BytesText::new(&value); writer.write_event(Event::Text(elem))?; None }, None => Some(elem), }; let has_value = start_elem.is_none(); let has_children = !self.children().is_empty(); // A `Some` value here means the start element was not written if let Some(start_elem) = start_elem { if !has_children { writer.write_event(Event::Empty(start_elem))?; } else { writer.write_event(Event::Start(start_elem))?; } } for child in self.children() { child.write(writer)?; } if has_value || has_children { let end_elem = BytesEnd::new(key); writer.write_event(Event::End(end_elem))?; } Ok(()) } }
#[path = "support/macros.rs"] #[macro_use] mod macros; use criterion::{criterion_group, criterion_main, Criterion}; fn bench_vec3_length(c: &mut Criterion) { use criterion::Benchmark; c.bench( "vec3 length", Benchmark::new("glam", |b| { use glam::Vec3; bench_unop!(b, op => length, ty => Vec3) }) .with_function("cgmath", |b| { use cgmath::{InnerSpace, Vector3}; bench_unop!(b, op => magnitude, ty => Vector3<f32>) }) .with_function("nalgebra", |b| { use nalgebra::Vector3; bench_unop!(b, op => magnitude, ty => Vector3<f32>) }) .with_function("euclid", |b| { use euclid::{UnknownUnit, Vector3D}; bench_unop!(b, op => length, ty => Vector3D<f32, UnknownUnit>) }), ); } fn bench_vec3_normalize(c: &mut Criterion) { use criterion::Benchmark; c.bench( "vec3 normalize", Benchmark::new("glam", |b| { use glam::Vec3; bench_unop!(b, op => normalize, ty => Vec3) }) .with_function("cgmath", |b| { use cgmath::{InnerSpace, Vector3}; bench_unop!(b, op => normalize, ty => Vector3<f32>) }) .with_function("nalgebra", |b| { use nalgebra::Vector3; bench_unop!(b, op => normalize, ty => Vector3<f32>) }) .with_function("euclid", |b| { use euclid::{UnknownUnit, Vector3D}; bench_unop!(b, op => normalize, ty => Vector3D<f32, UnknownUnit>) }), ); } fn bench_vec3_dot(c: &mut Criterion) { use criterion::Benchmark; c.bench( "vec3 dot", Benchmark::new("glam", |b| { use glam::Vec3; bench_binop!(b, op => dot, ty1 => Vec3, ty2 => Vec3) }) .with_function("cgmath", |b| { use cgmath::{InnerSpace, Vector3}; bench_binop!(b, op => dot, ty1 => Vector3<f32>, ty2 => Vector3<f32>) }) .with_function("nalgebra", |b| { use nalgebra::Vector3; bench_binop!(b, op => dot, ty1 => Vector3<f32>, ty2 => Vector3<f32>, param => by_ref) }) .with_function("euclid", |b| { use euclid::{Vector3D, UnknownUnit}; bench_binop!(b, op => dot, ty1 => Vector3D<f32, UnknownUnit>, ty2 => Vector3D<f32, UnknownUnit>) }), ); } fn bench_vec3_cross(c: &mut Criterion) { use criterion::Benchmark; c.bench( "vec3 cross", Benchmark::new("glam", |b| { use glam::Vec3; bench_binop!(b, op => cross, ty1 => Vec3, ty2 => Vec3) }) .with_function("cgmath", |b| { use cgmath::Vector3; bench_binop!(b, op => cross, ty1 => Vector3<f32>, ty2 => Vector3<f32>) }) .with_function("nalgebra", |b| { use nalgebra::Vector3; bench_binop!(b, op => cross, ty1 => Vector3<f32>, ty2 => Vector3<f32>, param => by_ref) }) .with_function("euclid", |b| { use euclid::{Vector3D, UnknownUnit}; bench_binop!(b, op => cross, ty1 => Vector3D<f32, UnknownUnit>, ty2 => Vector3D<f32, UnknownUnit>) }), ); } criterion_group!( vec_benches, bench_vec3_length, bench_vec3_normalize, bench_vec3_dot, bench_vec3_cross ); criterion_main!(vec_benches);
use core::fmt; use std::collections::{HashSet, VecDeque}; use std::hash::Hash; use std::net::SocketAddr; use std::ops::Deref; use std::sync::Arc; use std::time::Duration; use clap::Parser; use dashmap::DashMap; use hyper::{Body, Request, Response}; use internment::Intern; use petgraph::graph::NodeIndex; use petgraph::stable_graph::StableUnGraph; use petgraph_graphml::GraphMl; use color_eyre::{Report, Result}; use tokio::sync::RwLock; use crate::cli::CliOptions; use crate::ext::{FutureExt, ResultExt}; use crate::networking::{Network, NetworkEvent}; pub mod cli; pub mod ext; pub mod json; pub mod networking; pub mod proto; #[derive(Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct CreditcoinNode { endpoint: Intern<String>, tip: Option<u64>, } impl From<String> for CreditcoinNode { fn from(endpoint: String) -> Self { Self { endpoint: Intern::new(endpoint), tip: None, } } } impl fmt::Debug for CreditcoinNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("CreditcoinNode") .field("endpoint", &*self.endpoint) .finish() } } impl fmt::Display for CreditcoinNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.endpoint) } } type NetworkTopology = Arc<RwLock<StableUnGraph<CreditcoinNode, ()>>>; async fn topology_request( _req: Request<Body>, topology: NetworkTopology, ) -> Result<Response<Body>> { log::warn!("GOT REQUEST"); let graph = json::Graph::from(&*topology.read().await); let json = serde_json::to_string(&graph)?; let response = Response::builder() .header(hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN, "*") .header(hyper::header::CONTENT_TYPE, "application/json") .body(Body::from(json))?; Ok(response) } #[tokio::main] async fn main() -> Result<()> { color_eyre::install()?; pretty_env_logger::init(); let mut opts = CliOptions::parse(); let mut rng = rand::thread_rng(); let key = secp256k1::SecretKey::new(&mut rng); let seeds: Vec<_> = std::mem::take(&mut opts.seeds) .iter() .cloned() .map(CreditcoinNode::from) .collect(); let network = Arc::new(Network::with_options(key, &opts).await?); let mut updates = network.take_update_rx().unwrap(); let mut visited = HashSet::new(); let mut queue = VecDeque::new(); visited.extend(seeds.clone()); queue.extend(seeds.clone()); let mut stop = network.stop_rx(); let node_ids: DashMap<String, NodeIndex> = DashMap::new(); let topology: StableUnGraph<CreditcoinNode, ()> = StableUnGraph::default(); let topology = Arc::new(RwLock::new(topology)); let addr: SocketAddr = opts .server .as_ref() .map(|s| s.as_str()) .unwrap_or_else(|| "127.0.0.1:4321") .parse()?; let topo_clone = topology.clone(); let make_service = hyper::service::make_service_fn(move |_| { let topology = topo_clone.clone(); async move { Ok::<_, Report>(hyper::service::service_fn(move |req| { topology_request(req, topology.clone()) })) } }); if opts.server.is_some() { let server = hyper::Server::bind(&addr).serve(make_service); // let server = hyper::Server::bind(&addr).serve(make_service); // let listener = Listener::new(&opts).await?; let shutdown = server.with_graceful_shutdown({ let mut stop = network.stop_rx(); async move { stop.recv().await.log_err() } }); tokio::spawn(shutdown); } 'a: loop { while let Some(node) = queue.pop_front() { log::debug!("visiting {}", node); if let Ok(()) = stop.try_recv() { log::warn!("Stopping main loop"); break 'a; } let network = Arc::clone(&network); let mut stop = network.stop_rx(); tokio::spawn(async move { match network.connect_to(&*node.endpoint).await { Ok(node_id) => { let mut timer = tokio::time::interval(Duration::from_secs(60)); timer.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { tokio::select! { _ = timer.tick() => { if let Err(e) = network .request_peers_of(node_id) .timeout(Duration::from_secs(55)) .await { log::error!("received error: {}", e); break; } } _ = stop.recv() => { break; } } } } Err(e) => log::error!("failed to connect to {}: {}", &node, e), } }); } tokio::select! { _ = stop.recv() => { log::warn!("Stopping main loop"); break 'a; } update = updates.recv() => { if let Some(NetworkEvent::DiscoveredPeers { node, peers }) = update { log::info!("Discovered peers of {}: {:?}", node, peers); let mut topo = topology.write().await; let node_id = if let Some(id) = node_ids.get(&*node.endpoint) { *id } else { let id = topo.add_node(node); node_ids.insert(node.endpoint.deref().clone(), id); id }; let peerset: HashSet<_> = peers.into_iter().map(|nod| { if let Some(id) = node_ids.get(&nod) { *id } else { let id = topo.add_node(CreditcoinNode::from(nod.clone())); node_ids.insert(nod, id); id } }).collect(); let topology_peers: HashSet<_> = topo .neighbors(node_id) .into_iter() .collect(); let new_peers = &peerset - &topology_peers; let stale_peers = &topology_peers - &peerset; for peer in new_peers { if node_id == peer { continue; } topo.add_edge(node_id, peer, ()); let peer = topo.node_weight(peer).unwrap(); if visited.insert(peer.clone()) { queue.push_back(peer.clone()); } } for peer in stale_peers { if let Some(edge) = topo.find_edge(node_id, peer) { topo.remove_edge(edge); } } } } // conn = listener.accept() => { // log::info!("Got new connection"); // match conn { // Ok((stream, addr)) => { // tokio::spawn(handle_connection(stream, addr, network.stop_rx(), topology.clone())); // }, // Err(e) => { // log::error!("Error on websocket stream: {}", e); // } // } // } } } let topo = topology.read().await; if let Some(dot_out) = &opts.dot { log::info!("Writing graphviz output"); let dot = petgraph::dot::Dot::with_config(&*topo, &[petgraph::dot::Config::EdgeNoLabel]); std::fs::write(dot_out, format!("{:?}", dot))?; } if let Some(ml_out) = &opts.graphml { log::info!("Writing graphml output"); let graphml = GraphMl::new(&*topo) .export_node_weights_display() .to_string(); std::fs::write(ml_out, graphml)?; } if let Some(json_out) = &opts.json { log::info!("Writing json output"); let graph = json::Graph::new(&*topo); let json = serde_json::to_vec(&graph)?; std::fs::write(json_out, json)?; } drop(network); updates.recv().await; Ok(()) }
use std::io::{self, Read}; use permutohedron::heap_recursive; extern crate intcode_computer; use intcode_computer::{address_counter, State}; fn read_stdin() -> String{ let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).expect("did not recieve anything from stdin"); return buffer; } fn max_signal(opcodes: &Vec<i64>, setting_sequence: &Vec<i64>, input_signal: &i64) -> i64{ let mut signal = *input_signal; for i in 0..(setting_sequence.len()){ let result: State = address_counter(&opcodes, &vec![setting_sequence[i], signal]); signal = result.get_output().expect("Did not get an output when one was expected"); } return signal; } fn find_max_signal(opcodes: &Vec<i64>, base_seq: Vec<i64>) -> i64{ let mut best_signal: i64 = 0; let mut data = base_seq.clone(); let mut permutations = Vec::new(); heap_recursive(&mut data, |permutation| { permutations.push(permutation.to_vec()) }); for seq in &permutations{ let signal_strength = max_signal(&opcodes, &seq, &0); if signal_strength > best_signal{ best_signal = signal_strength; } } return best_signal; } fn max_signal_p2(opcodes: &Vec<i64>, setting_sequence: &Vec<i64>, input_signal: &i64) -> i64{ let mut signal = *input_signal; let mut latest_end_signal = 0; let mut states: Vec<Option<State>> = vec![None, None, None, None, None]; loop { for i in 0..(setting_sequence.len()){ if states[i].as_ref().map_or(false, |s| s.is_halted()){ return latest_end_signal; } let result: State = match &states[i]{ None => { address_counter(&opcodes, &vec![setting_sequence[i], signal]) }, Some(s) => { //println!("Input: {:?}", s.get_input()); s.add_input(signal).process() } }; signal = match result.get_output(){ Some(o) => *o, None => return latest_end_signal }; states[i] = Some(result.clean_output()); } latest_end_signal = signal; } } fn find_max_signal_p2(opcodes: &Vec<i64>, base_seq: Vec<i64>) -> i64{ let mut best_signal: i64 = 0; let mut data = base_seq.clone(); let mut permutations = Vec::new(); heap_recursive(&mut data, |permutation| { permutations.push(permutation.to_vec()) }); for seq in &permutations{ let signal_strength = max_signal_p2(&opcodes, &seq, &0); if signal_strength > best_signal{ best_signal = signal_strength; } } return best_signal; } fn main (){ let io_input: Vec<i64> = read_stdin() .trim() .split(",") .map(|s| s.parse::<i64>().expect("of of the lines of the input could not be parsed into an integer") ).collect(); println!("Started!"); println!("Max signal: {:?}", find_max_signal(&io_input, (0..5).collect())); //println!("test: {:?}", max_signal_p2(&io_input, &vec![9,8,7,6,5], &0)); println!("Max signal: {:?}", find_max_signal_p2(&io_input, (5..10).collect())); }
use crate::binds::{Bind, BindCount, BindsInternal, CollectBinds}; use crate::WriteSql; use std::fmt::{self, Write}; #[derive(Debug, Clone)] pub struct Offset(pub(crate) OffsetI); impl Into<Offset> for OffsetI { fn into(self) -> Offset { Offset(self) } } impl Offset { pub fn raw(sql: &str) -> Self { OffsetI::Raw(sql.to_string()).into() } } impl<T> From<T> for Offset where T: Into<i32>, { fn from(count: T) -> Self { OffsetI::Count(count.into()).into() } } #[derive(Debug, Clone)] pub(crate) enum OffsetI { Count(i32), Raw(String), } impl WriteSql for &OffsetI { fn write_sql<W: Write>(self, f: &mut W, bind_count: &mut BindCount) -> fmt::Result { match self { OffsetI::Count(_) => bind_count.write_sql(f), OffsetI::Raw(sql) => write!(f, "{}", sql), } } } impl CollectBinds for OffsetI { fn collect_binds(&self, binds: &mut BindsInternal) { match self { OffsetI::Count(count) => { binds.push(Bind::I32(*count)); } OffsetI::Raw(_) => {} } } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - TIM16 control register 1"] pub tim16_cr1: TIM16_CR1, _reserved1: [u8; 0x02], #[doc = "0x04 - TIM16 control register 2"] pub tim16_cr2: TIM16_CR2, _reserved2: [u8; 0x06], #[doc = "0x0c - TIM16 DMA/interrupt enable register"] pub tim16_dier: TIM16_DIER, _reserved3: [u8; 0x02], #[doc = "0x10 - TIM16 status register"] pub tim16_sr: TIM16_SR, _reserved4: [u8; 0x02], #[doc = "0x14 - TIM16 event generation register"] pub tim16_egr: TIM16_EGR, _reserved5: [u8; 0x02], _reserved_5_tim16_ccmr1: [u8; 0x04], _reserved6: [u8; 0x04], #[doc = "0x20 - TIM16 capture/compare enable register"] pub tim16_ccer: TIM16_CCER, _reserved7: [u8; 0x02], #[doc = "0x24 - TIM16 counter"] pub tim16_cnt: TIM16_CNT, #[doc = "0x28 - TIM16 prescaler"] pub tim16_psc: TIM16_PSC, _reserved9: [u8; 0x02], #[doc = "0x2c - TIM16 auto-reload register"] pub tim16_arr: TIM16_ARR, #[doc = "0x30 - TIM16 repetition counter register"] pub tim16_rcr: TIM16_RCR, _reserved11: [u8; 0x02], #[doc = "0x34 - TIM16 capture/compare register 1"] pub tim16_ccr1: TIM16_CCR1, _reserved12: [u8; 0x0c], #[doc = "0x44 - TIM16 break and dead-time register"] pub tim16_bdtr: TIM16_BDTR, _reserved13: [u8; 0x0c], #[doc = "0x54 - TIM16 timer deadtime register 2"] pub tim16_dtr2: TIM16_DTR2, _reserved14: [u8; 0x04], #[doc = "0x5c - TIM16 input selection register"] pub tim16_tisel: TIM16_TISEL, #[doc = "0x60 - TIM16 alternate function register 1"] pub tim16_af1: TIM16_AF1, #[doc = "0x64 - TIM16 alternate function register 2"] pub tim16_af2: TIM16_AF2, _reserved17: [u8; 0x0374], #[doc = "0x3dc - TIM16 DMA control register"] pub tim16_dcr: TIM16_DCR, #[doc = "0x3e0 - TIM16/TIM17 DMA address for full transfer"] pub tim16_dmar: TIM16_DMAR, } impl RegisterBlock { #[doc = "0x18 - TIM16 capture/compare mode register 1 \\[alternate\\]"] #[inline(always)] pub const fn tim16_ccmr1_output(&self) -> &TIM16_CCMR1_OUTPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x18 - TIM16 capture/compare mode register 1 \\[alternate\\]"] #[inline(always)] pub const fn tim16_ccmr1_input(&self) -> &TIM16_CCMR1_INPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } } #[doc = "TIM16_CR1 (rw) register accessor: TIM16 control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_cr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_cr1`] module"] pub type TIM16_CR1 = crate::Reg<tim16_cr1::TIM16_CR1_SPEC>; #[doc = "TIM16 control register 1"] pub mod tim16_cr1; #[doc = "TIM16_CR2 (rw) register accessor: TIM16 control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_cr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_cr2`] module"] pub type TIM16_CR2 = crate::Reg<tim16_cr2::TIM16_CR2_SPEC>; #[doc = "TIM16 control register 2"] pub mod tim16_cr2; #[doc = "TIM16_DIER (rw) register accessor: TIM16 DMA/interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_dier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_dier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_dier`] module"] pub type TIM16_DIER = crate::Reg<tim16_dier::TIM16_DIER_SPEC>; #[doc = "TIM16 DMA/interrupt enable register"] pub mod tim16_dier; #[doc = "TIM16_SR (rw) register accessor: TIM16 status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_sr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_sr`] module"] pub type TIM16_SR = crate::Reg<tim16_sr::TIM16_SR_SPEC>; #[doc = "TIM16 status register"] pub mod tim16_sr; #[doc = "TIM16_EGR (w) register accessor: TIM16 event generation register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_egr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_egr`] module"] pub type TIM16_EGR = crate::Reg<tim16_egr::TIM16_EGR_SPEC>; #[doc = "TIM16 event generation register"] pub mod tim16_egr; #[doc = "TIM16_CCMR1_Input (rw) register accessor: TIM16 capture/compare mode register 1 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_ccmr1_input::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_ccmr1_input::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_ccmr1_input`] module"] pub type TIM16_CCMR1_INPUT = crate::Reg<tim16_ccmr1_input::TIM16_CCMR1_INPUT_SPEC>; #[doc = "TIM16 capture/compare mode register 1 \\[alternate\\]"] pub mod tim16_ccmr1_input; #[doc = "TIM16_CCMR1_Output (rw) register accessor: TIM16 capture/compare mode register 1 \\[alternate\\]\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_ccmr1_output::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_ccmr1_output::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_ccmr1_output`] module"] pub type TIM16_CCMR1_OUTPUT = crate::Reg<tim16_ccmr1_output::TIM16_CCMR1_OUTPUT_SPEC>; #[doc = "TIM16 capture/compare mode register 1 \\[alternate\\]"] pub mod tim16_ccmr1_output; #[doc = "TIM16_CCER (rw) register accessor: TIM16 capture/compare enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_ccer::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_ccer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_ccer`] module"] pub type TIM16_CCER = crate::Reg<tim16_ccer::TIM16_CCER_SPEC>; #[doc = "TIM16 capture/compare enable register"] pub mod tim16_ccer; #[doc = "TIM16_CNT (rw) register accessor: TIM16 counter\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_cnt::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_cnt::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_cnt`] module"] pub type TIM16_CNT = crate::Reg<tim16_cnt::TIM16_CNT_SPEC>; #[doc = "TIM16 counter"] pub mod tim16_cnt; #[doc = "TIM16_PSC (rw) register accessor: TIM16 prescaler\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_psc::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_psc::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_psc`] module"] pub type TIM16_PSC = crate::Reg<tim16_psc::TIM16_PSC_SPEC>; #[doc = "TIM16 prescaler"] pub mod tim16_psc; #[doc = "TIM16_ARR (rw) register accessor: TIM16 auto-reload register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_arr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_arr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_arr`] module"] pub type TIM16_ARR = crate::Reg<tim16_arr::TIM16_ARR_SPEC>; #[doc = "TIM16 auto-reload register"] pub mod tim16_arr; #[doc = "TIM16_RCR (rw) register accessor: TIM16 repetition counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_rcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_rcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_rcr`] module"] pub type TIM16_RCR = crate::Reg<tim16_rcr::TIM16_RCR_SPEC>; #[doc = "TIM16 repetition counter register"] pub mod tim16_rcr; #[doc = "TIM16_CCR1 (rw) register accessor: TIM16 capture/compare register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_ccr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_ccr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_ccr1`] module"] pub type TIM16_CCR1 = crate::Reg<tim16_ccr1::TIM16_CCR1_SPEC>; #[doc = "TIM16 capture/compare register 1"] pub mod tim16_ccr1; #[doc = "TIM16_BDTR (rw) register accessor: TIM16 break and dead-time register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_bdtr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_bdtr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_bdtr`] module"] pub type TIM16_BDTR = crate::Reg<tim16_bdtr::TIM16_BDTR_SPEC>; #[doc = "TIM16 break and dead-time register"] pub mod tim16_bdtr; #[doc = "TIM16_DTR2 (rw) register accessor: TIM16 timer deadtime register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_dtr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_dtr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_dtr2`] module"] pub type TIM16_DTR2 = crate::Reg<tim16_dtr2::TIM16_DTR2_SPEC>; #[doc = "TIM16 timer deadtime register 2"] pub mod tim16_dtr2; #[doc = "TIM16_TISEL (rw) register accessor: TIM16 input selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_tisel::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_tisel::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_tisel`] module"] pub type TIM16_TISEL = crate::Reg<tim16_tisel::TIM16_TISEL_SPEC>; #[doc = "TIM16 input selection register"] pub mod tim16_tisel; #[doc = "TIM16_AF1 (rw) register accessor: TIM16 alternate function register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_af1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_af1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_af1`] module"] pub type TIM16_AF1 = crate::Reg<tim16_af1::TIM16_AF1_SPEC>; #[doc = "TIM16 alternate function register 1"] pub mod tim16_af1; #[doc = "TIM16_AF2 (rw) register accessor: TIM16 alternate function register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_af2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_af2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_af2`] module"] pub type TIM16_AF2 = crate::Reg<tim16_af2::TIM16_AF2_SPEC>; #[doc = "TIM16 alternate function register 2"] pub mod tim16_af2; #[doc = "TIM16_DCR (rw) register accessor: TIM16 DMA control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_dcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_dcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_dcr`] module"] pub type TIM16_DCR = crate::Reg<tim16_dcr::TIM16_DCR_SPEC>; #[doc = "TIM16 DMA control register"] pub mod tim16_dcr; #[doc = "TIM16_DMAR (rw) register accessor: TIM16/TIM17 DMA address for full transfer\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tim16_dmar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tim16_dmar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tim16_dmar`] module"] pub type TIM16_DMAR = crate::Reg<tim16_dmar::TIM16_DMAR_SPEC>; #[doc = "TIM16/TIM17 DMA address for full transfer"] pub mod tim16_dmar;
use regex::Regex; use std::io::{self, BufRead as _}; type BoxError = Box<dyn std::error::Error>; fn main() -> Result<(), BoxError> { let re = Regex::new(r"^(\d+)-(\d+) ([a-z]): ([a-z]+)$").expect("regex is valid"); let mut valid = 0; for line in io::stdin().lock().lines() { let line = line?; let caps = re.captures(&line).ok_or("invalid line")?; let min: usize = caps.get(1).ok_or("invalid line")?.as_str().parse()?; let max: usize = caps.get(2).ok_or("invalid line")?.as_str().parse()?; let ch = caps .get(3) .ok_or("invalid line")? .as_str() .chars() .next() .ok_or("invalid line")?; let password = caps.get(4).ok_or("invalid line")?.as_str(); let count = password .char_indices() .filter(|(i, c)| c == &ch && (i + 1 == min || i + 1 == max)) .count(); if count == 1 { valid += 1; } } println!("{}", valid); Ok(()) }
#![deny(warnings, missing_docs, missing_debug_implementations)] #![cfg_attr(test, deny(warnings, unreachable_pub))] //! Why multiply, when you can divide. //! I'd like to acknowledge the wonderful work done by the developers of Slab. //! Much of this is a direct derivative of their work. //! //! Build on top of Slab, SuperSlab uses an extent model, where a primary capacity //! is allocated. When full, a new slab of a secondary size is added to the //! SuperSlab. The primary advantage is that allocation doesn't reallocate the //! Slab. //! //! Nearly all of the Slab methods are present here as well. The notable exceptions //! being: //! * reserve() //! * reserve_exact() //! * shrink_to_fit() //! * compact() //! * key_of //! * various flavors of DoubleEndedIterator //! //! # Examples //! //! Basic storing and retrieval. //! //! ``` //! # use super_slab::*; //! let mut slab = SuperSlab::new(); //! //! let hello = slab.insert("hello"); //! let world = slab.insert("world"); //! //! assert_eq!(slab[hello], "hello"); //! assert_eq!(slab[world], "world"); //! //! slab[world] = "earth"; //! assert_eq!(slab[world], "earth"); //! ``` //! //! Sometimes it is useful to be able to associate the key with the value being //! inserted in the slab. This can be done with the `vacant_entry` API as such: //! //! ``` //! # use super_slab::*; //! let mut slab = SuperSlab::new(); //! //! let hello = { //! let entry = slab.vacant_entry(); //! let key = entry.key(); //! //! entry.insert((key, "hello")); //! key //! }; //! //! assert_eq!(hello, slab[hello].0); //! assert_eq!("hello", slab[hello].1); //! ``` //! //! It is generally a good idea to specify the desired capacity of a slab at //! creation time. Note that `SuperSlab` will add a new slab when attempting //! to insert a new value once the existing capacity has been reached. //! //! ``` //! # use super_slab::*; //! let mut slab = SuperSlab::with_capacity(1024); //! //! // ... use the slab //! //! //! slab.insert("the slab is not at capacity yet"); //! ``` //! //! For complete constroll, you can specify the primary capacity, the secondary //! capacity and the capacity of the slab vec. //! //! ``` //! # use super_slab::*; //! //! // allocate a primary capacity of 5000, once that fills, a new slab //! // with capacity 1000 will be allocated. Once 8 have been allocated, //! // the slab vec will need to be reallocated. //! //! let mut slab = SuperSlab::with_capacity_and_extents(5000, 1000, 8); //! //! //! // ... use the slab //! //! //! slab.insert("the slab is not at capacity yet"); //! ``` use std::fmt; use std::iter::IntoIterator; use std::ops; use slab::Slab; /// A SuperSlab is a collection of Slabs, viewed as single Slab. #[derive(Clone)] pub struct SuperSlab<T> { primary_capacity: usize, secondary_capacity: usize, slabs: Vec<Slab<T>>, } impl<T> Default for SuperSlab<T> { fn default() -> Self { Self::new() } } /// A handle to a vacant entry in a `Slab`. /// /// `VacantEntry` allows constructing values with the key that they will be /// assigned to. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let hello = { /// let entry = slab.vacant_entry(); /// let key = entry.key(); /// /// entry.insert((key, "hello")); /// key /// }; /// /// assert_eq!(hello, slab[hello].0); /// assert_eq!("hello", slab[hello].1); /// ``` #[derive(Debug)] pub struct VacantEntry<'a, T: 'a> { key_offset: usize, vacant_entry: slab::VacantEntry<'a, T>, } /// An iterator over the `Slabs` pub struct Iter<'a, T: 'a> { slabs: std::slice::Iter<'a, Slab<T>>, slab_iter: slab::Iter<'a, T>, primary_capacity: usize, secondary_capacity: usize, key_offset: usize, } /// A mutable iterator over the `Slabs` pub struct IterMut<'a, T: 'a> { slabs: std::slice::IterMut<'a, Slab<T>>, slab_iter: slab::IterMut<'a, T>, primary_capacity: usize, secondary_capacity: usize, key_offset: usize, } /// A draining iterator for `Slabs` pub struct Drain<'a, T: 'a> { iter: std::slice::IterMut<'a, Slab<T>>, draining: slab::Drain<'a, T>, } impl<T> SuperSlab<T> { /// Construct a new, empty `SuperSlab`. /// The function allocates 4 extents with each `Slab` having a capacity of 4. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let slab: SuperSlab<i32> = SuperSlab::new(); /// assert_eq!(slab.capacity(), 16); /// ``` pub fn new() -> Self { Self::with_capacity(16) } /// Construct a new, empty `SuperSlab` with the specified capacity. /// /// The returned slab will be able to store exactly `capacity` without /// allocating an extent. If `capacity` is 0, a panic will occur. /// /// It is important to note that this function does not specify the *length* /// of the returned slab, but only the capacity. For an explanation of the /// difference between length and capacity, see [Capacity and /// reallocation](index.html#capacity-and-reallocation). /// /// # Examples /// /// ``` /// # use super_slab::*; /// /// // allocate with a capacity of 10, reserve 4 extents, each with a capacity of 2 /// // this produces two allocation, one for the extents (4 slots) and one for /// // the primary (10 entries). /// /// let mut slab = SuperSlab::with_capacity_and_extents(10, 2, 4); /// /// // The slab contains no values, even though it has capacity for more /// assert_eq!(slab.len(), 0); /// assert_eq!(slab.capacity(), 10); /// /// // These are all done without extending... /// for i in 0..10 { /// slab.insert(i); /// } /// /// // ...but this will make the super slab add an extent /// slab.insert(11); /// assert_eq!(slab.capacity(), 12); /// ``` pub fn with_capacity_and_extents(capacity: usize, secondary: usize, extents: usize) -> Self { if capacity == 0 { panic!("capacity must not be zero") } if secondary == 0 { panic!("secondary must not be zero") } if extents == 0 { panic!("extents must not be zero") } let mut slabs: Vec<Slab<T>> = Vec::with_capacity(extents); slabs.push(Slab::<T>::with_capacity(capacity)); Self { primary_capacity: capacity, secondary_capacity: secondary, slabs, } } /// Simpler instantiation of a slab. This will extents will be 1/4 of capacity or capacity if capacity /// is less than or equal to 100. /// /// /// # Examples /// /// ``` /// # use super_slab::*; /// /// // allocate with a capacity of 10, reserve 4 extents, each with a capacity of 10 /// // this produces two allocation, one for the extents (4 slots) and one for /// // the primary (10 entries). /// /// let mut slab = SuperSlab::with_capacity(10); /// /// // The slab contains no values, even though it has capacity for more /// assert_eq!(slab.len(), 0); /// assert_eq!(slab.capacity(), 10); /// /// // These are all done without extending... /// for i in 0..10 { /// slab.insert(i); /// } /// /// // ...but this will make the super slab add an extent /// slab.insert(11); /// assert_eq!(slab.capacity(), 20); /// ``` pub fn with_capacity(capacity: usize) -> Self { let secondary = if capacity >= 100 { capacity >> 2 } else { capacity }; Self::with_capacity_and_extents(capacity, secondary, 4) } /// Return the number of values the slab can store without reallocating. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let slab: SuperSlab<i32> = SuperSlab::with_capacity(10); /// assert_eq!(slab.capacity(), 10); /// ``` pub fn capacity(&self) -> usize { self.primary_capacity + ((self.slabs.len() - 1) * self.secondary_capacity) } /// reserve is not supported. It seems to have limited value in a SuperSlab. /// reserve_exact is not supported. It seems to have limited value in a SuperSlab. /// shrink_to_fit is not supported. It seems to have limited value in a SuperSlab. /// compact is not supported. It may be supported in the future /// Clear the slabs of all values. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// for i in 0..slab.capacity() { /// slab.insert(i); /// } /// /// slab.clear(); /// assert!(slab.is_empty()); /// ``` pub fn clear(&mut self) { self.slabs.iter_mut().for_each(|s| s.clear()); } /// Return the number of stored values. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// for i in 0..6 { /// slab.insert(i); /// } /// /// assert_eq!(6, slab.len()); /// ``` pub fn len(&self) -> usize { let mut len: usize = 0; self.slabs.iter().for_each(|s| len += s.len()); len } /// Return `true` if there are no values stored in the slab. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// assert!(slab.is_empty()); /// /// slab.insert(1); /// assert!(!slab.is_empty()); /// ``` pub fn is_empty(&self) -> bool { self.slabs.iter().all(|s| s.is_empty()) } /// Return an iterator over the slabs. /// /// This function should generally be **avoided** as it is not efficient. /// Iterators must iterate over every slot in the slab even if it is /// vacant. As such, a slab with a capacity of 1 million but only one /// stored value must still iterate the million slots. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::with_capacity(2); /// /// for i in 0..3 { /// slab.insert(i); /// } /// /// let mut iterator = slab.iter(); /// assert_eq!(iterator.next(), Some((0, &0))); /// assert_eq!(iterator.next(), Some((1, &1))); /// assert_eq!(iterator.next(), Some((2, &2))); /// assert_eq!(iterator.next(), None); /// ``` pub fn iter(&self) -> Iter<T> { let mut slabs = self.slabs.iter(); let slab_iter = slabs.next().unwrap().iter(); Iter { slabs, slab_iter, primary_capacity: self.primary_capacity, secondary_capacity: self.secondary_capacity, key_offset: 0, } } /// Return an iterator that allows modifying each value. /// /// This function should generally be **avoided** as it is not efficient. /// Iterators must iterate over every slot in the slab even if it is /// vacant. As such, a slab with a capacity of 1 million but only one /// stored value must still iterate the million slots. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::with_capacity(2); /// /// let key1 = slab.insert(0); /// let key2 = slab.insert(1); /// /// for (key, val) in slab.iter_mut() { /// if key == key1 { /// *val += 2; /// } /// } /// /// assert_eq!(slab[key1], 2); /// assert_eq!(slab[key2], 1); /// ``` pub fn iter_mut(&mut self) -> IterMut<T> { let mut slabs = self.slabs.iter_mut(); let slab_iter = slabs.next().unwrap().iter_mut(); IterMut { slabs, slab_iter, primary_capacity: self.primary_capacity, secondary_capacity: self.secondary_capacity, key_offset: 0, } } /// Return a reference to the value associated with the given key. /// /// If the given key is not associated with a value, then `None` is /// returned. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// let key = slab.insert("hello"); /// /// assert_eq!(slab.get(key), Some(&"hello")); /// assert_eq!(slab.get(123), None); /// ``` pub fn get(&self, key: usize) -> Option<&T> { let (sub_key, slab) = self.conv_from_key(key); if slab >= self.slabs.len() { return None; } self.slabs[slab].get(sub_key) } /// Return a mutable reference to the value associated with the given key. /// /// If the given key is not associated with a value, then `None` is /// returned. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// let key = slab.insert("hello"); /// /// *slab.get_mut(key).unwrap() = "world"; /// /// assert_eq!(slab[key], "world"); /// assert_eq!(slab.get_mut(123), None); /// ``` pub fn get_mut(&mut self, key: usize) -> Option<&mut T> { let (sub_key, slab) = self.conv_from_key(key); if slab >= self.slabs.len() { return None; } self.slabs[slab].get_mut(sub_key) } /// Return a reference to the value associated with the given key without /// performing bounds checking. /// /// # Safety /// This function should be used with care. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// let key = slab.insert(2); /// /// unsafe { /// assert_eq!(slab.get_unchecked(key), &2); /// } /// ``` pub unsafe fn get_unchecked(&self, key: usize) -> &T { let (sub_key, slab) = self.conv_from_key(key); self.slabs[slab].get_unchecked(sub_key) } /// Return a mutable reference to the value associated with the given key /// without performing bounds checking. /// /// # Safety /// This function should be used with care. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// let key = slab.insert(2); /// /// unsafe { /// let val = slab.get_unchecked_mut(key); /// *val = 13; /// } /// /// assert_eq!(slab[key], 13); /// ``` pub unsafe fn get_unchecked_mut(&mut self, key: usize) -> &mut T { let (sub_key, slab) = self.conv_from_key(key); self.slabs[slab].get_unchecked_mut(sub_key) } /// key_of is not supported. It may be supported in the future. /// Insert a value in the slab, returning key assigned to the value. /// /// The returned key can later be used to retrieve or remove the value using indexed /// lookup and `remove`. Additional capacity is allocated if needed. See /// [Capacity and reallocation](index.html#capacity-and-reallocation). /// /// # Panics /// /// Panics if the number of elements in the vector overflows a `usize`. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// let key = slab.insert("hello"); /// assert_eq!(slab[key], "hello"); /// ``` pub fn insert(&mut self, val: T) -> usize { let primary_capacity = self.primary_capacity; let secondary_capacity = self.secondary_capacity; // find a slab that is not at capacity and insert into it match self.slabs.iter_mut().enumerate().find(|val| val.1.len() != val.1.capacity()) { Some((idx, slab)) => { let k = slab.insert(val); if idx == 0 { k } else { k + primary_capacity + ((idx - 1) * secondary_capacity) } }, None => { let mut slab = Slab::with_capacity(self.secondary_capacity); let res = self.conv_into_key(slab.insert(val), self.slabs.len()); self.slabs.push(slab); res }, } } // convert internal key/slab index to external key #[inline] fn conv_into_key(&self, key: usize, idx: usize) -> usize { let res = if idx == 0 { key } else { key + self.primary_capacity + ((idx - 1) * self.secondary_capacity) }; res } // convert exteneral key to internal key/slab index #[inline] const fn conv_from_key(&self, key: usize) -> (usize, usize) { if key < self.primary_capacity { (key, 0) } else { let k = key - self.primary_capacity; (k % self.secondary_capacity, (k / self.secondary_capacity) + 1) } } /// Return a handle to a vacant entry allowing for further manipulation. /// /// This function is useful when creating values that must contain their /// slab key. The returned `VacantEntry` reserves a slot in the slab and is /// able to query the associated key. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let hello = { /// let entry = slab.vacant_entry(); /// let key = entry.key(); /// /// entry.insert((key, "hello")); /// key /// }; /// /// assert_eq!(hello, slab[hello].0); /// assert_eq!("hello", slab[hello].1); /// ``` pub fn vacant_entry(&mut self) -> VacantEntry<T> { let idx = self.find_or_create_available_slab(); VacantEntry { key_offset: self.conv_into_key(0, idx), vacant_entry: self.slabs[idx].vacant_entry(), } } fn find_or_create_available_slab(&mut self) -> usize { for (idx, slab) in self.slabs.iter_mut().enumerate() { if slab.len() != slab.capacity() { return idx; } } // need to add an extent let slab = Slab::with_capacity(self.secondary_capacity); self.slabs.push(slab); self.slabs.len() - 1 } /// Remove and return the value associated with the given key. /// /// The key is then released and may be associated with future stored /// values. /// /// # Panics /// /// Panics if `key` is not associated with a value. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let hello = slab.insert("hello"); /// /// assert_eq!(slab.remove(hello), "hello"); /// assert!(!slab.contains(hello)); /// ``` pub fn remove(&mut self, key: usize) -> T { let (sub_key, slab) = self.conv_from_key(key); self.slabs[slab].remove(sub_key) } /// Return `true` if a value is associated with the given key. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let hello = slab.insert("hello"); /// assert!(slab.contains(hello)); /// /// slab.remove(hello); /// /// assert!(!slab.contains(hello)); /// ``` pub fn contains(&self, key: usize) -> bool { let (sub_key, slab) = self.conv_from_key(key); self.slabs[slab].contains(sub_key) } /// Retain only the elements specified by the predicate. /// /// In other words, remove all elements `e` such that `f(usize, &mut e)` /// returns false. This method operates in place and preserves the key /// associated with the retained values. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::with_capacity(2); /// /// let k1 = slab.insert(0); /// let k2 = slab.insert(1); /// let k3 = slab.insert(2); /// /// slab.retain(|key, val| key == k1 || *val == 1); /// /// assert!(slab.contains(k1)); /// assert!(slab.contains(k2)); /// assert!(!slab.contains(k3)); /// /// assert_eq!(2, slab.len()); /// ``` pub fn retain<F>(&mut self, mut f: F) where F: FnMut(usize, &mut T) -> bool, { use std::sync::atomic::{AtomicUsize, Ordering}; // wrap the enclosure to deal with keys let offset = AtomicUsize::new(0); let mut wrapper = |key: usize, val: &mut T| -> bool { f(key + offset.load(Ordering::SeqCst), val) }; for slab in self.slabs.iter_mut() { slab.retain(&mut wrapper); let capacity = if offset.load(Ordering::SeqCst) == 0 { self.primary_capacity } else { self.secondary_capacity }; offset.fetch_add(capacity, Ordering::SeqCst); } } /// Return a draining iterator that removes all elements from the slab and /// yields the removed items. /// /// Note: Elements are removed even if the iterator is only partially /// consumed or not consumed at all. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let _ = slab.insert(0); /// let _ = slab.insert(1); /// let _ = slab.insert(2); /// /// { /// let mut drain = slab.drain(); /// /// assert_eq!(Some(0), drain.next()); /// assert_eq!(Some(1), drain.next()); /// assert_eq!(Some(2), drain.next()); /// assert_eq!(None, drain.next()); /// } /// /// assert!(slab.is_empty()); /// ``` pub fn drain(&mut self) -> Drain<T> { let mut iter = self.slabs.iter_mut(); let draining = iter.next().unwrap().drain(); Drain { iter, draining } } } impl<T> ops::Index<usize> for SuperSlab<T> { type Output = T; fn index(&self, key: usize) -> &T { let (sub_key, slab) = self.conv_from_key(key); if slab >= self.slabs.len() { panic!("invalid key") } self.slabs[slab].index(sub_key) } } impl<T> ops::IndexMut<usize> for SuperSlab<T> { fn index_mut(&mut self, key: usize) -> &mut T { let (sub_key, slab) = self.conv_from_key(key); if slab >= self.slabs.len() { panic!("invalid key") } self.slabs[slab].index_mut(sub_key) } } impl<'a, T> IntoIterator for &'a SuperSlab<T> { type Item = (usize, &'a T); type IntoIter = Iter<'a, T>; fn into_iter(self) -> Iter<'a, T> { self.iter() } } impl<'a, T> IntoIterator for &'a mut SuperSlab<T> { type Item = (usize, &'a mut T); type IntoIter = IterMut<'a, T>; fn into_iter(self) -> IterMut<'a, T> { self.iter_mut() } } impl<T> fmt::Debug for SuperSlab<T> where T: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("SuperSlab") .field("len", &self.len()) .field("cap", &self.capacity()) .field("ext", &self.slabs.len()) .finish() } } impl<'a, T: 'a> fmt::Debug for Iter<'a, T> where T: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Iter") .field("slabs", &self.slabs) .field("cap", &self.primary_capacity) .finish() } } impl<'a, T: 'a> fmt::Debug for IterMut<'a, T> where T: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("IterMut") .field("slabs", &self.slabs) .field("cap", &self.primary_capacity) .finish() } } impl<'a, T: 'a> fmt::Debug for Drain<'a, T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Drain").finish() } } // ===== VacantEntry ===== impl<'a, T> VacantEntry<'a, T> { /// Insert a value in the entry, returning a mutable reference to the value. /// /// To get the key associated with the value, use `key` prior to calling /// `insert`. /// /// # Examples /// /// ``` /// # use super_slab::*; /// let mut slab = SuperSlab::new(); /// /// let hello = { /// let entry = slab.vacant_entry(); /// let key = entry.key(); /// /// entry.insert((key, "hello")); /// key /// }; /// /// assert_eq!(hello, slab[hello].0); /// assert_eq!("hello", slab[hello].1); /// ``` pub fn insert(self, val: T) -> &'a mut T { self.vacant_entry.insert(val) } /// Return the key associated with this entry. /// /// A value stored in this entry will be associated with this key. /// /// # Examples /// /// ``` /// # use slab::*; /// let mut slab = Slab::new(); /// /// let hello = { /// let entry = slab.vacant_entry(); /// let key = entry.key(); /// /// entry.insert((key, "hello")); /// key /// }; /// /// assert_eq!(hello, slab[hello].0); /// assert_eq!("hello", slab[hello].1); /// ``` pub fn key(&self) -> usize { self.vacant_entry.key() + self.key_offset } } // ===== Iter ===== impl<'a, T> Iterator for Iter<'a, T> { type Item = (usize, &'a T); fn next(&mut self) -> Option<(usize, &'a T)> { // try advancing within the current slab if let Some((key, val)) = self.slab_iter.next() { return Some((key + self.key_offset, val)); } // advance to the next slab that has entries while let Some(slab) = self.slabs.next() { self.key_offset += if self.key_offset == 0 { self.primary_capacity } else { self.secondary_capacity }; if slab.is_empty() { continue; } self.slab_iter = slab.iter(); if let Some((key, val)) = self.slab_iter.next() { return Some((key + self.key_offset, val)); } } None } } /// DoubleEndedIterator for Iter isn't supported. // ===== IterMut ===== impl<'a, T> Iterator for IterMut<'a, T> { type Item = (usize, &'a mut T); fn next(&mut self) -> Option<(usize, &'a mut T)> { // try advancing within the current slab if let Some((key, val)) = self.slab_iter.next() { return Some((key + self.key_offset, val)); } // advance to the next slab that has entries while let Some(slab) = self.slabs.next() { self.key_offset += if self.key_offset == 0 { self.primary_capacity } else { self.secondary_capacity }; if slab.is_empty() { continue; } self.slab_iter = slab.iter_mut(); if let Some((key, val)) = self.slab_iter.next() { return Some((key + self.key_offset, val)); } } None } } /// DoubleEndedIterator for IterMut isn't supported. // ===== Drain ===== impl<'a, T> Iterator for Drain<'a, T> { type Item = T; fn next(&mut self) -> Option<T> { loop { match self.draining.next() { Some(v) => break Some(v), None => match self.iter.next() { Some(slab) => self.draining = slab.drain(), None => break None, }, } } } } /// DoubleEndedIterator for Drain isn't supported. #[cfg(test)] mod tests { use super::*; #[test] fn iter() { let mut super_slab = SuperSlab::with_capacity(2); for i in 0 .. 6 { super_slab.insert(i); } assert_eq!(super_slab.get(4), Some(&4)); // remove all from 2nd extend and remove last from 3rd super_slab.remove(2); super_slab.remove(3); super_slab.remove(5); let mut iterator = super_slab.iter(); assert_eq!(iterator.next(), Some((0, &0))); assert_eq!(iterator.next(), Some((1, &1))); assert_eq!(iterator.next(), Some((4, &4))); assert_eq!(iterator.next(), None); assert_eq!(iterator.next(), None); } }
use crate::rl::prelude::*; pub trait Environment<A: Action>: Clone { fn reset(&mut self); fn observe(&self) -> State; fn step(&mut self, action: &A) -> Reward; fn is_done(&self) -> bool; fn max_reward(&self) -> Reward; fn action_space(&self) -> usize; fn observation_space(&self) -> usize; }
use std; use std::collections::HashMap; use std::fmt::Display; use std::path::Path; use assembler::lexer::{Lexer, LexerError}; use assembler::parser::{Parser, ParserError}; use assembler::token::{LexerToken, ParserToken}; use opcodes::{AddressingMode, OpCode}; #[derive(Debug, PartialEq)] pub struct Label(u16); #[derive(Debug)] pub struct AssemblerError { pub message: String, } impl AssemblerError { fn unknown_label<S>(label: S) -> AssemblerError where S: Into<String> + std::fmt::Display, { AssemblerError::from(format!("Unknown label: '{}'", label)) } fn relative_offset_too_large<S>(context: S) -> AssemblerError where S: Into<String> + Display, { AssemblerError::from(format!("Branch too far: {}", context)) } } impl From<String> for AssemblerError { fn from(error: String) -> AssemblerError { AssemblerError { message: error } } } impl From<LexerError> for AssemblerError { fn from(error: LexerError) -> AssemblerError { AssemblerError { message: error.message, } } } impl From<ParserError> for AssemblerError { fn from(error: ParserError) -> AssemblerError { AssemblerError { message: error.message, } } } #[derive(Debug)] pub struct CodeSegment { pub address: u16, pub code: Vec<u8>, } pub struct Assembler { symbol_table: HashMap<String, Label>, } impl Assembler { pub fn new() -> Assembler { Assembler { symbol_table: HashMap::new(), } } pub fn assemble_string<S, O>( &mut self, code: S, offset: O, ) -> Result<Vec<CodeSegment>, AssemblerError> where S: Into<String>, O: Into<Option<u16>>, { let code = code.into(); let mut lexer = Lexer::new(); let tokens = lexer.lex_string(code)?; let mut parser = Parser::new(); let tokens = parser.parse(tokens)?; Ok(self.assemble(tokens, offset)?) } pub fn assemble_file<P, O>( &mut self, path: P, offset: O, ) -> Result<Vec<CodeSegment>, AssemblerError> where P: AsRef<Path>, O: Into<Option<u16>>, { let mut lexer = Lexer::new(); let tokens = lexer.lex_file(path)?; let mut parser = Parser::new(); let tokens = parser.parse(tokens)?; Ok(self.assemble(tokens, offset)?) } fn assemble<O>( &mut self, tokens: Vec<ParserToken>, offset: O, ) -> Result<Vec<CodeSegment>, AssemblerError> where O: Into<Option<u16>>, { let mut addr: u16 = offset.into().unwrap_or(0); // First, index the labels so we have addresses for them self.index_labels(&tokens, addr); // Now assemble the code let mut result = Vec::new(); let mut last_addressing_mode = AddressingMode::Absolute; let mut current_segment = CodeSegment { address: addr, code: Vec::new(), }; for token in tokens { // Push an opcode into the output and increment our address // offset if let ParserToken::OpCode(opcode) = token { current_segment.code.push(opcode.code); addr += opcode.length as u16; last_addressing_mode = opcode.mode; } else if let ParserToken::OrgDirective(org_addr) = token { if current_segment.code.len() > 0 { result.push(current_segment); } current_segment = CodeSegment { address: org_addr, code: Vec::new(), }; addr = org_addr; } else if let ParserToken::RawByte(byte) = token { // Push raw bytes directly into the output current_segment.code.push(byte); } else if let ParserToken::RawBytes(bytes) = token { // Push raw bytes directly into output for b in &bytes { current_segment.code.push(*b); } } else if let ParserToken::LabelArg(ref label) = token { // Labels as arguments should be in the symbol table, look // it up and calculate the address direction/location if let Some(&Label(label_addr)) = self.symbol_table.get(label) { if last_addressing_mode == AddressingMode::Absolute { let low_byte = (label_addr & 0xFF) as u8; let high_byte = ((label_addr >> 8) & 0xFF) as u8; current_segment.code.push(low_byte); current_segment.code.push(high_byte); } else { // Its relative.. lets generate a relative branch if addr > label_addr { let distance = (label_addr as i16 - addr as i16) as i8; if distance < -128 || distance > 127 { return Err(AssemblerError::relative_offset_too_large(format!( "Attempted jump to {} at {:04X}", label, addr ))); } current_segment.code.push(distance as u8); } else { let distance = label_addr - addr; if distance > 127 { return Err(AssemblerError::relative_offset_too_large(format!( "Attempted jump to {} at {:04X}", label, addr ))); } current_segment.code.push(distance as u8); } } } else { return Err(AssemblerError::unknown_label(label.clone())); } } } result.push(current_segment); Ok(result) } /// Stores all labels in the code in a Symbol table for lookup later fn index_labels(&mut self, tokens: &[ParserToken], offset: u16) { let mut addr: u16 = offset; let mut last_addressing_mode = AddressingMode::Absolute; for token in tokens { if let &ParserToken::Label(ref label) = token { // Insert a label with the specified memory address // as its offset self.symbol_table.insert(label.clone(), Label(addr)); } else if let &ParserToken::OpCode(opcode) = token { // Add the length of this opcode to our // address offset addr += opcode.length as u16; last_addressing_mode = opcode.mode; } else if let &ParserToken::OrgDirective(new_addr) = token { addr = new_addr } } } } #[cfg(test)] mod tests { use super::*; #[test] fn can_assemble_basic_code() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " LDA $4400 ", None, ) .unwrap(); assert_eq!(&[0xAD, 0x00, 0x44], &segments[0].code[..]); } #[test] fn can_jump_to_label_behind() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " MAIN LDA $4400 PHA JMP MAIN ", None, ) .unwrap(); assert_eq!( &[0xAD, 0x00, 0x44, 0x48, 0x4C, 0x00, 0x00], &segments[0].code[..] ); } #[test] fn can_jump_to_label_with_colon_behind() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " MAIN: LDA $4400 PHA JMP MAIN ", None, ) .unwrap(); assert_eq!( &[0xAD, 0x00, 0x44, 0x48, 0x4C, 0x00, 0x00], &segments[0].code[..] ); } #[test] fn can_jump_to_label_ahead() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " JMP MAIN PHA LDX #15 MAIN LDA $4400 RTS ", None, ) .unwrap(); assert_eq!( &[0x4C, 0x06, 0x00, 0x48, 0xA2, 0x0F, 0xAD, 0x00, 0x44, 0x60], &segments[0].code[..] ); } #[test] fn can_use_variables() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " MAIN_ADDRESS = $0000 MAIN: LDX #15 JMP MAIN_ADDRESS ", None, ) .unwrap(); assert_eq!(&[0xA2, 0x0F, 0x4C, 0x00, 0x00], &segments[0].code[..]); } #[test] fn can_use_variables_assigned_to_variables() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " MAIN_ADDRESS = $0000 MAIN_ADDRESS_INDIRECT_ONE = MAIN_ADDRESS MAIN_ADDRESS_INDIRECT_TWO = MAIN_ADDRESS_INDIRECT_ONE MAIN: LDX #15 JMP MAIN_ADDRESS_INDIRECT_TWO ", None, ) .unwrap(); assert_eq!(&[0xA2, 0x0F, 0x4C, 0x00, 0x00], &segments[0].code[..]); } #[test] fn can_assemble_clearmem_implementation() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " CLRMEM LDA #$00 TAY CLRM1 STA ($FF),Y INY DEX BNE CLRM1 RTS ", None, ) .unwrap(); assert_eq!( &[0xA9, 0x00, 0xA8, 0x91, 0xFF, 0xC8, 0xCA, 0xD0, 0xFA, 0x60], &segments[0].code[..] ); } #[test] fn can_assemble_clearmem_implementation_that_jumps_forward_and_is_lowercase() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " jmp clrmem lda #$00 beq clrm1 nop nop clrm1 sta ($ff),y iny dex bne clrm1 rts clrmem lda #$00 tay jmp clrm1 ", None, ) .unwrap(); assert_eq!( &[ 0x4C, 0x10, 0x00, 0xA9, 0x00, 0xF0, 0x02, 0xEA, 0xEA, 0x91, 0xFF, 0xC8, 0xCA, 0xD0, 0xFA, 0x60, 0xA9, 0x00, 0xA8, 0x4C, 0x09, 0x00 ], &segments[0].code[..] ); } #[test] fn can_assemble_clearmem_implementation_that_jumps_forward() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " JMP CLRMEM LDA #$00 BEQ CLRM1 NOP NOP BRK CLRM1 STA ($FF),Y INY DEX BNE CLRM1 RTS CLRMEM LDA #$00 TAY JMP CLRM1 ", None, ) .unwrap(); assert_eq!( &[ 0x4C, 0x11, 0x00, 0xA9, 0x00, 0xF0, 0x03, 0xEA, 0xEA, 0x00, 0x91, 0xFF, 0xC8, 0xCA, 0xD0, 0xFA, 0x60, 0xA9, 0x00, 0xA8, 0x4C, 0x0A, 0x00 ], &segments[0].code[..] ); } #[test] fn can_use_variables_for_indirect_addressing() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " MAIN_ADDRESS = $0000 MAIN: LDX #15 LDA (MAIN_ADDRESS),Y ", None, ) .unwrap(); assert_eq!(&[0xA2, 0x0F, 0xB1, 0x00, 0x00], &segments[0].code[..]); } #[test] fn can_assign_code_segments_to_different_memory_addresses() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " .ORG $C000 LDA #$FF STA $2000 .ORG $100 LDA #$AA STA $2001 ", None, ) .unwrap(); assert_eq!(0xC000, segments[0].address); assert_eq!(0x0100, segments[1].address); } #[test] fn can_jump_between_code_segments() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " .ORG $C000 JMP CALLBACK .ORG $2000 LDA #$AA STA $2001 CALLBACK LDX #$0A ", None, ) .unwrap(); assert_eq!(0xC000, segments[0].address); assert_eq!(0x2000, segments[1].address); assert_eq!(0x05, segments[0].code[0x01]); assert_eq!(0x20, segments[0].code[0x02]); } #[test] fn can_dump_raw_bytes() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " .ORG $C000 .BYTE #$40, #10, #$0A ", None, ) .unwrap(); assert_eq!(&[64, 10, 10], &segments[0].code[..]); } #[test] fn can_dump_single_raw_byte() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " .ORG $C000 .BYTE #$FF ", None, ) .unwrap(); assert_eq!(&[255], &segments[0].code[..]); } #[test] fn can_dump_bytes_with_other_code() { let mut assembler = Assembler::new(); let segments = assembler .assemble_string( " .ORG $C000 JMP CALLBACK .BYTE #$0A .ORG $2000 LDA #$AA STA $2001 .BYTE #$FE, #$CB CALLBACK LDX #$0A ", None, ) .unwrap(); assert_eq!(0x0A, segments[0].code[3]); assert_eq!(&[0xFE, 0xCB], &segments[1].code[5..7]); assert_eq!(0xC000, segments[0].address); assert_eq!(0x2000, segments[1].address); assert_eq!(0x05, segments[0].code[0x01]); assert_eq!(0x20, segments[0].code[0x02]); } }
use async_echo::{echo_server, EcResult}; use async_std::io::{stdin, BufRead, BufReader}; use async_std::stream::Stream; use async_std::task; async fn wait_exitus() -> EcResult<()> { let mut lines = BufReader::new(stdin()).lines(); while let Some(line) = lines.next().await { if line? == "exit" { break; } } Ok(()) } fn main() { task::spawn(async { if let Err(e) = echo_server("127.0.0.1:9102").await { eprintln!("{}", e); } }); let _ = task::block_on(wait_exitus()); }
pub mod key; pub mod oauth2; pub mod reset; pub mod token; use crate::{ core, server::{ route_json_config, route_response_json, validate, Data, Error, FromJsonValue, PwnedPasswordsError, }, }; use actix_web::{ http::{header, StatusCode}, middleware::identity::Identity, web, HttpResponse, }; use futures::{future, Future}; use sha1::{Digest, Sha1}; use validator::Validate; #[derive(Debug, Serialize, Deserialize)] pub struct PasswordMeta { pub password_strength: Option<u8>, pub password_pwned: Option<bool>, } impl Default for PasswordMeta { fn default() -> Self { PasswordMeta { password_strength: None, password_pwned: None, } } } /// Returns password strength and pwned checks. pub fn password_meta( data: &Data, password: Option<&str>, ) -> impl Future<Item = PasswordMeta, Error = Error> { match password { Some(password) => { let password_strength = password_meta_strength(password).then(|r| match r { Ok(entropy) => future::ok(Some(entropy.score)), Err(err) => { warn!("{}", err); future::ok(None) } }); let password_pwned = password_meta_pwned(data, password).then(|r| match r { Ok(password_pwned) => future::ok(Some(password_pwned)), Err(err) => { warn!("{}", err); future::ok(None) } }); future::Either::A(password_strength.join(password_pwned).map( |(password_strength, password_pwned)| PasswordMeta { password_strength, password_pwned, }, )) } None => future::Either::B(future::ok(PasswordMeta::default())), } } /// Returns password strength test performed by `zxcvbn`. /// <https://github.com/shssoichiro/zxcvbn-rs> fn password_meta_strength(password: &str) -> impl Future<Item = zxcvbn::Entropy, Error = Error> { future::result(zxcvbn::zxcvbn(password, &[]).map_err(Error::Zxcvbn)) } /// Returns true if password is present in `Pwned Passwords` index, else false. /// <https://haveibeenpwned.com/Passwords> fn password_meta_pwned(data: &Data, password: &str) -> impl Future<Item = bool, Error = Error> { let password_pwned_enabled = data.configuration().password_pwned_enabled(); let user_agent = data.configuration().user_agent(); if password_pwned_enabled { // Make request to API using first 5 characters of SHA1 password hash. let mut hash = Sha1::new(); hash.input(password); let hash = format!("{:X}", hash.result()); let client = actix_web::client::Client::new(); let url = format!("https://api.pwnedpasswords.com/range/{:.5}", hash); future::Either::A( client .get(url) .header(header::USER_AGENT, user_agent) .send() .map_err(|_err| Error::PwnedPasswords(PwnedPasswordsError::ActixClientSendRequest)) // Receive OK response and return body as string. .and_then(|response| { let status = response.status(); match status { StatusCode::OK => future::ok(response), _ => future::err(Error::PwnedPasswords(PwnedPasswordsError::StatusCode( status, ))), } }) .and_then(|mut response| { response .body() .map_err(|_err| Error::PwnedPasswords(PwnedPasswordsError::ActixPayload)) .and_then(|b| { String::from_utf8(b.to_vec()).map_err(|err| { Error::PwnedPasswords(PwnedPasswordsError::FromUtf8(err)) }) }) }) // Compare suffix of hash to lines to determine if password is pwned. .and_then(move |text| { for line in text.lines() { if hash[5..] == line[..35] { return Ok(true); } } Ok(false) }), ) } else { future::Either::B(future::err(Error::PwnedPasswords( PwnedPasswordsError::Disabled, ))) } } #[derive(Debug, Serialize, Deserialize, Validate)] #[serde(deny_unknown_fields)] pub struct LoginBody { #[validate(email)] pub email: String, #[validate(custom = "validate::password")] pub password: String, } impl validate::FromJsonValue<LoginBody> for LoginBody {} #[derive(Debug, Serialize, Deserialize)] pub struct LoginResponse { pub meta: PasswordMeta, pub data: core::UserToken, } fn login_handler( data: web::Data<Data>, id: Identity, body: web::Json<serde_json::Value>, ) -> impl Future<Item = HttpResponse, Error = actix_web::Error> { let id = id.identity(); LoginBody::from_value(body.into_inner()) .and_then(|body| { web::block(move || { let user_token = login_inner(data.get_ref(), id, &body)?; Ok((data, body, user_token)) }) .map_err(Into::into) }) .and_then(|(data, body, user_token)| { let password_meta = password_meta(data.get_ref(), Some(&body.password)); let user_token = future::ok(user_token); password_meta.join(user_token) }) .map(|(meta, user_token)| LoginResponse { meta, data: user_token, }) .then(route_response_json) } fn login_inner( data: &Data, id: Option<String>, body: &LoginBody, ) -> Result<core::UserToken, Error> { core::key::authenticate_service(data.driver(), id) .and_then(|service| { core::auth::login( data.driver(), &service, &body.email, &body.password, data.configuration().token_exp(), ) }) .map_err(Into::into) } /// Version 1 API authentication scope. pub fn api_v1_scope() -> actix_web::Scope { web::scope("/auth") .service( web::resource("/login") .data(route_json_config()) .route(web::post().to_async(login_handler)), ) .service(oauth2::api_v1_scope()) .service(key::api_v1_scope()) .service(reset::api_v1_scope()) .service(token::api_v1_scope()) } #[derive(Debug, Serialize, Deserialize, Validate)] #[serde(deny_unknown_fields)] pub struct TokenBody { #[validate(custom = "validate::token")] pub token: String, } impl validate::FromJsonValue<TokenBody> for TokenBody {} #[derive(Debug, Serialize, Deserialize)] pub struct TokenResponse { pub data: core::UserToken, } #[derive(Debug, Serialize, Deserialize, Validate)] #[serde(deny_unknown_fields)] pub struct KeyBody { #[validate(custom = "validate::key")] pub key: String, } impl validate::FromJsonValue<KeyBody> for KeyBody {} #[derive(Debug, Serialize, Deserialize)] pub struct KeyResponse { pub data: core::UserKey, }
use std::time::{Duration, SystemTime}; /// Basic metadata for a file. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct Metadata { accessed: Duration, created: Duration, modified: Duration, } impl Metadata { /// Create a new [`Metadata`] using the number of seconds since the /// [`SystemTime::UNIX_EPOCH`]. pub const fn new(accessed: Duration, created: Duration, modified: Duration) -> Self { Metadata { accessed, created, modified, } } /// Get the time this file was last accessed. /// /// See also: [`std::fs::Metadata::accessed()`]. pub fn accessed(&self) -> SystemTime { SystemTime::UNIX_EPOCH + self.accessed } /// Get the time this file was created. /// /// See also: [`std::fs::Metadata::created()`]. pub fn created(&self) -> SystemTime { SystemTime::UNIX_EPOCH + self.created } /// Get the time this file was last modified. /// /// See also: [`std::fs::Metadata::modified()`]. pub fn modified(&self) -> SystemTime { SystemTime::UNIX_EPOCH + self.modified } }
// Copyright 2021 MaidSafe.net limited. // // This SAFE Network Software is licensed to you under The General Public License (GPL), version 3. // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. Please review the Licences for the specific language governing // permissions and limitations relating to use of the SAFE Network Software. mod block; mod branch; mod deserialized; pub mod error; #[cfg(test)] pub(crate) mod tests; use itertools::Itertools; use serde::{Deserialize, Serialize}; use std::{ cmp::Ordering, collections::HashSet, fmt::{self, Debug, Formatter}, iter, mem, }; use self::{block::Block, branch::Branch, deserialized::Deserialized, error::Error}; /// Chain of BLS keys where every key is proven (signed) by its parent key, except the /// first one. /// /// # CRDT /// /// The operations that mutate the chain ([`insert`](Self::insert) and [`merge`](Self::merge)) are /// commutative, associative and idempotent. This means the chain is a /// [CRDT](https://en.wikipedia.org/wiki/Conflict-free_replicated_data_type). /// /// # Forks /// /// It's possible to insert multiple keys that all have the same parent key. This is called a /// "fork". The chain implements automatic fork resolution which means that even in the presence of /// forks the chain presents the blocks in a well-defined unique and deterministic order. /// /// # Block order /// /// Block are ordered primarily according to their parent-child relation (parents always precede /// children) and forks are resolved by additionally ordering the sibling blocks according to the /// `Ord` relation of their public key. That is, "lower" keys precede "higher" keys. #[derive(Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[serde(try_from = "Deserialized")] pub struct SecuredLinkedList { root: bls::PublicKey, tree: Vec<Block>, } #[allow(clippy::len_without_is_empty)] impl SecuredLinkedList { /// Creates a new chain consisting of only one block. pub fn new(root: bls::PublicKey) -> Self { Self { root, tree: Vec::new(), } } /// Insert new key into the chain. `parent_key` must exists in the chain and must validate /// `signature`, otherwise error is returned. pub fn insert( &mut self, parent_key: &bls::PublicKey, key: bls::PublicKey, signature: bls::Signature, ) -> Result<(), Error> { let parent_index = self.index_of(parent_key).ok_or(Error::KeyNotFound)?; let block = Block { key, signature, parent_index, }; if block.verify(parent_key) { let _ = self.insert_block(block); Ok(()) } else { Err(Error::FailedSignature) } } /// Merges two chains into one. /// /// This succeeds only if the root key of one of the chain is present in the other one. /// Otherwise it returns `Error::InvalidOperation` pub fn join(&mut self, mut other: Self) -> Result<(), Error> { let root_index = if let Some(index) = self.index_of(other.root_key()) { index } else if let Some(index) = other.index_of(self.root_key()) { mem::swap(self, &mut other); index } else { return Err(Error::InvalidOperation); }; let mut reindex_map = vec![0; other.len()]; reindex_map[0] = root_index; for (other_index, mut other_block) in other .tree .into_iter() .enumerate() .map(|(index, block)| (index + 1, block)) { other_block.parent_index = reindex_map[other_block.parent_index]; reindex_map[other_index] = self.insert_block(other_block); } Ok(()) } /// Creates a sub-chain from given `from` and `to` keys. /// Returns `Error::KeyNotFound` if the given keys are not present in the chain. pub fn get_proof_chain( &self, from_key: &bls::PublicKey, to_key: &bls::PublicKey, ) -> Result<Self, Error> { let from_index = self.index_of(from_key).ok_or(Error::KeyNotFound)?; let mut chain = Self::new(if from_index == 0 { self.root } else { self.tree[from_index - 1].key }); let mut curr_index = self.index_of(to_key).ok_or(Error::KeyNotFound)?; while curr_index != 0 && curr_index != from_index { let block = &self.tree[curr_index - 1]; chain.tree.insert( 0, Block { key: block.key, signature: block.signature.clone(), parent_index: 0, // we'll update it afterwards }, ); curr_index = block.parent_index; } if curr_index != from_index { // the 'from_key' is not an ancestor in any chain containing 'to_key' Err(Error::SubChainNotFound) } else { for (i, elem) in chain.tree.iter_mut().enumerate() { elem.parent_index = i; } Ok(chain) } } /// Creates a minimal sub-chain of `self` that contains all `required_keys`. /// Returns `Error::KeyNotFound` if some of `required_keys` is not present in `self`. /// /// Note: "minimal" means it contains the fewest number of blocks of all such sub-chains. pub fn minimize<'a, I>(&self, required_keys: I) -> Result<Self, Error> where I: IntoIterator<Item = &'a bls::PublicKey>, { // Note: the returned chain is not always strictly minimal. Consider this chain: // // 0->1->3->4 // | // +->2 // // Then calling `minimize([1, 3])` currently returns // // 1->3 // | // +->2 // // Even though the truly minimal chain containing 1 and 3 is just // // 1->3 // // This is because 2 lies between 1 and 3 in the underlying `tree` vector and so is // currently included. // // TODO: make this function return the truly minimal chain in all cases. let mut min_index = self.len() - 1; let mut max_index = 0; for key in required_keys { let index = self.index_of(key).ok_or(Error::KeyNotFound)?; min_index = min_index.min(index); max_index = max_index.max(index); } // To account for forks, we also need to include the closest common ancestors of all the // required keys. This is to maintain the invariant that for every key in the chain that is // not the root its parent key is also in the chain. min_index = self.closest_common_ancestor(min_index, max_index); let mut chain = Self::new(if min_index == 0 { self.root } else { self.tree[min_index - 1].key }); for index in min_index..max_index { let block = &self.tree[index]; chain.tree.push(Block { key: block.key, signature: block.signature.clone(), parent_index: block.parent_index - min_index, }) } Ok(chain) } /// Returns a sub-chain of `self` truncated to the last `count` keys. /// NOTE: a chain must have at least 1 block, so if `count` is 0 it is treated the same as if /// it was 1. pub fn truncate(&self, count: usize) -> Self { let count = count.max(1); let mut tree: Vec<_> = self.branch(self.tree.len()).take(count).cloned().collect(); let root = if tree.len() >= count { tree.pop().map(|block| block.key).unwrap_or(self.root) } else { self.root }; tree.reverse(); // Fix the parent indices. for (index, block) in tree.iter_mut().enumerate() { block.parent_index = index; } Self { root, tree } } /// Returns the smallest super-chain of `self` that would be trusted by a peer that trust /// `trusted_key`. Ensures that the last key of the resuling chain is the same as the last key /// of `self`. /// /// Returns `Error::KeyNotFound` if any of `trusted_key`, `self.root_key()` or `self.last_key()` /// is not present in `super_chain`. /// /// Returns `Error::InvalidOperation` if `trusted_key` is not reachable from `self.last_key()`. pub fn extend(&self, trusted_key: &bls::PublicKey, super_chain: &Self) -> Result<Self, Error> { let trusted_key_index = super_chain .index_of(trusted_key) .ok_or(Error::KeyNotFound)?; let last_key_index = super_chain .index_of(self.last_key()) .ok_or(Error::KeyNotFound)?; if !super_chain.has_key(self.root_key()) { return Err(Error::KeyNotFound); } if super_chain.is_ancestor(trusted_key_index, last_key_index) { super_chain.minimize(vec![trusted_key, self.last_key()]) } else { Err(Error::InvalidOperation) } } /// Iterator over all the keys in the chain in order. pub fn keys(&self) -> impl DoubleEndedIterator<Item = &bls::PublicKey> { iter::once(&self.root).chain(self.tree.iter().map(|block| &block.key)) } /// Returns the root key of this chain. This is the first key in the chain and is the only key /// that doesn't have a parent key. pub fn root_key(&self) -> &bls::PublicKey { &self.root } /// Returns the last key of this chain. pub fn last_key(&self) -> &bls::PublicKey { self.tree .last() .map(|block| &block.key) .unwrap_or(&self.root) } /// Returns the parent key of the last key or the root key if this chain has only one key. pub fn prev_key(&self) -> &bls::PublicKey { self.branch(self.tree.len()) .nth(1) .map(|block| &block.key) .unwrap_or(&self.root) } /// Returns whether `key` is present in this chain. pub fn has_key(&self, key: &bls::PublicKey) -> bool { self.keys().any(|existing_key| existing_key == key) } /// Verify every BLS key in this chain is proven (signed) by its parent key, /// except the first one. pub fn self_verify(&self) -> bool { self.tree.iter().all(|block| { let parent_key = if block.parent_index > 0 { &self.tree[block.parent_index - 1].key } else { &self.root }; block.verify(parent_key) }) } /// Given a collection of keys that are already trusted, returns whether this chain is also /// trusted. A chain is considered trusted only if at least one of the `trusted_keys` is on its /// main branch. /// /// # Explanation /// /// Consider this chain that contains fork: /// /// ```ascii-art /// A->B->C /// | /// +->D /// ``` /// /// Now if the only trusted key is `D`, then there is no way to prove the chain is trusted, /// because this chain would be indistinguishable in terms of trust from any other chain with /// the same general "shape", say: /// /// ```ascii-art /// W->X->Y->Z /// | /// +->D /// ``` /// /// So an adversary is easily able to forge any such chain. /// /// When the trusted key is on the main branch, on the other hand: /// /// ```ascii-art /// D->E->F /// | /// +->G /// ``` /// /// Then such chain is impossible to forge because the adversary would have to have access to /// the secret key corresponding to `D` in order to validly sign `E`. Thus such chain can be /// safely considered trusted. pub fn check_trust<'a, I>(&self, trusted_keys: I) -> bool where I: IntoIterator<Item = &'a bls::PublicKey>, { let trusted_keys: HashSet<_> = trusted_keys.into_iter().collect(); self.branch(self.tree.len()) .map(|block| &block.key) .chain(iter::once(&self.root)) .any(|key| trusted_keys.contains(key)) } /// Compare the two keys by their position in the chain. The key that is higher (closer to the /// last key) is considered `Greater`. If exactly one of the keys is not in the chain, the other /// one is implicitly considered `Greater`. If none are in the chain, they are considered /// `Equal`. pub fn cmp_by_position(&self, lhs: &bls::PublicKey, rhs: &bls::PublicKey) -> Ordering { match (self.index_of(lhs), self.index_of(rhs)) { (Some(lhs), Some(rhs)) => lhs.cmp(&rhs), (Some(_), None) => Ordering::Greater, (None, Some(_)) => Ordering::Less, (None, None) => Ordering::Equal, } } /// Returns the number of blocks in the chain. This is always >= 1. pub fn len(&self) -> usize { 1 + self.tree.len() } /// Returns the number of block on the main branch of the chain - that is - the ones reachable /// from the last block. /// /// NOTE: this is a `O(n)` operation. pub fn main_branch_len(&self) -> usize { self.branch(self.tree.len()).count() + 1 } fn insert_block(&mut self, new_block: Block) -> usize { // Find the index into `self.tree` to insert the new block at so that the block order as // described in the `SecuredLinkedList` doc comment is maintained. let same_block = self .tree .iter() .enumerate() .skip(new_block.parent_index) .find(|(_, block)| { block.parent_index == new_block.parent_index && block.key == new_block.key }) .map(|(index, _)| index); // If the key already exists in the chain, do nothing but still return success to make the // `insert` operation idempotent. let insert_at = match same_block { Some(index) => return index + 1, None => self .tree .iter() .enumerate() .skip(new_block.parent_index) .find(|(_, block)| { block.parent_index != new_block.parent_index || block.key >= new_block.key }) .map(|(index, _)| index) .unwrap_or(self.tree.len()), }; self.tree.insert(insert_at, new_block); // Adjust the parent indices of the keys whose parents are after the inserted key. for block in &mut self.tree[insert_at + 1..] { if block.parent_index > insert_at { block.parent_index += 1; } } insert_at + 1 } /// Returns the index of the given key. Returns `None` if not present. pub fn index_of(&self, key: &bls::PublicKey) -> Option<usize> { self.keys() .rev() .position(|existing_key| existing_key == key) .map(|rev_position| self.len() - rev_position - 1) } fn parent_index_at(&self, index: usize) -> Option<usize> { if index == 0 { None } else { self.tree.get(index - 1).map(|block| block.parent_index) } } // Is the key at `lhs` an ancestor of the key at `rhs`? fn is_ancestor(&self, lhs: usize, rhs: usize) -> bool { let mut index = rhs; loop { if index == lhs { return true; } if index < lhs { return false; } if let Some(parent_index) = self.parent_index_at(index) { index = parent_index; } else { return false; } } } // Returns the index of the closest common ancestor of the keys in the *closed* interval // [min_index, max_index]. fn closest_common_ancestor(&self, mut min_index: usize, mut max_index: usize) -> usize { loop { if max_index == 0 || min_index == 0 { return 0; } if max_index <= min_index { return min_index; } if let Some(parent_index) = self.parent_index_at(max_index) { min_index = min_index.min(parent_index); } else { return 0; } max_index -= 1; } } // Iterator over the blocks on the branch that ends at `index` in reverse order. // Does not include the root block. fn branch(&self, index: usize) -> Branch { Branch { chain: self, index } } } impl Debug for SecuredLinkedList { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{:?}", self.keys().format("->")) } }
#![feature(test)] #[allow(dead_code)] const KB: usize = 1024; #[allow(dead_code)] const MB: usize = KB * KB; #[allow(dead_code)] const N: usize = 2 * MB; #[cfg(test)] mod tests { use super::*; extern crate test; use test::Bencher; #[bench] fn bench_calc_with_15det_array(b: &mut Bencher) { let det = 15; let data = vec![0; N]; b.iter(|| { let mut res = false; for i in 0..MB { res |= data[i] < data[i + det]; } res }); } #[bench] fn bench_calc_with_16det_array(b: &mut Bencher) { let det = 16; let data = vec![0; N]; b.iter(|| { let mut res = false; for i in 0..MB { res |= data[i] < data[i + det]; } res }); } #[bench] fn bench_calc_with_17det_array(b: &mut Bencher) { let det = 17; let data = vec![0; N]; b.iter(|| { let mut res = false; for i in 0..MB { res |= data[i] < data[i + det]; } res }); } }
#[doc = "Reader of register WAKEUP_CONFIG_EXTD"] pub type R = crate::R<u32, super::WAKEUP_CONFIG_EXTD>; #[doc = "Writer for register WAKEUP_CONFIG_EXTD"] pub type W = crate::W<u32, super::WAKEUP_CONFIG_EXTD>; #[doc = "Register WAKEUP_CONFIG_EXTD `reset()`'s with value 0"] impl crate::ResetValue for super::WAKEUP_CONFIG_EXTD { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DSM_LF_OFFSET`"] pub type DSM_LF_OFFSET_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DSM_LF_OFFSET`"] pub struct DSM_LF_OFFSET_W<'a> { w: &'a mut W, } impl<'a> DSM_LF_OFFSET_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 & !0x1f) | ((value as u32) & 0x1f); self.w } } impl R { #[doc = "Bits 0:4 - Number of 'LF slots' before the wake up instant before which the hardware needs to exit from deep sleep mode. The LF slot is of 62.5us period. This is a onetime configuration field, which is used every time hardware does an auto-wakeup before the next wakeup instant. This is in addition to the LF slots calculated by HW window widening logic."] #[inline(always)] pub fn dsm_lf_offset(&self) -> DSM_LF_OFFSET_R { DSM_LF_OFFSET_R::new((self.bits & 0x1f) as u8) } } impl W { #[doc = "Bits 0:4 - Number of 'LF slots' before the wake up instant before which the hardware needs to exit from deep sleep mode. The LF slot is of 62.5us period. This is a onetime configuration field, which is used every time hardware does an auto-wakeup before the next wakeup instant. This is in addition to the LF slots calculated by HW window widening logic."] #[inline(always)] pub fn dsm_lf_offset(&mut self) -> DSM_LF_OFFSET_W { DSM_LF_OFFSET_W { w: self } } }
use crate::data::component::{Component, PortType, StateChange}; use crate::data::subnet::SubnetState; use std::collections::HashMap; use std::cell::Cell; use crate::{map, port_or_default}; #[derive(Debug)] pub(crate) struct Constant { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for Constant { fn ports(&self) -> usize { 1 } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0 => Some(PortType::Output), _ => None, } } fn evaluate(&self, _: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let val = match self.state.get() { true => SubnetState::On, false => SubnetState::Off, }; map!(0 => val) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => SubnetState::On, false => SubnetState::Off, } } } impl Constant { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct Button { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for Button { fn ports(&self) -> usize { 1 } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0 => Some(PortType::Output), _ => None, } } fn evaluate(&self, _: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let val = match self.state.get() { true => SubnetState::On, false => SubnetState::Off, }; map!(0 => val) } fn pressed(&self) -> SubnetState{ self.state.set(true); return SubnetState::On } fn released(&self) -> SubnetState { self.state.set(false); return SubnetState::Off } } impl Button { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct Switch { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for Switch { fn ports(&self) -> usize { 1 } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0 => Some(PortType::Output), _ => None, } } fn evaluate(&self, _: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let val = match self.state.get() { true => SubnetState::On, false => SubnetState::Off, }; map!(0 => val) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => { return SubnetState::On } false => { self.state.set(true); return SubnetState::Off } } } } impl Switch { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct DFlipFlop { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for DFlipFlop { fn ports(&self) -> usize { 5 // 0 is D, 1 is clock, 2 is disable, 3 is Q, 4 is Q inverse } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0..=2 => Some(PortType::Input), 3 | 4 => Some(PortType::Output), _ => None, } } fn evaluate(&self, data: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let d = port_or_default!(data, 0); let clock = data.get(&1).map(|e| e.rising()).unwrap_or(false); let disable = port_or_default!(data, 2); if clock && disable != SubnetState::On { if d == SubnetState::On { self.state.set(true); } else if d == SubnetState::Off { self.state.set(false); } } let vals = match self.state.get() { true => (SubnetState::On, SubnetState::Off), false => (SubnetState::Off, SubnetState::On), }; map!( 3 => vals.0, 4 => vals.1 ) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => { return SubnetState::On } false => { self.state.set(true); return SubnetState::Off } } } } impl DFlipFlop { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct TFlipFlop { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for TFlipFlop { fn ports(&self) -> usize { 5 // 0 is T, 1 is clock, 2 is disable, 3 is Q, 4 is Q inverse } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0..=2 => Some(PortType::Input), 3 | 4 => Some(PortType::Output), _ => None, } } fn evaluate(&self, data: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let t = port_or_default!(data, 0); let clock = data.get(&1).map(|e| e.rising()).unwrap_or(false); let disable = port_or_default!(data, 2); if clock && disable != SubnetState::On { if t.truthy() { self.state.set(!self.state.get()); } } let vals = match self.state.get() { true => (SubnetState::On, SubnetState::Off), false => (SubnetState::Off, SubnetState::On), }; map!( 3 => vals.0, 4 => vals.1 ) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => { return SubnetState::On } false => { self.state.set(true); return SubnetState::Off } } } } impl TFlipFlop { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct JKFlipFlop { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for JKFlipFlop { fn ports(&self) -> usize { 6 // 0 is J, 1 is K, 2 is clock, 3 is disable, 4 is Q, 5 is Q inverse } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0..=3 => Some(PortType::Input), 4 | 5 => Some(PortType::Output), _ => None, } } fn evaluate(&self, data: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let j = port_or_default!(data, 0); let k = port_or_default!(data, 1); let clock = data.get(&2).map(|e| e.rising()).unwrap_or(false); let disable = port_or_default!(data, 3); if clock && disable != SubnetState::On { if j.truthy() && k.falsy() { self.state.set(true); } else if j.falsy() && k.truthy() { self.state.set(false); } else if j.truthy() && k.truthy() { self.state.set(!self.state.get()); } } let vals = match self.state.get() { true => (SubnetState::On, SubnetState::Off), false => (SubnetState::Off, SubnetState::On), }; map!( 4 => vals.0, 5 => vals.1 ) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => { return SubnetState::On } false => { self.state.set(true); return SubnetState::Off } } } } impl JKFlipFlop { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct SRFlipFlop { #[cfg(not(test))] state: Cell<bool>, #[cfg(test)] pub state: Cell<bool>, } impl Component for SRFlipFlop { fn ports(&self) -> usize { 6 // 0 is S, 1 is R, 2 is clock, 3 is disable, 4 is Q, 5 is Q inverse } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0..=3 => Some(PortType::Input), 4 | 5 => Some(PortType::Output), _ => None, } } fn evaluate(&self, data: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let s = port_or_default!(data, 0); let r = port_or_default!(data, 1); let clock = data.get(&2).map(|e| e.rising()).unwrap_or(false); let disable = port_or_default!(data, 3); if clock && disable != SubnetState::On { if s.truthy() && r.falsy() { self.state.set(true); } else if s.falsy() && r.truthy() { self.state.set(false); } } let vals = match self.state.get() { true => (SubnetState::On, SubnetState::Off), false => (SubnetState::Off, SubnetState::On), }; map!( 4 => vals.0, 5 => vals.1 ) } fn pressed(&self) -> SubnetState{ match self.state.get(){ true => { self.state.set(false); return SubnetState::Off } false => { self.state.set(true); return SubnetState::On } } } fn released(&self) -> SubnetState { match self.state.get(){ true => { return SubnetState::On } false => { self.state.set(true); return SubnetState::Off } } } } impl SRFlipFlop { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } } #[derive(Debug)] pub(crate) struct Clock { state: Cell<bool>, } impl Component for Clock { fn ports(&self) -> usize { 1 } fn port_type(&self, port: usize) -> Option<PortType> { match port { 0 => Some(PortType::Output), _ => None, } } fn evaluate(&self, _: HashMap<usize, StateChange>) -> HashMap<usize, SubnetState> { let val = match self.state.get() { true => SubnetState::On, false => SubnetState::Off }; self.state.set(!self.state.get()); map!(0 => val) } } impl Clock { pub(crate) fn new() -> Self { Self { state: Cell::new(false) } } }
#[macro_use] extern crate log; #[macro_use] extern crate serde_derive; mod button; mod database; mod event; mod moisture; mod valve; mod weather; pub mod controller; pub mod pirrigator; pub mod settings;
use anyhow::Result; // use pay_tx::run; use pay_tx::run_stream; #[tokio::main] async fn main() -> Result<()> { env_logger::init(); run_stream().await?; // run()?; Ok(()) }
use glium::Display; use crate::draw::{Vertex, ObjDef, load_data_to_gpu}; use crate::quadoctree::CollisionObj; pub fn generate_cube_vertices(pre_pos: &[f32; 3], post_pos: &[f32; 3], dim: &[f32; 3], yaw: f32) -> [Vertex; 24] { let gen_pos = |proto: [f32; 3]| { let before_yaw = [proto[0] * dim[0] + pre_pos[0], proto[1] * dim[1] + pre_pos[1], proto[2] * dim[2] + pre_pos[2]]; let after_yaw = ( (before_yaw[0] * yaw.cos()) + (before_yaw[2] * yaw.sin()), (-before_yaw[0] * yaw.sin()) + (before_yaw[2] * yaw.cos()) ); [after_yaw.0 + post_pos[0], before_yaw[1] + post_pos[1], after_yaw.1 + post_pos[2]] }; [ // back face Vertex { position: gen_pos([-1., -1., -1.]), normal: [0., 0., -1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., -1., -1.]), normal: [0., 0., -1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., 1., -1.]), normal: [0., 0., -1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., -1.]), normal: [0., 0., -1.], texcoords: [0., 0.] }, // front face Vertex { position: gen_pos([-1., -1., 1.]), normal: [0., 0., 1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., -1., 1.]), normal: [0., 0., 1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., 1., 1.]), normal: [0., 0., 1.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., 1.]), normal: [0., 0., 1.], texcoords: [0., 0.] }, // left face Vertex { position: gen_pos([-1., -1., 1.]), normal: [-1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., -1., -1.]), normal: [-1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., 1., -1.]), normal: [-1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., 1., 1.]), normal: [-1., 0., 0.], texcoords: [0., 0.] }, // right face Vertex { position: gen_pos([1., -1., 1.]), normal: [1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., -1., -1.]), normal: [1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., -1.]), normal: [1., 0., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., 1.]), normal: [1., 0., 0.], texcoords: [0., 0.] }, // top face Vertex { position: gen_pos([-1., 1., 1.]), normal: [0., 1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., -1.]), normal: [0., 1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., 1., -1.]), normal: [0., 1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., 1., 1.]), normal: [0., 1., 0.], texcoords: [0., 0.] }, // bottom face Vertex { position: gen_pos([-1., -1., 1.]), normal: [0., -1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., -1., -1.]), normal: [0., -1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([-1., -1., -1.]), normal: [0., -1., 0.], texcoords: [0., 0.] }, Vertex { position: gen_pos([1., -1., 1.]), normal: [0., -1., 0.], texcoords: [0., 0.] }, ] } const INDICES: [[u32; 3]; 12] = [ // back face [0, 1, 2], [1, 3, 2], // front face [6, 5, 4], [6, 7, 5], // left face [8, 9, 10], [11, 8, 10], // right face [14, 13, 12], [15, 14, 12], // top face [18, 17, 16], [19, 16, 17], // bottom face [20, 21, 22], [21, 20, 23] ]; pub fn load_cube(display: &Display, dim: &[f32; 3], cull_reverse: bool) -> ObjDef { let mut indices: Vec<u32> = Vec::new(); if cull_reverse { for tri in &INDICES { let mut tri_clone = tri.clone(); tri_clone.reverse(); indices.extend(&tri_clone); } } else { INDICES.iter().for_each(|i| indices.extend(i)); }; load_data_to_gpu(display, &generate_cube_vertices(&[0., 0., 0.], &[0., 0., 0.], dim, 0.), &indices) } pub fn generate_cube_collideobj(pre_pos: &[f32; 3], post_pos: &[f32; 3], dim: &[f32; 3], yaw: f32) -> CollisionObj { CollisionObj::Polygon(generate_cube_vertices(pre_pos, post_pos, dim, yaw).to_vec(), *post_pos) }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crate::{ errors::*, group::Group, key_exchange::NONCE_LEN, keypair::{Key, KeyPair, SignalKeyPair}, opaque::*, tests::mock_rng::CycleRng, }; use aes_gcm::Aes256Gcm; use curve25519_dalek::edwards::EdwardsPoint; use rand_core::{OsRng, RngCore}; use serde_json::Value; use std::convert::TryFrom; // Tests // ===== pub struct TestVectorParameters { pub client_s_pk: Vec<u8>, pub client_s_sk: Vec<u8>, pub client_e_pk: Vec<u8>, pub client_e_sk: Vec<u8>, pub server_s_pk: Vec<u8>, pub server_s_sk: Vec<u8>, pub server_e_pk: Vec<u8>, pub server_e_sk: Vec<u8>, pub password: Vec<u8>, pub blinding_factor_raw: Vec<u8>, pub blinding_factor: Vec<u8>, pub pepper: Vec<u8>, pub oprf_key: Vec<u8>, pub envelope_nonce: Vec<u8>, pub client_nonce: Vec<u8>, pub server_nonce: Vec<u8>, pub r1: Vec<u8>, pub r2: Vec<u8>, pub r3: Vec<u8>, pub l1: Vec<u8>, pub l2: Vec<u8>, pub l3: Vec<u8>, client_registration_state: Vec<u8>, server_registration_state: Vec<u8>, client_login_state: Vec<u8>, server_login_state: Vec<u8>, pub password_file: Vec<u8>, pub opaque_key: Vec<u8>, pub shared_secret: Vec<u8>, } static TEST_VECTOR: &str = r#" { "client_s_pk": "f7b150789db3322c8c7b8c4a10ce42baa5ee846de83eaf04c17ffbd0d9e5cd60", "client_s_sk": "601ed276a42ec5795b3471f1a64e312f192e17ff252ce6053c8ecaf210138273", "client_e_pk": "57260d4e231035f0f3e1fb836fe5d9ddb498c956cacb5fab1d6b287e1422376c", "client_e_sk": "e89d0fa4e387a9bd7c26466704ec30e62f58892bf3dfd1fd25133be52f34ea68", "server_s_pk": "a2b4e12d0621ebfb2631e00f5c872ab749e1a33915f16fb11203658b2189cc5e", "server_s_sk": "90b6ca2ea8a37306060c7cd0998d4cdae59e972af7760312f7cf77099e78f940", "server_e_pk": "64ce4a453eb8c27b1d81f6acdc01d36d3ae6cea506432e9509917b195ad90073", "server_e_sk": "883148cc1ba70acb1eb909d99e09493b5d4b3fe6b12c75e2f5aeea6c5d4b267f", "password": "70617373776f7264", "blinding_factor_raw": "b85e0df2ad0495771edf09a04b1073045e6472e2f86a41e9bab3143ebfb8eb08a3462503eb3750bf006dc82c93b37e07cdf3768018c22b431cf5146a9caeda1c", "blinding_factor": "fac0ed1c38bc8945a91dc4d944af22c466cbffc24fc3d97b8a91798d1ec8b60f", "pepper": "706570706572", "oprf_key": "d5cedff72509af4702a985bb31af8dbe88d72c4eee13a09e3f52a76766fa6f0b", "envelope_nonce": "c87e44792a9dfd8858db676e", "client_nonce": "1f023acc6155a06166ee7e5b7ef0360277ed5da3a46adcd4a0a5bce938a67a23", "server_nonce": "d448cb1f58c38605fc29069ac688ec9c667c99d0316b38cd1b2609c1bc14aa90", "r1": "e46efe7d673805b6135a5293ecab13082b322c45f029595efa4b8d1d53ccd897", "r2": "a2a3df89cf85976c4aa5add752736419f728805722571a9646983587ce4c55fb", "r3": "374c49768e4399d4cd46e8b3bc2050e2f6737e3a2f8aee6fddc82e117f340f79a7f10c84445657c6bb4940bd02bc08ca0f107618d810ec94639e8ae43af48ab66f1f75e8bbc169eed0035e347310978bc87e44792a9dfd8858db676ef7b150789db3322c8c7b8c4a10ce42baa5ee846de83eaf04c17ffbd0d9e5cd60", "l1": "e46efe7d673805b6135a5293ecab13082b322c45f029595efa4b8d1d53ccd8971f023acc6155a06166ee7e5b7ef0360277ed5da3a46adcd4a0a5bce938a67a2357260d4e231035f0f3e1fb836fe5d9ddb498c956cacb5fab1d6b287e1422376c", "l2": "a2a3df89cf85976c4aa5add752736419f728805722571a9646983587ce4c55fb374c49768e4399d4cd46e8b3bc2050e2f6737e3a2f8aee6fddc82e117f340f79a7f10c84445657c6bb4940bd02bc08ca0f107618d810ec94639e8ae43af48ab66f1f75e8bbc169eed0035e347310978bc87e44792a9dfd8858db676e883148cc1ba70acb1eb909d99e09493b5d4b3fe6b12c75e2f5aeea6c5d4b267f64ce4a453eb8c27b1d81f6acdc01d36d3ae6cea506432e9509917b195ad90073d81a1104fbd599ef56228bdbe9bf7be4a38ae907a8717ca0883b9d69b2efc529", "l3": "a01332643e8aa7113f6f160205a9b3bd0705f3b33d8e4ea8eab9eae6685a6adb", "client_registration_state": "fac0ed1c38bc8945a91dc4d944af22c466cbffc24fc3d97b8a91798d1ec8b60f70617373776f7264", "client_login_state": "fac0ed1c38bc8945a91dc4d944af22c466cbffc24fc3d97b8a91798d1ec8b60fe89d0fa4e387a9bd7c26466704ec30e62f58892bf3dfd1fd25133be52f34ea681f023acc6155a06166ee7e5b7ef0360277ed5da3a46adcd4a0a5bce938a67a23dd1a7c2b4e9f9be94bd36f3b6c7f23aa9f1e6b3fda9030412a918d1288b4af1970617373776f7264", "server_registration_state": "d5cedff72509af4702a985bb31af8dbe88d72c4eee13a09e3f52a76766fa6f0b", "server_login_state": "809f95143f8f7fc1d0b42f578a83f714f58cfd96d9499aacee730ad296b37b19c18c903396e85da607d02542d4d07456e5357ff2e2eade3aaa42e532d4e9364f66317ab0460307e33d6151e99c7406f2fa1d309f507b46e43f732924d1dc8d0d", "password_file": "d5cedff72509af4702a985bb31af8dbe88d72c4eee13a09e3f52a76766fa6f0bf7b150789db3322c8c7b8c4a10ce42baa5ee846de83eaf04c17ffbd0d9e5cd60374c49768e4399d4cd46e8b3bc2050e2f6737e3a2f8aee6fddc82e117f340f79a7f10c84445657c6bb4940bd02bc08ca0f107618d810ec94639e8ae43af48ab66f1f75e8bbc169eed0035e347310978bc87e44792a9dfd8858db676e", "opaque_key": "682f2868a3e1460fed5a16767bd8778c33b4aecac6607270f848aa61c95a1a68", "shared_secret": "66317ab0460307e33d6151e99c7406f2fa1d309f507b46e43f732924d1dc8d0d" } "#; fn decode(values: &Value, key: &str) -> Option<Vec<u8>> { values[key] .as_str() .and_then(|s| hex::decode(&s.to_string()).ok()) } fn populate_test_vectors(values: &Value) -> TestVectorParameters { TestVectorParameters { client_s_pk: decode(&values, "client_s_pk").unwrap(), client_s_sk: decode(&values, "client_s_sk").unwrap(), client_e_pk: decode(&values, "client_e_pk").unwrap(), client_e_sk: decode(&values, "client_e_sk").unwrap(), server_s_pk: decode(&values, "server_s_pk").unwrap(), server_s_sk: decode(&values, "server_s_sk").unwrap(), server_e_pk: decode(&values, "server_e_pk").unwrap(), server_e_sk: decode(&values, "server_e_sk").unwrap(), password: decode(&values, "password").unwrap(), blinding_factor_raw: decode(&values, "blinding_factor_raw").unwrap(), blinding_factor: decode(&values, "blinding_factor").unwrap(), pepper: decode(&values, "pepper").unwrap(), oprf_key: decode(&values, "oprf_key").unwrap(), envelope_nonce: decode(&values, "envelope_nonce").unwrap(), client_nonce: decode(&values, "client_nonce").unwrap(), server_nonce: decode(&values, "server_nonce").unwrap(), r1: decode(&values, "r1").unwrap(), r2: decode(&values, "r2").unwrap(), r3: decode(&values, "r3").unwrap(), l1: decode(&values, "l1").unwrap(), l2: decode(&values, "l2").unwrap(), l3: decode(&values, "l3").unwrap(), client_registration_state: decode(&values, "client_registration_state").unwrap(), client_login_state: decode(&values, "client_login_state").unwrap(), server_registration_state: decode(&values, "server_registration_state").unwrap(), server_login_state: decode(&values, "server_login_state").unwrap(), password_file: decode(&values, "password_file").unwrap(), opaque_key: decode(&values, "opaque_key").unwrap(), shared_secret: decode(&values, "shared_secret").unwrap(), } } fn stringify_test_vectors(p: &TestVectorParameters) -> String { let mut s = String::new(); s.push_str("{\n"); s.push_str(format!("\"client_s_pk\": \"{}\",\n", hex::encode(&p.client_s_pk)).as_str()); s.push_str(format!("\"client_s_sk\": \"{}\",\n", hex::encode(&p.client_s_sk)).as_str()); s.push_str(format!("\"client_e_pk\": \"{}\",\n", hex::encode(&p.client_e_pk)).as_str()); s.push_str(format!("\"client_e_sk\": \"{}\",\n", hex::encode(&p.client_e_sk)).as_str()); s.push_str(format!("\"server_s_pk\": \"{}\",\n", hex::encode(&p.server_s_pk)).as_str()); s.push_str(format!("\"server_s_sk\": \"{}\",\n", hex::encode(&p.server_s_sk)).as_str()); s.push_str(format!("\"server_e_pk\": \"{}\",\n", hex::encode(&p.server_e_pk)).as_str()); s.push_str(format!("\"server_e_sk\": \"{}\",\n", hex::encode(&p.server_e_sk)).as_str()); s.push_str(format!("\"password\": \"{}\",\n", hex::encode(&p.password)).as_str()); s.push_str( format!( "\"blinding_factor_raw\": \"{}\",\n", hex::encode(&p.blinding_factor_raw) ) .as_str(), ); s.push_str( format!( "\"blinding_factor\": \"{}\",\n", hex::encode(&p.blinding_factor) ) .as_str(), ); s.push_str(format!("\"pepper\": \"{}\",\n", hex::encode(&p.pepper)).as_str()); s.push_str(format!("\"oprf_key\": \"{}\",\n", hex::encode(&p.oprf_key)).as_str()); s.push_str( format!( "\"envelope_nonce\": \"{}\",\n", hex::encode(&p.envelope_nonce) ) .as_str(), ); s.push_str(format!("\"client_nonce\": \"{}\",\n", hex::encode(&p.client_nonce)).as_str()); s.push_str(format!("\"server_nonce\": \"{}\",\n", hex::encode(&p.server_nonce)).as_str()); s.push_str(format!("\"r1\": \"{}\",\n", hex::encode(&p.r1)).as_str()); s.push_str(format!("\"r2\": \"{}\",\n", hex::encode(&p.r2)).as_str()); s.push_str(format!("\"r3\": \"{}\",\n", hex::encode(&p.r3)).as_str()); s.push_str(format!("\"l1\": \"{}\",\n", hex::encode(&p.l1)).as_str()); s.push_str(format!("\"l2\": \"{}\",\n", hex::encode(&p.l2)).as_str()); s.push_str(format!("\"l3\": \"{}\",\n", hex::encode(&p.l3)).as_str()); s.push_str( format!( "\"client_registration_state\": \"{}\",\n", hex::encode(&p.client_registration_state) ) .as_str(), ); s.push_str( format!( "\"client_login_state\": \"{}\",\n", hex::encode(&p.client_login_state) ) .as_str(), ); s.push_str( format!( "\"server_registration_state\": \"{}\",\n", hex::encode(&p.server_registration_state) ) .as_str(), ); s.push_str( format!( "\"server_login_state\": \"{}\",\n", hex::encode(&p.server_login_state) ) .as_str(), ); s.push_str( format!( "\"password_file\": \"{}\",\n", hex::encode(&p.password_file) ) .as_str(), ); s.push_str(format!("\"opaque_key\": \"{}\",\n", hex::encode(&p.opaque_key)).as_str()); s.push_str(format!("\"shared_secret\": \"{}\"\n", hex::encode(&p.shared_secret)).as_str()); s.push_str("}\n"); s } fn generate_parameters() -> TestVectorParameters { let mut rng = OsRng; // Inputs let server_s_kp = SignalKeyPair::generate_random(&mut rng).unwrap(); let server_e_kp = SignalKeyPair::generate_random(&mut rng).unwrap(); let client_s_kp = SignalKeyPair::generate_random(&mut rng).unwrap(); let client_e_kp = SignalKeyPair::generate_random(&mut rng).unwrap(); let password = b"password"; let pepper = b"pepper"; let mut blinding_factor_raw = [0u8; 64]; rng.fill_bytes(&mut blinding_factor_raw); let mut oprf_key_raw = [0u8; 32]; rng.fill_bytes(&mut oprf_key_raw); let mut envelope_nonce = [0u8; 12]; rng.fill_bytes(&mut envelope_nonce); let mut client_nonce = [0u8; NONCE_LEN]; rng.fill_bytes(&mut client_nonce); let mut server_nonce = [0u8; NONCE_LEN]; rng.fill_bytes(&mut server_nonce); let mut blinding_factor_registration_rng = CycleRng::new(blinding_factor_raw.to_vec()); let (r1, client_registration) = ClientRegistration::<Aes256Gcm, EdwardsPoint>::start( password, Some(pepper), &mut blinding_factor_registration_rng, ) .unwrap(); let r1_bytes = r1.to_bytes().to_vec(); let blinding_factor_bytes = client_registration.blinding_factor.to_bytes(); let client_registration_state = client_registration.to_bytes().to_vec(); let mut oprf_key_rng = CycleRng::new(oprf_key_raw.to_vec()); let (r2, server_registration) = ServerRegistration::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start(r1, &mut oprf_key_rng) .unwrap(); let r2_bytes = r2.to_bytes().to_vec(); let oprf_key = server_registration.oprf_key; let oprf_key_bytes = EdwardsPoint::scalar_as_bytes(&oprf_key); let server_registration_state = server_registration.to_bytes().to_vec(); let mut client_s_sk_and_nonce: Vec<u8> = Vec::new(); client_s_sk_and_nonce.extend_from_slice(&client_s_kp.private()); client_s_sk_and_nonce.extend_from_slice(&envelope_nonce); let mut finish_registration_rng = CycleRng::new(client_s_sk_and_nonce); let (r3, opaque_key_registration) = client_registration .finish::<_, SignalKeyPair>(r2, server_s_kp.public(), &mut finish_registration_rng) .unwrap(); let r3_bytes = r3.to_bytes().to_vec(); let password_file = server_registration.finish(r3).unwrap(); let password_file_bytes = password_file.to_bytes(); let mut client_login_start: Vec<u8> = Vec::new(); client_login_start.extend_from_slice(&blinding_factor_raw); client_login_start.extend_from_slice(&client_e_kp.private()); client_login_start.extend_from_slice(&client_nonce); let mut client_login_start_rng = CycleRng::new(client_login_start); let (l1, client_login) = ClientLogin::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start( password, Some(pepper), &mut client_login_start_rng, ) .unwrap(); let l1_bytes = l1.to_bytes().to_vec(); let client_login_state = client_login.to_bytes().to_vec(); let mut server_e_sk_rng = CycleRng::new(server_e_kp.private().to_vec()); let (l2, server_login) = ServerLogin::start( password_file, server_s_kp.private(), l1, &mut server_e_sk_rng, ) .unwrap(); let l2_bytes = l2.to_bytes().to_vec(); let server_login_state = server_login.to_bytes().to_vec(); let mut client_e_sk_rng = CycleRng::new(client_e_kp.private().to_vec()); let (l3, client_shared_secret, _opaque_key_login) = client_login .finish(l2, server_s_kp.public(), &mut client_e_sk_rng) .unwrap(); let l3_bytes = l3.to_bytes().to_vec(); TestVectorParameters { client_s_pk: client_s_kp.public().to_vec(), client_s_sk: client_s_kp.private().to_vec(), client_e_pk: client_e_kp.public().to_vec(), client_e_sk: client_e_kp.private().to_vec(), server_s_pk: server_s_kp.public().to_vec(), server_s_sk: server_s_kp.private().to_vec(), server_e_pk: server_e_kp.public().to_vec(), server_e_sk: server_e_kp.private().to_vec(), password: password.to_vec(), blinding_factor_raw: blinding_factor_raw.to_vec(), blinding_factor: blinding_factor_bytes.to_vec(), pepper: pepper.to_vec(), oprf_key: oprf_key_bytes.to_vec(), envelope_nonce: envelope_nonce.to_vec(), client_nonce: client_nonce.to_vec(), server_nonce: server_nonce.to_vec(), r1: r1_bytes, r2: r2_bytes, r3: r3_bytes, l1: l1_bytes, l2: l2_bytes, l3: l3_bytes, password_file: password_file_bytes, client_registration_state, server_registration_state, client_login_state, server_login_state, shared_secret: client_shared_secret, opaque_key: opaque_key_registration.to_vec(), } } #[test] fn generate_test_vectors() { let parameters = generate_parameters(); println!("{}", stringify_test_vectors(&parameters)); } #[test] fn test_r1() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let mut blinding_factor_rng = CycleRng::new(parameters.blinding_factor_raw); let (r1, client_registration) = ClientRegistration::<Aes256Gcm, EdwardsPoint>::start( &parameters.password, Some(&parameters.pepper), &mut blinding_factor_rng, ) .unwrap(); assert_eq!(hex::encode(&parameters.r1), hex::encode(r1.to_bytes())); assert_eq!( hex::encode(&parameters.client_registration_state), hex::encode(client_registration.to_bytes()) ); Ok(()) } #[test] fn test_r2() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let mut oprf_key_rng = CycleRng::new(parameters.oprf_key); let (r2, server_registration) = ServerRegistration::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start( RegisterFirstMessage::try_from(&parameters.r1[..]).unwrap(), &mut oprf_key_rng, ) .unwrap(); assert_eq!(hex::encode(parameters.r2), hex::encode(r2.to_bytes())); assert_eq!( hex::encode(&parameters.server_registration_state), hex::encode(server_registration.to_bytes()) ); Ok(()) } #[test] fn test_r3() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let client_s_sk_and_nonce: Vec<u8> = [parameters.client_s_sk, parameters.envelope_nonce].concat(); let mut finish_registration_rng = CycleRng::new(client_s_sk_and_nonce); let (r3, opaque_key_registration) = ClientRegistration::<Aes256Gcm, EdwardsPoint>::try_from( &parameters.client_registration_state[..], ) .unwrap() .finish::<CycleRng, SignalKeyPair>( RegisterSecondMessage::try_from(&parameters.r2[..]).unwrap(), &Key::try_from(parameters.server_s_pk).unwrap(), &mut finish_registration_rng, ) .unwrap(); assert_eq!(hex::encode(parameters.r3), hex::encode(r3.to_bytes())); assert_eq!( hex::encode(parameters.opaque_key), hex::encode(opaque_key_registration.to_vec()) ); Ok(()) } #[test] fn test_password_file() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let server_registration = ServerRegistration::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::try_from( &parameters.server_registration_state[..], ) .unwrap(); let password_file = server_registration .finish(RegisterThirdMessage::try_from(&parameters.r3[..]).unwrap()) .unwrap(); assert_eq!( hex::encode(parameters.password_file), hex::encode(password_file.to_bytes()) ); Ok(()) } #[test] fn test_l1() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let client_login_start = [ parameters.blinding_factor_raw, parameters.client_e_sk, parameters.client_nonce, ] .concat(); let mut client_login_start_rng = CycleRng::new(client_login_start); let (l1, client_login) = ClientLogin::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start( &parameters.password, Some(&parameters.pepper), &mut client_login_start_rng, ) .unwrap(); assert_eq!(hex::encode(&parameters.l1), hex::encode(l1.to_bytes())); assert_eq!( hex::encode(&parameters.client_login_state), hex::encode(client_login.to_bytes()) ); Ok(()) } #[test] fn test_l2() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let mut server_e_sk_rng = CycleRng::new(parameters.server_e_sk); let (l2, server_login) = ServerLogin::start::<_, Aes256Gcm, _, SignalKeyPair>( ServerRegistration::try_from(&parameters.password_file[..]).unwrap(), &Key::try_from(parameters.server_s_sk).unwrap(), LoginFirstMessage::<EdwardsPoint>::try_from(&parameters.l1[..]).unwrap(), &mut server_e_sk_rng, ) .unwrap(); assert_eq!(hex::encode(&parameters.l2), hex::encode(l2.to_bytes())); assert_eq!( hex::encode(&parameters.server_login_state), hex::encode(server_login.to_bytes()) ); Ok(()) } #[test] fn test_l3() -> Result<(), PakeError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let mut client_e_sk_rng = CycleRng::new(parameters.client_e_sk.to_vec()); let (l3, shared_secret, opaque_key_login) = ClientLogin::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::try_from( &parameters.client_login_state[..], ) .unwrap() .finish( LoginSecondMessage::<Aes256Gcm, EdwardsPoint>::try_from(&parameters.l2[..]).unwrap(), &Key::try_from(parameters.server_s_pk)?, &mut client_e_sk_rng, ) .unwrap(); assert_eq!( hex::encode(&parameters.shared_secret), hex::encode(&shared_secret) ); assert_eq!(hex::encode(&parameters.l3), hex::encode(l3.to_bytes())); assert_eq!( hex::encode(&parameters.opaque_key), hex::encode(opaque_key_login) ); Ok(()) } #[test] fn test_server_login_finish() -> Result<(), ProtocolError> { let parameters = populate_test_vectors(&serde_json::from_str(TEST_VECTOR).unwrap()); let shared_secret = ServerLogin::try_from(&parameters.server_login_state[..]) .unwrap() .finish(LoginThirdMessage::try_from(&parameters.l3[..])?) .unwrap(); assert_eq!( hex::encode(parameters.shared_secret), hex::encode(shared_secret) ); Ok(()) } fn test_complete_flow( registration_password: &[u8], login_password: &[u8], ) -> Result<(), ProtocolError> { let mut client_rng = OsRng; let mut server_rng = OsRng; let server_kp = SignalKeyPair::generate_random(&mut server_rng)?; let (register_m1, client_state) = ClientRegistration::<Aes256Gcm, EdwardsPoint>::start( registration_password, None, &mut client_rng, )?; let (register_m2, server_state) = ServerRegistration::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start( register_m1, &mut server_rng, )?; let (register_m3, registration_opaque_key) = client_state.finish(register_m2, server_kp.public(), &mut client_rng)?; let p_file = server_state.finish(register_m3)?; let (login_m1, client_login_state) = ClientLogin::<Aes256Gcm, EdwardsPoint, SignalKeyPair>::start( login_password, None, &mut client_rng, )?; let (login_m2, server_login_state) = ServerLogin::start(p_file, &server_kp.private(), login_m1, &mut server_rng)?; let client_login_result = client_login_state.finish(login_m2, &server_kp.public(), &mut client_rng); if hex::encode(registration_password) == hex::encode(login_password) { let (login_m3, client_shared_secret, login_opaque_key) = client_login_result?; let server_shared_secret = server_login_state.finish(login_m3)?; assert_eq!( hex::encode(server_shared_secret), hex::encode(client_shared_secret) ); assert_eq!( hex::encode(registration_opaque_key), hex::encode(login_opaque_key) ); } else { let res = match client_login_result { Err(ProtocolError::VerificationError(PakeError::InvalidLoginError)) => true, _ => false, }; assert!(res); } Ok(()) } #[test] fn test_complete_flow_success() -> Result<(), ProtocolError> { test_complete_flow(b"good password", b"good password") } #[test] fn test_complete_flow_fail() -> Result<(), ProtocolError> { test_complete_flow(b"good password", b"bad password") }
extern crate aoc2017; use aoc2017::days::day16; fn main() { let input = aoc2017::read_trim("input/day16.txt").unwrap(); let programs = "abcdefghijklmnop"; // let value1 = day16::part1::parse(programs, &input, 1); let value2 = day16::part2::parse(programs, &input, 1_000_000_000); // println!("Day 16 part 1 value: {}", value1); println!("Day 16 part 2 value: {}", value2); }
/* */ use parse::lex; pub struct Preproc { lexers: ::std::vec::Vec<LexHandle>, saved_tok: Option<::parse::lex::Token>, macros: ::std::collections::TreeMap<String,Vec<lex::Token>> } struct LexHandle { lexer: ::parse::lex::Lexer, filename: String, line: uint, } macro_rules! syntax_assert( ($tok:expr, $pat:pat => $val:expr) => ({ let v = try!($tok); match v { $pat => $val, _ => fail!("TODO: Syntax errors, assert {}, got {}", stringify!($pat), v) }})) impl Preproc { pub fn new(filename: &str) -> ::parse::ParseResult<Preproc> { let file_stream = if filename == "-" { box ::std::io::stdio::stdin() as Box<Reader> } else { box match ::std::io::File::open(&::std::path::Path::new(filename)) { Ok(f) => f, Err(e) => return Err(::parse::IOError(e)), } as Box<Reader> }; Ok(Preproc { lexers: vec![ LexHandle { lexer: ::parse::lex::Lexer::new(file_stream), filename: filename.to_string(), line: 1, } ], saved_tok: None, macros: ::std::collections::TreeMap::new(), }) } pub fn put_back(&mut self, tok: lex::Token) { assert!( self.saved_tok.is_none() ); self.saved_tok = Some( tok ); } pub fn get_token(&mut self) -> ::parse::ParseResult<lex::Token> { if self.saved_tok.is_some() { let tok = self.saved_tok.take_unwrap(); debug!("get_token = {} (saved)", tok); return Ok( tok ); } loop { let lexer_h = &mut self.lexers.mut_last().unwrap(); let lexer = &mut lexer_h.lexer; let tok = try!(lexer.get_token()); match tok { lex::TokNewline => { lexer_h.line += 1; }, lex::TokLineComment(_) => {}, lex::TokBlockComment(_) => {}, lex::TokHash => { match try!(lexer.get_token()) { lex::TokIdent(name) => { fail!("TODO: Preprocessor '{}'", name); }, lex::TokInteger(line, _) => { let file = syntax_assert!(lexer.get_token(), lex::TokString(s) => s); lexer_h.filename = file; lexer_h.line = line as uint; while try!(lexer.get_token()) != lex::TokNewline { } debug!("Set locaion to \"{}\":{}", lexer_h.filename, line); }, _ => { fail!("TODO: Syntax errors"); }, } }, lex::TokIdent(v) => { match self.macros.find(&v) { Some(macro) => fail!("TODO: Macro expansion"), _ => {} } let ret = lex::TokIdent(v); debug!("get_token = {}", ret); return Ok( ret ); }, _ => { debug!("get_token = {}", tok); return Ok(tok) } } } } } // vim: ft=rust
/// Round the 'array' passed using 'decimals' pub fn round_array(array: &mut [f64], decimals: u8) { let divider = (10.0 as f64).powi(decimals as i32); for number in array { *number = (*number * divider).round() / divider; } }
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 crate::peekable_chars_with_position::PeekableCharsWithPosition; use serde::{Deserialize, Serialize}; use std::fmt; #[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize)] pub enum TokenType { Let, Assign, Ident, Number, // :help string-literal // :help expr-quote StringLiteral, Function, EndFunction, If, Else, ElseIf, EndIf, Try, Catch, Finally, EndTry, // () LeftParenthesis, RightParenthesis, // [] LeftBracket, RightBracket, // {} LeftCurlyBrace, RightCurlyBrace, Colon, QuestionMark, Bang, Comma, Set, For, EndFor, While, EndWhile, In, Dot, Variadic, Abort, Call, Break, Execute, Return, EqualCaseSensitive, InEqualCaseSensitive, EqualCaseInSensitive, InEqualCaseInSensitive, Equal, InEqual, Less, LessOrEqual, Greater, GreaterOrEqual, RegexpMatchesIgnoreCase, RegexpMatchesCaseSensitive, RegexpMatchesCaseInSensitive, And, Or, Pipe, Plus, Minus, Multiply, Divide, Modulo, PlusAssign, MinusAssign, MultiplyAssign, DivideAssign, ModuloAssign, DotAssign, Finish, Comment, NewLine, Invalid, Eof, } impl TokenType { pub fn to_str(&self) -> &str { return self.as_str(); } pub fn as_str(&self) -> &str { match self { TokenType::Let => "`let`", TokenType::Assign => "`=`", TokenType::Ident => "identifier", TokenType::Number => "number", TokenType::StringLiteral => "string literal", TokenType::Function => "`function`", TokenType::EndFunction => "`endfunction`", TokenType::If => "`if`", TokenType::Else => "`else`", TokenType::ElseIf => "`elseif`", TokenType::EndIf => "`endif`", TokenType::Try => "`try`", TokenType::Catch => "`catch`", TokenType::Finally => "`finally`", TokenType::EndTry => "`endtry`", TokenType::LeftParenthesis => "`(`", TokenType::RightParenthesis => "`)`", TokenType::LeftBracket => "`[`", TokenType::RightBracket => "`]`", TokenType::LeftCurlyBrace => "`{`", TokenType::RightCurlyBrace => "`}`", TokenType::Bang => "`!`", TokenType::Colon => "`:`", TokenType::QuestionMark => "`?`", TokenType::Comma => "`,`", TokenType::Set => "`set`", TokenType::For => "`for`", TokenType::EndFor => "`endfor`", TokenType::While => "`while`", TokenType::EndWhile => "`endwhile`", TokenType::In => "`in`", TokenType::Dot => "`.`", TokenType::Variadic => "`...`", TokenType::Abort => "`abort`", TokenType::Call => "`call`", TokenType::Break => "`break`", TokenType::Execute => "`execute`", TokenType::Return => "`return`", TokenType::EqualCaseSensitive => "`==#`", TokenType::InEqualCaseSensitive => "`!=#`", TokenType::EqualCaseInSensitive => "`==?`", TokenType::InEqualCaseInSensitive => "`!=?`", TokenType::Equal => "`==`", TokenType::InEqual => "`!=`", TokenType::Less => "`<`", TokenType::LessOrEqual => "`<=`", TokenType::Greater => "`>`", TokenType::GreaterOrEqual => "`>=`", TokenType::RegexpMatchesIgnoreCase => "`=~`", TokenType::RegexpMatchesCaseSensitive => "`=~#`", TokenType::RegexpMatchesCaseInSensitive => "`=~?`", TokenType::And => "`&&`", TokenType::Or => "`||`", TokenType::Pipe => "`|`", TokenType::Plus => "`+`", TokenType::Minus => "`-`", TokenType::Multiply => "`*`", TokenType::Divide => "`/`", TokenType::Modulo => "`%`", TokenType::PlusAssign => "`+=`", TokenType::MinusAssign => "`-=`", TokenType::MultiplyAssign => "`*=`", TokenType::DivideAssign => "`/=`", TokenType::ModuloAssign => "`%=`", TokenType::DotAssign => "`.=`", TokenType::Finish => "`finish`", TokenType::Comment => "comment", TokenType::NewLine => "new line", TokenType::Invalid => "invalid", TokenType::Eof => "end of file", } } } /// Location in a source code (most of the time points to the start of the token). #[derive(PartialEq, Debug, Clone, Serialize, Deserialize)] pub struct SourceLocation { pub range: std::ops::Range<usize>, } #[derive(PartialEq, Debug)] pub struct TokenPosition { pub start: SourcePosition, pub end: SourcePosition, } impl fmt::Display for TokenPosition { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}-{}", self.start, self.end) } } // Position with zero based offsets, points to position just before the character. #[derive(PartialEq, PartialOrd, Debug)] pub struct SourcePosition { // starting from 0 pub line: i32, // starting from 0 pub character: i32, } impl fmt::Display for SourcePosition { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.line, self.character) } } #[derive(PartialEq, Debug, Clone)] pub struct Token { pub token_type: TokenType, pub location: SourceLocation, } pub struct Lexer<'a> { source: &'a str, chars: PeekableCharsWithPosition<'a>, tokens: Vec<Token>, // The position of the start of the current token. start: usize, first_token_in_line: bool, } impl<'a> Lexer<'a> { pub fn new(source: &'a str) -> Lexer<'a> { return Lexer { source: source, chars: PeekableCharsWithPosition::new(source), start: 0, tokens: Vec::new(), first_token_in_line: true, }; } // TODO: remove this method once Lexer always returns Eof as last token. pub fn eof_token(&self) -> Token { return Token { token_type: TokenType::Eof, location: SourceLocation { range: self.source.len()..self.source.len(), }, }; } pub fn token_text(&self, location: &SourceLocation) -> &'a str { return &self.source[location.range.clone()]; } // This is expensive, expected to be called only for errors. fn source_position(&self, location: usize) -> SourcePosition { let mut line = 0; let mut character = 0; for (pos, c) in self.source.char_indices() { if pos >= location { return SourcePosition { line: line, character: character, }; } character += 1; if c == '\n' { line += 1; character = 0; } } return SourcePosition { line: line, character: character, }; } // This is expensive, expected to be called only for errors. pub fn token_position(&self, location: &SourceLocation) -> TokenPosition { return TokenPosition { start: self.source_position(location.range.start), end: self.source_position(location.range.end), }; } pub fn lex(&mut self) -> Vec<Token> { while self.read_token() { self.start = self.chars.pos(); } return std::mem::replace(&mut self.tokens, Vec::new()); } fn read_token(&mut self) -> bool { match self.chars.next() { None => return false, Some('\n') => self.read_newline(), Some('(') => self.add_token(TokenType::LeftParenthesis), Some(')') => self.add_token(TokenType::RightParenthesis), Some('[') => self.add_token(TokenType::LeftBracket), Some(']') => self.add_token(TokenType::RightBracket), Some('{') => self.add_token(TokenType::LeftCurlyBrace), Some('}') => self.add_token(TokenType::RightCurlyBrace), Some(',') => self.add_token(TokenType::Comma), Some(':') => self.add_token(TokenType::Colon), Some('?') => self.add_token(TokenType::QuestionMark), Some('+') => self.read_math_operator(TokenType::Plus, TokenType::PlusAssign), Some('-') => self.read_math_operator(TokenType::Minus, TokenType::MinusAssign), Some('*') => self.read_math_operator(TokenType::Multiply, TokenType::MultiplyAssign), Some('/') => self.read_math_operator(TokenType::Divide, TokenType::DivideAssign), Some('%') => self.read_math_operator(TokenType::Modulo, TokenType::ModuloAssign), Some('.') => self.read_dot(), Some('\'') => self.read_string_literal(), Some('=') => self.read_equal(), Some('!') => self.read_in_equal(), Some('<') => self.read_less(), Some('>') => self.read_greater(), Some('&') => self.read_and(), Some('|') => self.read_pipe(), Some('"') => self.read_quote(), Some(' ') => {} Some(c) => { if '0' <= c && c <= '9' { self.read_number(); } else { self.read_identifier(); } } } return true; } fn add_token(&mut self, token_type: TokenType) { self.tokens.push(Token { token_type: token_type, location: SourceLocation { range: self.start..self.chars.pos(), }, }); self.first_token_in_line = token_type == TokenType::NewLine } fn read_math_operator(&mut self, op: TokenType, assign: TokenType) { if Some('=') == self.chars.peek() { self.chars.next(); self.add_token(assign); } else { self.add_token(op); } } fn read_newline(&mut self) { let token = Token { token_type: TokenType::NewLine, location: SourceLocation { range: self.start..self.chars.pos(), }, }; loop { match self.chars.peek() { Some(' ') => { self.chars.next(); } Some('\t') => { self.chars.next(); } Some('\\') => { self.chars.next(); return; } _ => { self.tokens.push(token); self.first_token_in_line = true; return; } } } } fn read_less(&mut self) { match self.chars.peek() { Some('=') => { self.chars.next(); self.add_token(TokenType::LessOrEqual); } _ => self.add_token(TokenType::Less), } } fn read_greater(&mut self) { match self.chars.peek() { Some('=') => { self.chars.next(); self.add_token(TokenType::GreaterOrEqual); } _ => self.add_token(TokenType::Greater), } } fn read_and(&mut self) { match self.chars.peek() { Some('&') => { self.chars.next(); self.add_token(TokenType::And); } _ => { self.read_identifier(); } } } fn read_equal(&mut self) { match self.chars.peek() { Some('=') => { self.chars.next(); match self.chars.peek() { Some('#') => { self.chars.next(); self.add_token(TokenType::EqualCaseSensitive); } Some('?') => { self.chars.next(); self.add_token(TokenType::EqualCaseInSensitive); } _ => { self.add_token(TokenType::Equal); } } } Some('~') => { self.chars.next(); match self.chars.peek() { Some('#') => { self.chars.next(); self.add_token(TokenType::RegexpMatchesCaseSensitive); } Some('?') => { self.chars.next(); self.add_token(TokenType::RegexpMatchesCaseInSensitive); } _ => { self.add_token(TokenType::RegexpMatchesIgnoreCase); } } } _ => self.add_token(TokenType::Assign), } } fn read_in_equal(&mut self) { match self.chars.peek() { Some('=') => { self.chars.next(); match self.chars.peek() { Some('#') => { self.chars.next(); self.add_token(TokenType::InEqualCaseSensitive); } Some('?') => { self.chars.next(); self.add_token(TokenType::InEqualCaseInSensitive); } _ => { self.add_token(TokenType::InEqual); } } } _ => self.add_token(TokenType::Bang), } } fn read_dot(&mut self) { match self.chars.peek() { None => self.add_token(TokenType::Dot), Some('.') => { self.chars.next(); if let Some('.') = self.chars.peek() { self.chars.next(); self.add_token(TokenType::Variadic); return; } else { self.add_token(TokenType::Invalid); } } Some('=') => { self.chars.next(); self.add_token(TokenType::DotAssign); } Some(_) => self.add_token(TokenType::Dot), } } fn read_string_literal(&mut self) { loop { match self.chars.next() { None => { self.add_token(TokenType::Invalid); return; } Some('\'') => { if self.chars.peek() == Some('\'') { self.chars.next(); continue; } break; } Some('\n') => { // Next line has to start with a backslash (with allowed spaces before). // TODO: how can we report the error nicely here? loop { match self.chars.peek() { Some(' ') => { self.chars.next(); } Some('\\') => { self.chars.next(); break; } _ => { self.add_token(TokenType::Invalid); return; } } } } _ => {} } } self.add_token(TokenType::StringLiteral) } fn read_quote(&mut self) { // TODO: handle proper escaping. let mut escaped = false; loop { match self.chars.peek() { None => return, Some('\\') => { self.chars.next(); escaped = !escaped; } Some('"') => { self.chars.next(); if !self.first_token_in_line && !escaped { self.add_token(TokenType::StringLiteral); return; } } Some('\n') => { self.add_token(TokenType::Comment); return; } _ => { self.chars.next(); escaped = false; } } } } fn read_pipe(&mut self) { if self.chars.peek() == Some('|') { self.chars.next(); self.add_token(TokenType::Or); return; } self.add_token(TokenType::Pipe); } fn read_number(&mut self) { // TODO: handle floating point numbers. loop { match self.chars.peek() { None => break, Some(c) => { if !('0' <= c && c <= '9') { break; } } } self.chars.next(); } self.add_token(TokenType::Number); } fn read_identifier(&mut self) { loop { match self.chars.peek() { None => break, Some(c) => { if !(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || c == '#' || c == ':' || c == '_' || ('0' <= c && c <= '9')) { break; } } } self.chars.next(); } let s = &self.source[self.start..self.chars.pos()]; self.add_token(match s { "let" => TokenType::Let, "function" => TokenType::Function, "endfunction" => TokenType::EndFunction, "if" => TokenType::If, "else" => TokenType::Else, "elseif" => TokenType::ElseIf, "endif" => TokenType::EndIf, "try" => TokenType::Try, "catch" => TokenType::Catch, "finally" => TokenType::Finally, "endtry" => TokenType::EndTry, "for" => TokenType::For, "set" => TokenType::Set, "endfor" => TokenType::EndFor, "while" => TokenType::While, "endwhile" => TokenType::EndWhile, "in" => TokenType::In, "call" => TokenType::Call, "break" => TokenType::Break, "execute" => TokenType::Execute, "return" => TokenType::Return, "abort" => TokenType::Abort, "finish" => TokenType::Finish, _ => TokenType::Ident, }); } } #[cfg(test)] mod tests { use super::*; #[cfg(test)] use pretty_assertions::assert_eq; fn parse_source(source: &str) -> Vec<(TokenType, &str)> { let mut lexer = Lexer::new(source); return lexer .lex() .into_iter() .map(|t| (t.token_type, lexer.token_text(&t.location))) .collect(); } #[test] fn parses_sample_vimscript() { assert_eq!( parse_source( "let s:enabled = 15 function! plug#name(...) abort if a:test_123 endif endfunction" ), &[ (TokenType::Let, "let"), (TokenType::Ident, "s:enabled"), (TokenType::Assign, "="), (TokenType::Number, "15"), (TokenType::NewLine, "\n"), (TokenType::Function, "function"), (TokenType::Bang, "!"), (TokenType::Ident, "plug#name"), (TokenType::LeftParenthesis, "("), (TokenType::Variadic, "..."), (TokenType::RightParenthesis, ")"), (TokenType::Abort, "abort"), (TokenType::NewLine, "\n"), (TokenType::If, "if"), (TokenType::Ident, "a:test_123"), (TokenType::NewLine, "\n"), (TokenType::EndIf, "endif"), (TokenType::NewLine, "\n"), (TokenType::EndFunction, "endfunction"), ], ); } #[test] fn parses_concatenation_of_string_literals() { assert_eq!( parse_source("'a' . 'b'"), &[ (TokenType::StringLiteral, "'a'"), (TokenType::Dot, "."), (TokenType::StringLiteral, "'b'"), ], ); } #[test] fn parses_comma_colon_question_mark() { assert_eq!( parse_source(", : ?"), &[ (TokenType::Comma, ","), (TokenType::Colon, ":"), (TokenType::QuestionMark, "?"), ], ); } #[test] fn parses_pipe_and_or() { assert_eq!( parse_source("| ||"), &[(TokenType::Pipe, "|"), (TokenType::Or, "||"),] ); } #[test] fn parses_reserved_words() { assert_eq!( parse_source("let return execute call break set for endfor while endwhile if endif function endfunction abort in finish"), &[ (TokenType::Let, "let"), (TokenType::Return, "return"), (TokenType::Execute, "execute"), (TokenType::Call, "call"), (TokenType::Break, "break"), (TokenType::Set, "set"), (TokenType::For, "for"), (TokenType::EndFor, "endfor"), (TokenType::While, "while"), (TokenType::EndWhile, "endwhile"), (TokenType::If, "if"), (TokenType::EndIf, "endif"), (TokenType::Function, "function"), (TokenType::EndFunction, "endfunction"), (TokenType::Abort, "abort"), (TokenType::In, "in"), (TokenType::Finish, "finish"), ], ); } #[test] fn parses_for_statement() { assert_eq!( parse_source("for [a, b] in items endfor",), &[ (TokenType::For, "for"), (TokenType::LeftBracket, "["), (TokenType::Ident, "a"), (TokenType::Comma, ","), (TokenType::Ident, "b"), (TokenType::RightBracket, "]"), (TokenType::In, "in"), (TokenType::Ident, "items"), (TokenType::EndFor, "endfor"), ] ); } #[test] fn parses_quote_expression() { assert_eq!( parse_source("endif \"some\""), &[ (TokenType::EndIf, "endif"), (TokenType::StringLiteral, "\"some\"") ] ); } #[test] fn parses_comments() { assert_eq!( parse_source(",\" some comment\n="), &[ (TokenType::Comma, ","), (TokenType::Comment, "\" some comment"), (TokenType::NewLine, "\n"), (TokenType::Assign, "=") ], ); } #[test] fn returns_no_tokens_when_input_is_empty() { assert_eq!(parse_source(""), &[]) } #[test] fn parses_string_literals() { assert_eq!( parse_source("'That''s enough.'"), &[(TokenType::StringLiteral, "'That''s enough.'"),] ) } #[test] fn parses_string_literals_with_new_lines() { assert_eq!( parse_source("'That\n \\is valid literal'"), &[(TokenType::StringLiteral, "'That\n \\is valid literal'"),] ) } #[test] fn returns_invalid_string_for_multi_line_literal_without_backslash() { assert_eq!( parse_source("'That\n '"), &[(TokenType::Invalid, "'That\n "), (TokenType::Invalid, "'"),] ) } #[test] fn parses_comparison_operators() { assert_eq!( parse_source("==# !=# ==? !=? == != < <= > >= && =~ =~# =~?"), &[ (TokenType::EqualCaseSensitive, "==#"), (TokenType::InEqualCaseSensitive, "!=#"), (TokenType::EqualCaseInSensitive, "==?"), (TokenType::InEqualCaseInSensitive, "!=?"), (TokenType::Equal, "=="), (TokenType::InEqual, "!="), (TokenType::Less, "<"), (TokenType::LessOrEqual, "<="), (TokenType::Greater, ">"), (TokenType::GreaterOrEqual, ">="), (TokenType::And, "&&"), (TokenType::RegexpMatchesIgnoreCase, "=~"), (TokenType::RegexpMatchesCaseSensitive, "=~#"), (TokenType::RegexpMatchesCaseInSensitive, "=~?"), ], ) } #[test] fn parses_math_operators() { assert_eq!( parse_source("+ += - -= * *= / /= % %= . .="), &[ (TokenType::Plus, "+"), (TokenType::PlusAssign, "+="), (TokenType::Minus, "-"), (TokenType::MinusAssign, "-="), (TokenType::Multiply, "*"), (TokenType::MultiplyAssign, "*="), (TokenType::Divide, "/"), (TokenType::DivideAssign, "/="), (TokenType::Modulo, "%"), (TokenType::ModuloAssign, "%="), (TokenType::Dot, "."), (TokenType::DotAssign, ".="), ], ) } #[test] fn parses_two_string_literals() { assert_eq!( parse_source(r#"endif "foo" "bar""#), &[ (TokenType::EndIf, "endif"), (TokenType::StringLiteral, "\"foo\""), (TokenType::StringLiteral, "\"bar\""), ], ) } #[test] fn parses_identifier_with_capital_letter() { assert_eq!( parse_source(r#"s:Length"#), &[(TokenType::Ident, "s:Length"),], ) } #[test] fn parses_identifier_with_ampersand() { assert_eq!(parse_source(r#"&paste"#), &[(TokenType::Ident, "&paste"),],) } #[test] fn parses_string_literal_with_escaped_quote() { assert_eq!( parse_source(r#"endif "\"foo""#), &[ (TokenType::EndIf, "endif"), (TokenType::StringLiteral, r#""\"foo""#), ], ) } #[test] fn parses_comment_with_quotes_in_it() { assert_eq!(parse_source(r#"" This is comment with "quotes""#), &[]) } #[test] fn includes_new_line_after_comment() { assert_eq!( parse_source("\"comment\nendif"), &[ (TokenType::Comment, "\"comment"), (TokenType::NewLine, "\n"), (TokenType::EndIf, "endif"), ] ) } #[test] fn parses_line_breaks() { assert_eq!( parse_source("a + \n \t\\ b"), &[ (TokenType::Ident, "a"), (TokenType::Plus, "+"), (TokenType::Ident, "b"), ] ) } #[test] fn parses_try_catch_keywords() { assert_eq!( parse_source("try catch finally endtry"), &[ (TokenType::Try, "try"), (TokenType::Catch, "catch"), (TokenType::Finally, "finally"), (TokenType::EndTry, "endtry"), ] ) } #[test] fn returns_correct_token_position() { let mut lexer = Lexer::new("unknown"); let tokens = lexer.lex(); let position = lexer.token_position(&tokens[0].location); assert_eq!( position, TokenPosition { start: SourcePosition { line: 0, character: 0 }, end: SourcePosition { line: 0, character: 7 }, } ) } }
pub struct Solution {} /// LeetCode Monthly Challenge problem for February 22nd, 2021. impl Solution { /// Given a string, s, and a vector of strings, d, returns the longest /// string in d that can be formed from s with zero or more deletions. /// If there are two or more possible results, returns the smallest /// lexicographical word. /// /// # Arguments /// * s - The base string to form words with. /// * d - A vector of strings to form from s. /// /// # Examples: /// ``` /// # use crate::longest_word_in_dictionary::Solution; /// let ex_one = Solution::find_longest_word( /// String::from("abpcplea"), /// vec!["ale".to_string(), "apple".to_string(), "monkey".to_string(), "plea".to_string()], /// ); /// /// let ex_two = Solution::find_longest_word( /// String::from("abpcplea"), /// vec!["a".to_string(), "b".to_string(), "c".to_string()], /// ); /// /// assert_eq!(ex_one, "apple"); /// assert_eq!(ex_two, "a"); /// ``` /// /// # Constraints /// * All the strings in the input will only contain lowercase letters. /// * The size of d won't exceed 1,000. /// * The length of all the strings in the input won't exceed 1,000. pub fn find_longest_word(s: String, d: Vec<String>) -> String { let mut res = String::new(); for word in d { let mut word_iter = word.chars(); let mut w = word_iter.next(); let mut start_iter = s.chars(); let mut st = start_iter.next(); while w.is_some() && st.is_some() { if w == st { w = word_iter.next(); } st = start_iter.next(); } if w == None { if res.len() < word.len() { res = word; } else if res.len() == word.len() { res = res.min(word); } } } res } } #[cfg(test)] mod tests { use super::*; #[test] fn test_find_longest_word() { assert_eq!( Solution::find_longest_word( String::from("abpcplea"), vec!["ale".to_string(), "apple".to_string(), "monkey".to_string(), "plea".to_string()], ), "apple", ); assert_eq!( Solution::find_longest_word( String::from("abpcplea"), vec!["a".to_string(), "b".to_string(), "c".to_string()], ), "a", ); assert_eq!( Solution::find_longest_word( String::from("a"), vec!["b".to_string()], ), "", ); assert_eq!( Solution::find_longest_word( String::from("aewfafwafjlwajflwajflwafj"), vec![ "apple".to_string(), "ewaf".to_string(), "awefawfwaf".to_string(), "awef".to_string(), "awefe".to_string(), "ewafeffewafewf".to_string(), ], ), "ewaf", ); } }
use crate::fnmatch::fnmatch; use std::fs::{self, DirEntry}; use std::path::{Component, Path, PathBuf, MAIN_SEPARATOR}; /// A directory entry found in a walk paired with pattern matched substrings. /// /// This is a pair of a `std::fs::DirEntry` found while the walk and a vector /// of the substrings. pub struct Match { pub dir_entry: DirEntry, pub matched_parts: Vec<String>, } impl Match { pub fn path(&self) -> PathBuf { //TODO: Should we return a ref? self.dir_entry.path() } } /// Returns the directory entries which matched the given pattern. /// /// This function recursively search directory tree for entries matching the /// given pattern. While this function walks the directory tree, it remembers /// which part of the path corresponds to which wildcard in the pattern. /// /// Note that this function expects the current directory is available. /// In that case, this function fails. pub fn walk<P: AsRef<Path>>(dir: P, pattern: &str) -> Result<Vec<Match>, String> { let dir = dir.as_ref(); if !dir.is_absolute() { return Err(format!( "needs an absolute directory path: {}", dir.to_string_lossy() )); } let mut matches: Vec<Match> = Vec::new(); let mut matched_parts: Vec<String> = Vec::new(); let patterns: Vec<Component> = Path::new(pattern).components().collect(); walk1(dir, &patterns[..], &mut matches, &mut matched_parts)?; Ok(matches) } pub fn walk1( dir: &Path, patterns: &[Component], matches: &mut Vec<Match>, matched_parts: &mut Vec<String>, ) -> Result<(), String> { assert!(dir.is_dir()); assert!(!patterns.is_empty()); if patterns.is_empty() { return Ok(()); } // Match directories match patterns[0] { Component::Prefix(p) => { // Reset the curdir to the path let curdir = p.as_os_str(); let curdir = PathBuf::from(curdir); walk1(&curdir, &patterns[1..], matches, matched_parts) } Component::RootDir => { // Move to the root let root = MAIN_SEPARATOR.to_string(); let root = PathBuf::from(root); walk1(root.as_path(), &patterns[1..], matches, matched_parts) } Component::ParentDir => { // Move to the parent let parent = dir.parent().unwrap(); //TODO: Handle error walk1(parent, &patterns[1..], matches, matched_parts) } Component::CurDir => { // Ignore the path component walk1(dir, &patterns[1..], matches, matched_parts) } Component::Normal(pattern) => { // Move into the matched sub-directories let entry_iter = match fs::read_dir(dir) { Err(err) => { return Err(format!( "fs::read_dir() failed: dir=\"{}\", error=\"{}\"", dir.to_str().unwrap(), err )) } Ok(iter) => iter, }; // Search entries of which name matches the pattern for maybe_entry in entry_iter { // Acquire the entry let entry = match maybe_entry { Err(err) => return Err(format!("failed to get a directory entry: {}", err)), //TODO: Test this Ok(entry) => entry, }; // Match its name let fname = entry.file_name(); let pattern = pattern.to_str().unwrap(); if let Some(mut m) = fnmatch(pattern, fname.to_str().unwrap()) { // It matched, then query its metadata let file_type = match entry.path().metadata() { Err(err) => { return Err(format!( "failed to get metadata of {:?}: {}", entry.path().to_str().unwrap_or("<UNKNOWN>"), err )) } Ok(v) => v.file_type(), }; // Distinguish and switch procedure according to its type let mut matched_parts = matched_parts.clone(); matched_parts.append(&mut m); if file_type.is_dir() { let subdir = dir.join(fname); if 1 < patterns.len() { // Walk into the found sub directory let patterns_ = &patterns[1..]; walk1(subdir.as_path(), patterns_, matches, &mut matched_parts)?; } else { // Found a matched directory as a leaf; store the path matches.push(Match { dir_entry: entry, matched_parts, }); } } else { // Found a file; store the path only if it matched the last pattern (leaf) if patterns.len() <= 1 { matches.push(Match { dir_entry: entry, matched_parts: matched_parts.clone(), }); } } } } Ok(()) } } } #[cfg(test)] mod tests { use super::*; use function_name::named; mod walk { use super::*; fn setup(id: &str) { let curdir = std::env::current_dir().unwrap(); let _ = fs::create_dir(curdir.join("temp")); let _ = fs::remove_dir_all(curdir.join(&format!("temp/{}", id))); for dir1 in ["foo", "bar", "baz"].iter() { for dir2 in ["foo", "bar", "baz"].iter() { let _ = fs::create_dir_all(Path::new(&format!("temp/{}/{}/{}", id, dir1, dir2))); for fname in ["foo", "bar", "baz"].iter() { let path: String = format!("temp/{}/{}/{}/{}", id, dir1, dir2, fname); fs::write(Path::new(&path), path.as_bytes()).unwrap(); } } } } fn new_setup(id: &str, prereq_dirs: Vec<&str>, prereq_files: Vec<&str>) -> PathBuf { // Prepare working directory let mut workdir = std::env::current_dir().unwrap(); workdir.push("temp"); workdir.push(id); let _ = fs::remove_dir_all(workdir.as_path()); fs::create_dir_all(workdir.as_path()).unwrap(); // Create directories and files for the test for dirpath in prereq_dirs.iter() { fs::create_dir_all(Path::join(workdir.as_path(), dirpath)).unwrap(); } for filepath in prereq_files.iter() { fs::write(Path::join(workdir.as_path(), filepath), filepath.as_bytes()).unwrap(); } return workdir; } #[test] fn non_absolute_search_root() { let result = walk(".", "*"); assert!(result.is_err()); let err = result.err().unwrap(); assert!(err.contains("needs an absolute directory path")); } #[named] #[test] fn no_specials() { setup(function_name!()); let curdir = std::env::current_dir().unwrap(); let matches = walk(curdir.join("temp/no_specials"), "foo/bar/baz").unwrap(); assert_eq!(matches.len(), 1); assert_eq!( matches[0].path(), curdir.join("temp/no_specials/foo/bar/baz") ); assert_eq!(matches[0].matched_parts, Vec::<String>::new()); } #[named] #[test] fn question() { setup(function_name!()); let curdir = std::env::current_dir().unwrap(); let mut matches = walk(curdir.join("temp/question"), "ba?/ba?/ba?").unwrap(); assert_eq!(matches.len(), 8); matches.sort_by(|a, b| a.path().cmp(&b.path())); let paths: Vec<_> = matches.iter().map(|m| m.path()).collect(); assert_eq!( paths, vec![ curdir.join("temp/question/bar/bar/bar"), curdir.join("temp/question/bar/bar/baz"), curdir.join("temp/question/bar/baz/bar"), curdir.join("temp/question/bar/baz/baz"), curdir.join("temp/question/baz/bar/bar"), curdir.join("temp/question/baz/bar/baz"), curdir.join("temp/question/baz/baz/bar"), curdir.join("temp/question/baz/baz/baz"), ] ); let patterns: Vec<_> = matches .iter() .map(|x| { x.matched_parts .iter() .fold("".to_string(), |acc, x| acc + "." + x) }) .collect(); assert_eq!( patterns, vec![ String::from(".r.r.r"), String::from(".r.r.z"), String::from(".r.z.r"), String::from(".r.z.z"), String::from(".z.r.r"), String::from(".z.r.z"), String::from(".z.z.r"), String::from(".z.z.z"), ] ); } #[named] #[test] fn star() { setup(function_name!()); let curdir = std::env::current_dir().unwrap(); let mut matches = walk(curdir.join("temp/star"), "b*/b*/b*").unwrap(); assert_eq!(matches.len(), 8); matches.sort_by(|a, b| a.path().cmp(&b.path())); let paths: Vec<_> = matches.iter().map(|x| x.path()).collect(); assert_eq!( paths, vec![ curdir.join("temp/star/bar/bar/bar"), curdir.join("temp/star/bar/bar/baz"), curdir.join("temp/star/bar/baz/bar"), curdir.join("temp/star/bar/baz/baz"), curdir.join("temp/star/baz/bar/bar"), curdir.join("temp/star/baz/bar/baz"), curdir.join("temp/star/baz/baz/bar"), curdir.join("temp/star/baz/baz/baz"), ] ); let patterns: Vec<_> = matches .iter() .map(|x| { x.matched_parts .iter() .fold("".to_string(), |acc, x| acc + "." + x) }) .collect(); assert_eq!( patterns, vec![ String::from(".ar.ar.ar"), String::from(".ar.ar.az"), String::from(".ar.az.ar"), String::from(".ar.az.az"), String::from(".az.ar.ar"), String::from(".az.ar.az"), String::from(".az.az.ar"), String::from(".az.az.az"), ] ); } #[named] #[test] fn issue17() { let prereq_dirs: Vec<&str> = vec![]; let prereq_files = vec!["foo"]; let workdir = new_setup(function_name!(), prereq_dirs, prereq_files); // pmv should not misrecognize "foo" as a directory walk(workdir, "foo/bar").unwrap(); } } }
// Generated from crates/unflow-parser/src/grammar/Design.g4 by ANTLR 4.8 #![allow(dead_code)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #![allow(nonstandard_style)] #![allow(unused_imports)] #![allow(unused_mut)] use antlr_rust::PredictionContextCache; use antlr_rust::parser::{Parser, BaseParser, ParserRecog, ParserNodeType}; use antlr_rust::token_stream::TokenStream; use antlr_rust::TokenSource; use antlr_rust::parser_atn_simulator::ParserATNSimulator; use antlr_rust::errors::*; use antlr_rust::rule_context::{BaseRuleContext, CustomRuleContext, RuleContext}; use antlr_rust::recognizer::{Recognizer,Actions}; use antlr_rust::atn_deserializer::ATNDeserializer; use antlr_rust::dfa::DFA; use antlr_rust::atn::{ATN, INVALID_ALT}; use antlr_rust::error_strategy::{ErrorStrategy, DefaultErrorStrategy}; use antlr_rust::parser_rule_context::{BaseParserRuleContext, ParserRuleContext,cast,cast_mut}; use antlr_rust::tree::*; use antlr_rust::token::{TOKEN_EOF,OwningToken,Token}; use antlr_rust::int_stream::EOF; use antlr_rust::vocabulary::{Vocabulary,VocabularyImpl}; use antlr_rust::token_factory::{CommonTokenFactory,TokenFactory, TokenAware}; use super::designlistener::*; use super::designvisitor::*; use antlr_rust::lazy_static; use antlr_rust::{TidAble,TidExt}; use std::marker::PhantomData; use std::sync::Arc; use std::rc::Rc; use std::convert::TryFrom; use std::cell::RefCell; use std::ops::{DerefMut, Deref}; use std::borrow::{Borrow,BorrowMut}; use std::any::{Any,TypeId}; pub const T__0:isize=1; pub const T__1:isize=2; pub const T__2:isize=3; pub const T__3:isize=4; pub const T__4:isize=5; pub const T__5:isize=6; pub const T__6:isize=7; pub const REPEAT:isize=8; pub const GOTO_KEY:isize=9; pub const SHOW_KEY:isize=10; pub const FLOW:isize=11; pub const SEE:isize=12; pub const DO:isize=13; pub const REACT:isize=14; pub const WITHTEXT:isize=15; pub const ANIMATE:isize=16; pub const PAGE:isize=17; pub const LIBRARY:isize=18; pub const COMPONENT:isize=19; pub const LAYOUT:isize=20; pub const POSITION:isize=21; pub const STYLE:isize=22; pub const STRING_LITERAL:isize=23; pub const LPAREN:isize=24; pub const RPAREN:isize=25; pub const LBRACE:isize=26; pub const RBRACE:isize=27; pub const LBRACK:isize=28; pub const RBRACK:isize=29; pub const Quote:isize=30; pub const SingleQuote:isize=31; pub const COLON:isize=32; pub const DOT:isize=33; pub const COMMA:isize=34; pub const LETTER:isize=35; pub const IDENTIFIER:isize=36; pub const DIGITS:isize=37; pub const DIGITS_IDENTIFIER:isize=38; pub const DECIMAL_LITERAL:isize=39; pub const FLOAT_LITERAL:isize=40; pub const WS:isize=41; pub const NL:isize=42; pub const NEWLINE:isize=43; pub const COMMENT:isize=44; pub const LINE_COMMENT:isize=45; pub const RULE_start:usize = 0; pub const RULE_declarations:usize = 1; pub const RULE_config_decl:usize = 2; pub const RULE_config_key:usize = 3; pub const RULE_config_value:usize = 4; pub const RULE_unit:usize = 5; pub const RULE_flow_decl:usize = 6; pub const RULE_interaction_decl:usize = 7; pub const RULE_see_decl:usize = 8; pub const RULE_do_decl:usize = 9; pub const RULE_react_decl:usize = 10; pub const RULE_animate_decl:usize = 11; pub const RULE_react_action:usize = 12; pub const RULE_goto_action:usize = 13; pub const RULE_show_action:usize = 14; pub const RULE_action_name:usize = 15; pub const RULE_component_name:usize = 16; pub const RULE_scene_name:usize = 17; pub const RULE_animate_name:usize = 18; pub const RULE_page_decl:usize = 19; pub const RULE_component_decl:usize = 20; pub const RULE_component_body_decl:usize = 21; pub const RULE_layout_decl:usize = 22; pub const RULE_flex_child:usize = 23; pub const RULE_component_use_decl:usize = 24; pub const RULE_component_parameter:usize = 25; pub const RULE_style_decl:usize = 26; pub const RULE_style_name:usize = 27; pub const RULE_style_body:usize = 28; pub const RULE_library_name:usize = 29; pub const RULE_library_decl:usize = 30; pub const RULE_library_exp:usize = 31; pub const RULE_key_value:usize = 32; pub const RULE_preset_key:usize = 33; pub const RULE_preset_value:usize = 34; pub const RULE_preset_array:usize = 35; pub const RULE_preset_call:usize = 36; pub const ruleNames: [&'static str; 37] = [ "start", "declarations", "config_decl", "config_key", "config_value", "unit", "flow_decl", "interaction_decl", "see_decl", "do_decl", "react_decl", "animate_decl", "react_action", "goto_action", "show_action", "action_name", "component_name", "scene_name", "animate_name", "page_decl", "component_decl", "component_body_decl", "layout_decl", "flex_child", "component_use_decl", "component_parameter", "style_decl", "style_name", "style_body", "library_name", "library_decl", "library_exp", "key_value", "preset_key", "preset_value", "preset_array", "preset_call" ]; pub const _LITERAL_NAMES: [Option<&'static str>;35] = [ None, Some("'rem'"), Some("'px'"), Some("'em'"), Some("'-'"), Some("'|'"), Some("';'"), Some("'='"), Some("'repeat'"), None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, Some("'('"), Some("')'"), Some("'{'"), Some("'}'"), Some("'['"), Some("']'"), Some("'\"'"), Some("'''"), Some("':'"), Some("'.'"), Some("','") ]; pub const _SYMBOLIC_NAMES: [Option<&'static str>;46] = [ None, None, None, None, None, None, None, None, Some("REPEAT"), Some("GOTO_KEY"), Some("SHOW_KEY"), Some("FLOW"), Some("SEE"), Some("DO"), Some("REACT"), Some("WITHTEXT"), Some("ANIMATE"), Some("PAGE"), Some("LIBRARY"), Some("COMPONENT"), Some("LAYOUT"), Some("POSITION"), Some("STYLE"), Some("STRING_LITERAL"), Some("LPAREN"), Some("RPAREN"), Some("LBRACE"), Some("RBRACE"), Some("LBRACK"), Some("RBRACK"), Some("Quote"), Some("SingleQuote"), Some("COLON"), Some("DOT"), Some("COMMA"), Some("LETTER"), Some("IDENTIFIER"), Some("DIGITS"), Some("DIGITS_IDENTIFIER"), Some("DECIMAL_LITERAL"), Some("FLOAT_LITERAL"), Some("WS"), Some("NL"), Some("NEWLINE"), Some("COMMENT"), Some("LINE_COMMENT") ]; lazy_static!{ static ref _shared_context_cache: Arc<PredictionContextCache> = Arc::new(PredictionContextCache::new()); static ref VOCABULARY: Box<dyn Vocabulary> = Box::new(VocabularyImpl::new(_LITERAL_NAMES.iter(), _SYMBOLIC_NAMES.iter(), None)); } type BaseParserType<'input, I> = BaseParser<'input,DesignParserExt, I, DesignParserContextType , dyn DesignListener<'input> + 'input >; type TokenType<'input> = <LocalTokenFactory<'input> as TokenFactory<'input>>::Tok; pub type LocalTokenFactory<'input> = antlr_rust::token_factory::ArenaCommonFactory<'input>; pub type DesignTreeWalker<'input,'a> = ParseTreeWalker<'input, 'a, DesignParserContextType , dyn DesignListener<'input> + 'a>; /// Parser for Design grammar pub struct DesignParser<'input,I,H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { base:BaseParserType<'input,I>, interpreter:Arc<ParserATNSimulator>, _shared_context_cache: Box<PredictionContextCache>, pub err_handler: H, } impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn get_serialized_atn() -> &'static str { _serializedATN } pub fn set_error_strategy(&mut self, strategy: H) { self.err_handler = strategy } pub fn with_strategy(input: I, strategy: H) -> Self { antlr_rust::recognizer::check_version("0","2"); let interpreter = Arc::new(ParserATNSimulator::new( _ATN.clone(), _decision_to_DFA.clone(), _shared_context_cache.clone(), )); Self { base: BaseParser::new_base_parser( input, Arc::clone(&interpreter), DesignParserExt{ } ), interpreter, _shared_context_cache: Box::new(PredictionContextCache::new()), err_handler: strategy, } } } type DynStrategy<'input,I> = Box<dyn ErrorStrategy<'input,BaseParserType<'input,I>> + 'input>; impl<'input, I> DesignParser<'input, I, DynStrategy<'input,I>> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, { pub fn with_dyn_strategy(input: I) -> Self{ Self::with_strategy(input,Box::new(DefaultErrorStrategy::new())) } } impl<'input, I> DesignParser<'input, I, DefaultErrorStrategy<'input,DesignParserContextType>> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, { pub fn new(input: I) -> Self{ Self::with_strategy(input,DefaultErrorStrategy::new()) } } /// Trait for monomorphized trait object that corresponds to the nodes of parse tree generated for DesignParser pub trait DesignParserContext<'input>: for<'x> Listenable<dyn DesignListener<'input> + 'x > + for<'x> Visitable<dyn DesignVisitor<'input> + 'x > + ParserRuleContext<'input, TF=LocalTokenFactory<'input>, Ctx=DesignParserContextType> {} impl<'input, 'x, T> VisitableDyn<T> for dyn DesignParserContext<'input> + 'input where T: DesignVisitor<'input> + 'x, { fn accept_dyn(&self, visitor: &mut T) { self.accept(visitor as &mut (dyn DesignVisitor<'input> + 'x)) } } impl<'input> DesignParserContext<'input> for TerminalNode<'input,DesignParserContextType> {} impl<'input> DesignParserContext<'input> for ErrorNode<'input,DesignParserContextType> {} #[antlr_rust::impl_tid] impl<'input> antlr_rust::TidAble<'input> for dyn DesignParserContext<'input> + 'input{} #[antlr_rust::impl_tid] impl<'input> antlr_rust::TidAble<'input> for dyn DesignListener<'input> + 'input{} pub struct DesignParserContextType; antlr_rust::type_id!{DesignParserContextType} impl<'input> ParserNodeType<'input> for DesignParserContextType{ type TF = LocalTokenFactory<'input>; type Type = dyn DesignParserContext<'input> + 'input; } impl<'input, I, H> Deref for DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { type Target = BaseParserType<'input,I>; fn deref(&self) -> &Self::Target { &self.base } } impl<'input, I, H> DerefMut for DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.base } } pub struct DesignParserExt{ } impl DesignParserExt{ } impl<'input> TokenAware<'input> for DesignParserExt{ type TF = LocalTokenFactory<'input>; } impl<'input,I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>> ParserRecog<'input, BaseParserType<'input,I>> for DesignParserExt{} impl<'input,I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>> Actions<'input, BaseParserType<'input,I>> for DesignParserExt{ fn get_grammar_file_name(&self) -> & str{ "Design.g4"} fn get_rule_names(&self) -> &[& str] {&ruleNames} fn get_vocabulary(&self) -> &dyn Vocabulary { &**VOCABULARY } } //------------------- start ---------------- pub type StartContextAll<'input> = StartContext<'input>; pub type StartContext<'input> = BaseParserRuleContext<'input,StartContextExt<'input>>; #[derive(Clone)] pub struct StartContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for StartContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for StartContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_start(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_start(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for StartContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_start(self); } } impl<'input> CustomRuleContext<'input> for StartContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_start } //fn type_rule_index() -> usize where Self: Sized { RULE_start } } antlr_rust::type_id!{StartContextExt<'a>} impl<'input> StartContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<StartContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,StartContextExt{ ph:PhantomData }), ) } } pub trait StartContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<StartContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token EOF /// Returns `None` if there is no child corresponding to token EOF fn EOF(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(EOF, 0) } fn declarations_all(&self) -> Vec<Rc<DeclarationsContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn declarations(&self, i: usize) -> Option<Rc<DeclarationsContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> StartContextAttrs<'input> for StartContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn start(&mut self,) -> Result<Rc<StartContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = StartContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 0, RULE_start); let mut _localctx: Rc<StartContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(77); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while (((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << FLOW) | (1usize << PAGE) | (1usize << LIBRARY) | (1usize << COMPONENT) | (1usize << LAYOUT) | (1usize << STYLE) | (1usize << IDENTIFIER))) != 0) { { { /*InvokeRule declarations*/ recog.base.set_state(74); recog.declarations()?; } } recog.base.set_state(79); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(80); recog.base.match_token(EOF,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- declarations ---------------- pub type DeclarationsContextAll<'input> = DeclarationsContext<'input>; pub type DeclarationsContext<'input> = BaseParserRuleContext<'input,DeclarationsContextExt<'input>>; #[derive(Clone)] pub struct DeclarationsContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for DeclarationsContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for DeclarationsContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_declarations(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_declarations(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for DeclarationsContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_declarations(self); } } impl<'input> CustomRuleContext<'input> for DeclarationsContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_declarations } //fn type_rule_index() -> usize where Self: Sized { RULE_declarations } } antlr_rust::type_id!{DeclarationsContextExt<'a>} impl<'input> DeclarationsContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<DeclarationsContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,DeclarationsContextExt{ ph:PhantomData }), ) } } pub trait DeclarationsContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<DeclarationsContextExt<'input>>{ fn config_decl(&self) -> Option<Rc<Config_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn flow_decl(&self) -> Option<Rc<Flow_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn page_decl(&self) -> Option<Rc<Page_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn style_decl(&self) -> Option<Rc<Style_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn component_decl(&self) -> Option<Rc<Component_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn library_decl(&self) -> Option<Rc<Library_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn layout_decl(&self) -> Option<Rc<Layout_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> DeclarationsContextAttrs<'input> for DeclarationsContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn declarations(&mut self,) -> Result<Rc<DeclarationsContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = DeclarationsContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 2, RULE_declarations); let mut _localctx: Rc<DeclarationsContextAll> = _localctx; let result: Result<(), ANTLRError> = try { recog.base.set_state(89); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { IDENTIFIER => { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule config_decl*/ recog.base.set_state(82); recog.config_decl()?; } } FLOW => { //recog.base.enter_outer_alt(_localctx.clone(), 2); recog.base.enter_outer_alt(None, 2); { /*InvokeRule flow_decl*/ recog.base.set_state(83); recog.flow_decl()?; } } PAGE => { //recog.base.enter_outer_alt(_localctx.clone(), 3); recog.base.enter_outer_alt(None, 3); { /*InvokeRule page_decl*/ recog.base.set_state(84); recog.page_decl()?; } } STYLE => { //recog.base.enter_outer_alt(_localctx.clone(), 4); recog.base.enter_outer_alt(None, 4); { /*InvokeRule style_decl*/ recog.base.set_state(85); recog.style_decl()?; } } COMPONENT => { //recog.base.enter_outer_alt(_localctx.clone(), 5); recog.base.enter_outer_alt(None, 5); { /*InvokeRule component_decl*/ recog.base.set_state(86); recog.component_decl()?; } } LIBRARY => { //recog.base.enter_outer_alt(_localctx.clone(), 6); recog.base.enter_outer_alt(None, 6); { /*InvokeRule library_decl*/ recog.base.set_state(87); recog.library_decl()?; } } LAYOUT => { //recog.base.enter_outer_alt(_localctx.clone(), 7); recog.base.enter_outer_alt(None, 7); { /*InvokeRule layout_decl*/ recog.base.set_state(88); recog.layout_decl()?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- config_decl ---------------- pub type Config_declContextAll<'input> = Config_declContext<'input>; pub type Config_declContext<'input> = BaseParserRuleContext<'input,Config_declContextExt<'input>>; #[derive(Clone)] pub struct Config_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Config_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Config_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_config_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_config_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Config_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_config_decl(self); } } impl<'input> CustomRuleContext<'input> for Config_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_config_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_config_decl } } antlr_rust::type_id!{Config_declContextExt<'a>} impl<'input> Config_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Config_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Config_declContextExt{ ph:PhantomData }), ) } } pub trait Config_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Config_declContextExt<'input>>{ fn config_key(&self) -> Option<Rc<Config_keyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token COLON /// Returns `None` if there is no child corresponding to token COLON fn COLON(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COLON, 0) } fn config_value(&self) -> Option<Rc<Config_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Config_declContextAttrs<'input> for Config_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn config_decl(&mut self,) -> Result<Rc<Config_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Config_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 4, RULE_config_decl); let mut _localctx: Rc<Config_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule config_key*/ recog.base.set_state(91); recog.config_key()?; recog.base.set_state(92); recog.base.match_token(COLON,&mut recog.err_handler)?; /*InvokeRule config_value*/ recog.base.set_state(93); recog.config_value()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- config_key ---------------- pub type Config_keyContextAll<'input> = Config_keyContext<'input>; pub type Config_keyContext<'input> = BaseParserRuleContext<'input,Config_keyContextExt<'input>>; #[derive(Clone)] pub struct Config_keyContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Config_keyContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Config_keyContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_config_key(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_config_key(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Config_keyContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_config_key(self); } } impl<'input> CustomRuleContext<'input> for Config_keyContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_config_key } //fn type_rule_index() -> usize where Self: Sized { RULE_config_key } } antlr_rust::type_id!{Config_keyContextExt<'a>} impl<'input> Config_keyContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Config_keyContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Config_keyContextExt{ ph:PhantomData }), ) } } pub trait Config_keyContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Config_keyContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Config_keyContextAttrs<'input> for Config_keyContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn config_key(&mut self,) -> Result<Rc<Config_keyContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Config_keyContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 6, RULE_config_key); let mut _localctx: Rc<Config_keyContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(95); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- config_value ---------------- pub type Config_valueContextAll<'input> = Config_valueContext<'input>; pub type Config_valueContext<'input> = BaseParserRuleContext<'input,Config_valueContextExt<'input>>; #[derive(Clone)] pub struct Config_valueContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Config_valueContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Config_valueContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_config_value(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_config_value(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Config_valueContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_config_value(self); } } impl<'input> CustomRuleContext<'input> for Config_valueContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_config_value } //fn type_rule_index() -> usize where Self: Sized { RULE_config_value } } antlr_rust::type_id!{Config_valueContextExt<'a>} impl<'input> Config_valueContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Config_valueContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Config_valueContextExt{ ph:PhantomData }), ) } } pub trait Config_valueContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Config_valueContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token DIGITS_IDENTIFIER /// Returns `None` if there is no child corresponding to token DIGITS_IDENTIFIER fn DIGITS_IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DIGITS_IDENTIFIER, 0) } fn unit(&self) -> Option<Rc<UnitContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token DECIMAL_LITERAL /// Returns `None` if there is no child corresponding to token DECIMAL_LITERAL fn DECIMAL_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DECIMAL_LITERAL, 0) } /// Retrieves first TerminalNode corresponding to token FLOAT_LITERAL /// Returns `None` if there is no child corresponding to token FLOAT_LITERAL fn FLOAT_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(FLOAT_LITERAL, 0) } /// Retrieves all `TerminalNode`s corresponding to token IDENTIFIER in current rule fn IDENTIFIER_all(&self) -> Vec<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.children_of_type() } /// Retrieves 'i's TerminalNode corresponding to token IDENTIFIER, starting from 0. /// Returns `None` if number of children corresponding to token IDENTIFIER is less or equal than `i`. fn IDENTIFIER(&self, i: usize) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, i) } /// Retrieves first TerminalNode corresponding to token COMMA /// Returns `None` if there is no child corresponding to token COMMA fn COMMA(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COMMA, 0) } /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } } impl<'input> Config_valueContextAttrs<'input> for Config_valueContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn config_value(&mut self,) -> Result<Rc<Config_valueContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Config_valueContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 8, RULE_config_value); let mut _localctx: Rc<Config_valueContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { recog.base.set_state(115); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { DIGITS_IDENTIFIER => { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(97); recog.base.match_token(DIGITS_IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(99); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if (((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << T__0) | (1usize << T__1) | (1usize << T__2))) != 0) { { /*InvokeRule unit*/ recog.base.set_state(98); recog.unit()?; } } } } DECIMAL_LITERAL => { //recog.base.enter_outer_alt(_localctx.clone(), 2); recog.base.enter_outer_alt(None, 2); { recog.base.set_state(101); recog.base.match_token(DECIMAL_LITERAL,&mut recog.err_handler)?; recog.base.set_state(103); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if (((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << T__0) | (1usize << T__1) | (1usize << T__2))) != 0) { { /*InvokeRule unit*/ recog.base.set_state(102); recog.unit()?; } } } } FLOAT_LITERAL => { //recog.base.enter_outer_alt(_localctx.clone(), 3); recog.base.enter_outer_alt(None, 3); { recog.base.set_state(105); recog.base.match_token(FLOAT_LITERAL,&mut recog.err_handler)?; recog.base.set_state(107); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if (((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << T__0) | (1usize << T__1) | (1usize << T__2))) != 0) { { /*InvokeRule unit*/ recog.base.set_state(106); recog.unit()?; } } } } IDENTIFIER => { //recog.base.enter_outer_alt(_localctx.clone(), 4); recog.base.enter_outer_alt(None, 4); { recog.base.set_state(109); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(112); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if _la==COMMA { { recog.base.set_state(110); recog.base.match_token(COMMA,&mut recog.err_handler)?; recog.base.set_state(111); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } } } } STRING_LITERAL => { //recog.base.enter_outer_alt(_localctx.clone(), 5); recog.base.enter_outer_alt(None, 5); { recog.base.set_state(114); recog.base.match_token(STRING_LITERAL,&mut recog.err_handler)?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- unit ---------------- pub type UnitContextAll<'input> = UnitContext<'input>; pub type UnitContext<'input> = BaseParserRuleContext<'input,UnitContextExt<'input>>; #[derive(Clone)] pub struct UnitContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for UnitContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for UnitContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_unit(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_unit(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for UnitContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_unit(self); } } impl<'input> CustomRuleContext<'input> for UnitContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_unit } //fn type_rule_index() -> usize where Self: Sized { RULE_unit } } antlr_rust::type_id!{UnitContextExt<'a>} impl<'input> UnitContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<UnitContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,UnitContextExt{ ph:PhantomData }), ) } } pub trait UnitContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<UnitContextExt<'input>>{ } impl<'input> UnitContextAttrs<'input> for UnitContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn unit(&mut self,) -> Result<Rc<UnitContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = UnitContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 10, RULE_unit); let mut _localctx: Rc<UnitContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(117); _la = recog.base.input.la(1); if { !((((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << T__0) | (1usize << T__1) | (1usize << T__2))) != 0)) } { recog.err_handler.recover_inline(&mut recog.base)?; } else { if recog.base.input.la(1)==TOKEN_EOF { recog.base.matched_eof = true }; recog.err_handler.report_match(&mut recog.base); recog.base.consume(&mut recog.err_handler); } } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- flow_decl ---------------- pub type Flow_declContextAll<'input> = Flow_declContext<'input>; pub type Flow_declContext<'input> = BaseParserRuleContext<'input,Flow_declContextExt<'input>>; #[derive(Clone)] pub struct Flow_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Flow_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Flow_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_flow_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_flow_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Flow_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_flow_decl(self); } } impl<'input> CustomRuleContext<'input> for Flow_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_flow_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_flow_decl } } antlr_rust::type_id!{Flow_declContextExt<'a>} impl<'input> Flow_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Flow_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Flow_declContextExt{ ph:PhantomData }), ) } } pub trait Flow_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Flow_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token FLOW /// Returns `None` if there is no child corresponding to token FLOW fn FLOW(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(FLOW, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn interaction_decl_all(&self) -> Vec<Rc<Interaction_declContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn interaction_decl(&self, i: usize) -> Option<Rc<Interaction_declContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Flow_declContextAttrs<'input> for Flow_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn flow_decl(&mut self,) -> Result<Rc<Flow_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Flow_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 12, RULE_flow_decl); let mut _localctx: Rc<Flow_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(119); recog.base.match_token(FLOW,&mut recog.err_handler)?; recog.base.set_state(120); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(121); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(125); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while (((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << SEE) | (1usize << DO) | (1usize << REACT))) != 0) { { { /*InvokeRule interaction_decl*/ recog.base.set_state(122); recog.interaction_decl()?; } } recog.base.set_state(127); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(128); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- interaction_decl ---------------- pub type Interaction_declContextAll<'input> = Interaction_declContext<'input>; pub type Interaction_declContext<'input> = BaseParserRuleContext<'input,Interaction_declContextExt<'input>>; #[derive(Clone)] pub struct Interaction_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Interaction_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Interaction_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_interaction_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_interaction_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Interaction_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_interaction_decl(self); } } impl<'input> CustomRuleContext<'input> for Interaction_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_interaction_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_interaction_decl } } antlr_rust::type_id!{Interaction_declContextExt<'a>} impl<'input> Interaction_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Interaction_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Interaction_declContextExt{ ph:PhantomData }), ) } } pub trait Interaction_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Interaction_declContextExt<'input>>{ fn see_decl(&self) -> Option<Rc<See_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn do_decl(&self) -> Option<Rc<Do_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn react_decl(&self) -> Option<Rc<React_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Interaction_declContextAttrs<'input> for Interaction_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn interaction_decl(&mut self,) -> Result<Rc<Interaction_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Interaction_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 14, RULE_interaction_decl); let mut _localctx: Rc<Interaction_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { recog.base.set_state(133); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { SEE => { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule see_decl*/ recog.base.set_state(130); recog.see_decl()?; } } DO => { //recog.base.enter_outer_alt(_localctx.clone(), 2); recog.base.enter_outer_alt(None, 2); { /*InvokeRule do_decl*/ recog.base.set_state(131); recog.do_decl()?; } } REACT => { //recog.base.enter_outer_alt(_localctx.clone(), 3); recog.base.enter_outer_alt(None, 3); { /*InvokeRule react_decl*/ recog.base.set_state(132); recog.react_decl()?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- see_decl ---------------- pub type See_declContextAll<'input> = See_declContext<'input>; pub type See_declContext<'input> = BaseParserRuleContext<'input,See_declContextExt<'input>>; #[derive(Clone)] pub struct See_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for See_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for See_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_see_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_see_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for See_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_see_decl(self); } } impl<'input> CustomRuleContext<'input> for See_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_see_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_see_decl } } antlr_rust::type_id!{See_declContextExt<'a>} impl<'input> See_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<See_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,See_declContextExt{ ph:PhantomData }), ) } } pub trait See_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<See_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token SEE /// Returns `None` if there is no child corresponding to token SEE fn SEE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(SEE, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } /// Retrieves first TerminalNode corresponding to token DOT /// Returns `None` if there is no child corresponding to token DOT fn DOT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DOT, 0) } fn component_name(&self) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> See_declContextAttrs<'input> for See_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn see_decl(&mut self,) -> Result<Rc<See_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = See_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 16, RULE_see_decl); let mut _localctx: Rc<See_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(135); recog.base.match_token(SEE,&mut recog.err_handler)?; recog.base.set_state(140); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { IDENTIFIER => { { recog.base.set_state(136); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } } STRING_LITERAL => { { recog.base.set_state(137); recog.base.match_token(STRING_LITERAL,&mut recog.err_handler)?; recog.base.set_state(138); recog.base.match_token(DOT,&mut recog.err_handler)?; /*InvokeRule component_name*/ recog.base.set_state(139); recog.component_name()?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- do_decl ---------------- pub type Do_declContextAll<'input> = Do_declContext<'input>; pub type Do_declContext<'input> = BaseParserRuleContext<'input,Do_declContextExt<'input>>; #[derive(Clone)] pub struct Do_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Do_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Do_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_do_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_do_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Do_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_do_decl(self); } } impl<'input> CustomRuleContext<'input> for Do_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_do_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_do_decl } } antlr_rust::type_id!{Do_declContextExt<'a>} impl<'input> Do_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Do_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Do_declContextExt{ ph:PhantomData }), ) } } pub trait Do_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Do_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token DO /// Returns `None` if there is no child corresponding to token DO fn DO(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DO, 0) } /// Retrieves first TerminalNode corresponding to token LBRACK /// Returns `None` if there is no child corresponding to token LBRACK fn LBRACK(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACK, 0) } fn action_name(&self) -> Option<Rc<Action_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token RBRACK /// Returns `None` if there is no child corresponding to token RBRACK fn RBRACK(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACK, 0) } /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } /// Retrieves first TerminalNode corresponding to token DOT /// Returns `None` if there is no child corresponding to token DOT fn DOT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DOT, 0) } fn component_name(&self) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Do_declContextAttrs<'input> for Do_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn do_decl(&mut self,) -> Result<Rc<Do_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Do_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 18, RULE_do_decl); let mut _localctx: Rc<Do_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(142); recog.base.match_token(DO,&mut recog.err_handler)?; recog.base.set_state(143); recog.base.match_token(LBRACK,&mut recog.err_handler)?; /*InvokeRule action_name*/ recog.base.set_state(144); recog.action_name()?; recog.base.set_state(145); recog.base.match_token(RBRACK,&mut recog.err_handler)?; recog.base.set_state(146); recog.base.match_token(STRING_LITERAL,&mut recog.err_handler)?; recog.base.set_state(147); recog.base.match_token(DOT,&mut recog.err_handler)?; /*InvokeRule component_name*/ recog.base.set_state(148); recog.component_name()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- react_decl ---------------- pub type React_declContextAll<'input> = React_declContext<'input>; pub type React_declContext<'input> = BaseParserRuleContext<'input,React_declContextExt<'input>>; #[derive(Clone)] pub struct React_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for React_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for React_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_react_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_react_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for React_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_react_decl(self); } } impl<'input> CustomRuleContext<'input> for React_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_react_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_react_decl } } antlr_rust::type_id!{React_declContextExt<'a>} impl<'input> React_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<React_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,React_declContextExt{ ph:PhantomData }), ) } } pub trait React_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<React_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token REACT /// Returns `None` if there is no child corresponding to token REACT fn REACT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(REACT, 0) } /// Retrieves first TerminalNode corresponding to token COLON /// Returns `None` if there is no child corresponding to token COLON fn COLON(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COLON, 0) } fn react_action(&self) -> Option<Rc<React_actionContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn scene_name(&self) -> Option<Rc<Scene_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn animate_decl(&self) -> Option<Rc<Animate_declContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> React_declContextAttrs<'input> for React_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn react_decl(&mut self,) -> Result<Rc<React_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = React_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 20, RULE_react_decl); let mut _localctx: Rc<React_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(150); recog.base.match_token(REACT,&mut recog.err_handler)?; recog.base.set_state(152); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if _la==IDENTIFIER { { /*InvokeRule scene_name*/ recog.base.set_state(151); recog.scene_name()?; } } recog.base.set_state(154); recog.base.match_token(COLON,&mut recog.err_handler)?; /*InvokeRule react_action*/ recog.base.set_state(155); recog.react_action()?; recog.base.set_state(157); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if _la==WITHTEXT { { /*InvokeRule animate_decl*/ recog.base.set_state(156); recog.animate_decl()?; } } } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- animate_decl ---------------- pub type Animate_declContextAll<'input> = Animate_declContext<'input>; pub type Animate_declContext<'input> = BaseParserRuleContext<'input,Animate_declContextExt<'input>>; #[derive(Clone)] pub struct Animate_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Animate_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Animate_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_animate_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_animate_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Animate_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_animate_decl(self); } } impl<'input> CustomRuleContext<'input> for Animate_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_animate_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_animate_decl } } antlr_rust::type_id!{Animate_declContextExt<'a>} impl<'input> Animate_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Animate_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Animate_declContextExt{ ph:PhantomData }), ) } } pub trait Animate_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Animate_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token WITHTEXT /// Returns `None` if there is no child corresponding to token WITHTEXT fn WITHTEXT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(WITHTEXT, 0) } /// Retrieves first TerminalNode corresponding to token ANIMATE /// Returns `None` if there is no child corresponding to token ANIMATE fn ANIMATE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(ANIMATE, 0) } /// Retrieves first TerminalNode corresponding to token LPAREN /// Returns `None` if there is no child corresponding to token LPAREN fn LPAREN(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LPAREN, 0) } fn animate_name(&self) -> Option<Rc<Animate_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token RPAREN /// Returns `None` if there is no child corresponding to token RPAREN fn RPAREN(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RPAREN, 0) } } impl<'input> Animate_declContextAttrs<'input> for Animate_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn animate_decl(&mut self,) -> Result<Rc<Animate_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Animate_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 22, RULE_animate_decl); let mut _localctx: Rc<Animate_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(159); recog.base.match_token(WITHTEXT,&mut recog.err_handler)?; recog.base.set_state(160); recog.base.match_token(ANIMATE,&mut recog.err_handler)?; recog.base.set_state(161); recog.base.match_token(LPAREN,&mut recog.err_handler)?; /*InvokeRule animate_name*/ recog.base.set_state(162); recog.animate_name()?; recog.base.set_state(163); recog.base.match_token(RPAREN,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- react_action ---------------- pub type React_actionContextAll<'input> = React_actionContext<'input>; pub type React_actionContext<'input> = BaseParserRuleContext<'input,React_actionContextExt<'input>>; #[derive(Clone)] pub struct React_actionContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for React_actionContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for React_actionContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_react_action(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_react_action(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for React_actionContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_react_action(self); } } impl<'input> CustomRuleContext<'input> for React_actionContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_react_action } //fn type_rule_index() -> usize where Self: Sized { RULE_react_action } } antlr_rust::type_id!{React_actionContextExt<'a>} impl<'input> React_actionContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<React_actionContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,React_actionContextExt{ ph:PhantomData }), ) } } pub trait React_actionContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<React_actionContextExt<'input>>{ fn goto_action(&self) -> Option<Rc<Goto_actionContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn show_action(&self) -> Option<Rc<Show_actionContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> React_actionContextAttrs<'input> for React_actionContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn react_action(&mut self,) -> Result<Rc<React_actionContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = React_actionContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 24, RULE_react_action); let mut _localctx: Rc<React_actionContextAll> = _localctx; let result: Result<(), ANTLRError> = try { recog.base.set_state(167); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { GOTO_KEY => { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule goto_action*/ recog.base.set_state(165); recog.goto_action()?; } } SHOW_KEY => { //recog.base.enter_outer_alt(_localctx.clone(), 2); recog.base.enter_outer_alt(None, 2); { /*InvokeRule show_action*/ recog.base.set_state(166); recog.show_action()?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- goto_action ---------------- pub type Goto_actionContextAll<'input> = Goto_actionContext<'input>; pub type Goto_actionContext<'input> = BaseParserRuleContext<'input,Goto_actionContextExt<'input>>; #[derive(Clone)] pub struct Goto_actionContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Goto_actionContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Goto_actionContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_goto_action(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_goto_action(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Goto_actionContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_goto_action(self); } } impl<'input> CustomRuleContext<'input> for Goto_actionContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_goto_action } //fn type_rule_index() -> usize where Self: Sized { RULE_goto_action } } antlr_rust::type_id!{Goto_actionContextExt<'a>} impl<'input> Goto_actionContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Goto_actionContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Goto_actionContextExt{ ph:PhantomData }), ) } } pub trait Goto_actionContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Goto_actionContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token GOTO_KEY /// Returns `None` if there is no child corresponding to token GOTO_KEY fn GOTO_KEY(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(GOTO_KEY, 0) } fn component_name(&self) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Goto_actionContextAttrs<'input> for Goto_actionContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn goto_action(&mut self,) -> Result<Rc<Goto_actionContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Goto_actionContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 26, RULE_goto_action); let mut _localctx: Rc<Goto_actionContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(169); recog.base.match_token(GOTO_KEY,&mut recog.err_handler)?; /*InvokeRule component_name*/ recog.base.set_state(170); recog.component_name()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- show_action ---------------- pub type Show_actionContextAll<'input> = Show_actionContext<'input>; pub type Show_actionContext<'input> = BaseParserRuleContext<'input,Show_actionContextExt<'input>>; #[derive(Clone)] pub struct Show_actionContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Show_actionContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Show_actionContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_show_action(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_show_action(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Show_actionContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_show_action(self); } } impl<'input> CustomRuleContext<'input> for Show_actionContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_show_action } //fn type_rule_index() -> usize where Self: Sized { RULE_show_action } } antlr_rust::type_id!{Show_actionContextExt<'a>} impl<'input> Show_actionContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Show_actionContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Show_actionContextExt{ ph:PhantomData }), ) } } pub trait Show_actionContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Show_actionContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token SHOW_KEY /// Returns `None` if there is no child corresponding to token SHOW_KEY fn SHOW_KEY(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(SHOW_KEY, 0) } /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } /// Retrieves first TerminalNode corresponding to token DOT /// Returns `None` if there is no child corresponding to token DOT fn DOT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DOT, 0) } fn component_name(&self) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Show_actionContextAttrs<'input> for Show_actionContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn show_action(&mut self,) -> Result<Rc<Show_actionContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Show_actionContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 28, RULE_show_action); let mut _localctx: Rc<Show_actionContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(172); recog.base.match_token(SHOW_KEY,&mut recog.err_handler)?; recog.base.set_state(173); recog.base.match_token(STRING_LITERAL,&mut recog.err_handler)?; recog.base.set_state(174); recog.base.match_token(DOT,&mut recog.err_handler)?; /*InvokeRule component_name*/ recog.base.set_state(175); recog.component_name()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- action_name ---------------- pub type Action_nameContextAll<'input> = Action_nameContext<'input>; pub type Action_nameContext<'input> = BaseParserRuleContext<'input,Action_nameContextExt<'input>>; #[derive(Clone)] pub struct Action_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Action_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Action_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_action_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_action_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Action_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_action_name(self); } } impl<'input> CustomRuleContext<'input> for Action_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_action_name } //fn type_rule_index() -> usize where Self: Sized { RULE_action_name } } antlr_rust::type_id!{Action_nameContextExt<'a>} impl<'input> Action_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Action_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Action_nameContextExt{ ph:PhantomData }), ) } } pub trait Action_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Action_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Action_nameContextAttrs<'input> for Action_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn action_name(&mut self,) -> Result<Rc<Action_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Action_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 30, RULE_action_name); let mut _localctx: Rc<Action_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(177); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- component_name ---------------- pub type Component_nameContextAll<'input> = Component_nameContext<'input>; pub type Component_nameContext<'input> = BaseParserRuleContext<'input,Component_nameContextExt<'input>>; #[derive(Clone)] pub struct Component_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Component_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_name(self); } } impl<'input> CustomRuleContext<'input> for Component_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_name } //fn type_rule_index() -> usize where Self: Sized { RULE_component_name } } antlr_rust::type_id!{Component_nameContextExt<'a>} impl<'input> Component_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Component_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Component_nameContextExt{ ph:PhantomData }), ) } } pub trait Component_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Component_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Component_nameContextAttrs<'input> for Component_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn component_name(&mut self,) -> Result<Rc<Component_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Component_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 32, RULE_component_name); let mut _localctx: Rc<Component_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(179); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- scene_name ---------------- pub type Scene_nameContextAll<'input> = Scene_nameContext<'input>; pub type Scene_nameContext<'input> = BaseParserRuleContext<'input,Scene_nameContextExt<'input>>; #[derive(Clone)] pub struct Scene_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Scene_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Scene_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_scene_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_scene_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Scene_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_scene_name(self); } } impl<'input> CustomRuleContext<'input> for Scene_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_scene_name } //fn type_rule_index() -> usize where Self: Sized { RULE_scene_name } } antlr_rust::type_id!{Scene_nameContextExt<'a>} impl<'input> Scene_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Scene_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Scene_nameContextExt{ ph:PhantomData }), ) } } pub trait Scene_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Scene_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Scene_nameContextAttrs<'input> for Scene_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn scene_name(&mut self,) -> Result<Rc<Scene_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Scene_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 34, RULE_scene_name); let mut _localctx: Rc<Scene_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(181); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- animate_name ---------------- pub type Animate_nameContextAll<'input> = Animate_nameContext<'input>; pub type Animate_nameContext<'input> = BaseParserRuleContext<'input,Animate_nameContextExt<'input>>; #[derive(Clone)] pub struct Animate_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Animate_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Animate_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_animate_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_animate_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Animate_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_animate_name(self); } } impl<'input> CustomRuleContext<'input> for Animate_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_animate_name } //fn type_rule_index() -> usize where Self: Sized { RULE_animate_name } } antlr_rust::type_id!{Animate_nameContextExt<'a>} impl<'input> Animate_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Animate_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Animate_nameContextExt{ ph:PhantomData }), ) } } pub trait Animate_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Animate_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Animate_nameContextAttrs<'input> for Animate_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn animate_name(&mut self,) -> Result<Rc<Animate_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Animate_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 36, RULE_animate_name); let mut _localctx: Rc<Animate_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(183); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- page_decl ---------------- pub type Page_declContextAll<'input> = Page_declContext<'input>; pub type Page_declContext<'input> = BaseParserRuleContext<'input,Page_declContextExt<'input>>; #[derive(Clone)] pub struct Page_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Page_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Page_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_page_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_page_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Page_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_page_decl(self); } } impl<'input> CustomRuleContext<'input> for Page_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_page_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_page_decl } } antlr_rust::type_id!{Page_declContextExt<'a>} impl<'input> Page_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Page_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Page_declContextExt{ ph:PhantomData }), ) } } pub trait Page_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Page_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token PAGE /// Returns `None` if there is no child corresponding to token PAGE fn PAGE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(PAGE, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn component_body_decl_all(&self) -> Vec<Rc<Component_body_declContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn component_body_decl(&self, i: usize) -> Option<Rc<Component_body_declContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Page_declContextAttrs<'input> for Page_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn page_decl(&mut self,) -> Result<Rc<Page_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Page_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 38, RULE_page_decl); let mut _localctx: Rc<Page_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(185); recog.base.match_token(PAGE,&mut recog.err_handler)?; recog.base.set_state(186); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(187); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(191); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==IDENTIFIER { { { /*InvokeRule component_body_decl*/ recog.base.set_state(188); recog.component_body_decl()?; } } recog.base.set_state(193); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(194); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- component_decl ---------------- pub type Component_declContextAll<'input> = Component_declContext<'input>; pub type Component_declContext<'input> = BaseParserRuleContext<'input,Component_declContextExt<'input>>; #[derive(Clone)] pub struct Component_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Component_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_decl(self); } } impl<'input> CustomRuleContext<'input> for Component_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_decl } } antlr_rust::type_id!{Component_declContextExt<'a>} impl<'input> Component_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Component_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Component_declContextExt{ ph:PhantomData }), ) } } pub trait Component_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Component_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token COMPONENT /// Returns `None` if there is no child corresponding to token COMPONENT fn COMPONENT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COMPONENT, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn component_body_decl_all(&self) -> Vec<Rc<Component_body_declContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn component_body_decl(&self, i: usize) -> Option<Rc<Component_body_declContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Component_declContextAttrs<'input> for Component_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn component_decl(&mut self,) -> Result<Rc<Component_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Component_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 40, RULE_component_decl); let mut _localctx: Rc<Component_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(196); recog.base.match_token(COMPONENT,&mut recog.err_handler)?; recog.base.set_state(197); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(198); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(202); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==IDENTIFIER { { { /*InvokeRule component_body_decl*/ recog.base.set_state(199); recog.component_body_decl()?; } } recog.base.set_state(204); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(205); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- component_body_decl ---------------- #[derive(Debug)] pub enum Component_body_declContextAll<'input>{ Component_body_configContext(Component_body_configContext<'input>), Component_body_nameContext(Component_body_nameContext<'input>), Error(Component_body_declContext<'input>) } antlr_rust::type_id!{Component_body_declContextAll<'a>} impl<'input> antlr_rust::parser_rule_context::DerefSeal for Component_body_declContextAll<'input>{} impl<'input> DesignParserContext<'input> for Component_body_declContextAll<'input>{} impl<'input> Deref for Component_body_declContextAll<'input>{ type Target = dyn Component_body_declContextAttrs<'input> + 'input; fn deref(&self) -> &Self::Target{ use Component_body_declContextAll::*; match self{ Component_body_configContext(inner) => inner, Component_body_nameContext(inner) => inner, Error(inner) => inner } } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_body_declContextAll<'input>{ fn accept(&self, visitor: &mut (dyn DesignVisitor<'input> + 'a)) { self.deref().accept(visitor) } } impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_body_declContextAll<'input>{ fn enter(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().enter(listener) } fn exit(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().exit(listener) } } pub type Component_body_declContext<'input> = BaseParserRuleContext<'input,Component_body_declContextExt<'input>>; #[derive(Clone)] pub struct Component_body_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Component_body_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_body_declContext<'input>{ } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_body_declContext<'input>{ } impl<'input> CustomRuleContext<'input> for Component_body_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_body_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_body_decl } } antlr_rust::type_id!{Component_body_declContextExt<'a>} impl<'input> Component_body_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Component_body_declContextAll<'input>> { Rc::new( Component_body_declContextAll::Error( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Component_body_declContextExt{ ph:PhantomData }), ) ) } } pub trait Component_body_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Component_body_declContextExt<'input>>{ } impl<'input> Component_body_declContextAttrs<'input> for Component_body_declContext<'input>{} pub type Component_body_configContext<'input> = BaseParserRuleContext<'input,Component_body_configContextExt<'input>>; pub trait Component_body_configContextAttrs<'input>: DesignParserContext<'input>{ fn config_key(&self) -> Option<Rc<Config_keyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token COLON /// Returns `None` if there is no child corresponding to token COLON fn COLON(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COLON, 0) } fn config_value(&self) -> Option<Rc<Config_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Component_body_configContextAttrs<'input> for Component_body_configContext<'input>{} pub struct Component_body_configContextExt<'input>{ base:Component_body_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_body_configContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_body_configContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_body_configContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_body_config(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_body_config(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_body_configContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_body_config(self); } } impl<'input> CustomRuleContext<'input> for Component_body_configContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_body_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_body_decl } } impl<'input> Borrow<Component_body_declContextExt<'input>> for Component_body_configContext<'input>{ fn borrow(&self) -> &Component_body_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_body_declContextExt<'input>> for Component_body_configContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_body_declContextExt<'input> { &mut self.base } } impl<'input> Component_body_declContextAttrs<'input> for Component_body_configContext<'input> {} impl<'input> Component_body_configContextExt<'input>{ fn new(ctx: &dyn Component_body_declContextAttrs<'input>) -> Rc<Component_body_declContextAll<'input>> { Rc::new( Component_body_declContextAll::Component_body_configContext( BaseParserRuleContext::copy_from(ctx,Component_body_configContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Component_body_nameContext<'input> = BaseParserRuleContext<'input,Component_body_nameContextExt<'input>>; pub trait Component_body_nameContextAttrs<'input>: DesignParserContext<'input>{ fn component_name_all(&self) -> Vec<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn component_name(&self, i: usize) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } /// Retrieves all `TerminalNode`s corresponding to token COMMA in current rule fn COMMA_all(&self) -> Vec<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.children_of_type() } /// Retrieves 'i's TerminalNode corresponding to token COMMA, starting from 0. /// Returns `None` if number of children corresponding to token COMMA is less or equal than `i`. fn COMMA(&self, i: usize) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COMMA, i) } } impl<'input> Component_body_nameContextAttrs<'input> for Component_body_nameContext<'input>{} pub struct Component_body_nameContextExt<'input>{ base:Component_body_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_body_nameContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_body_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_body_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_body_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_body_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_body_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_body_name(self); } } impl<'input> CustomRuleContext<'input> for Component_body_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_body_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_body_decl } } impl<'input> Borrow<Component_body_declContextExt<'input>> for Component_body_nameContext<'input>{ fn borrow(&self) -> &Component_body_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_body_declContextExt<'input>> for Component_body_nameContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_body_declContextExt<'input> { &mut self.base } } impl<'input> Component_body_declContextAttrs<'input> for Component_body_nameContext<'input> {} impl<'input> Component_body_nameContextExt<'input>{ fn new(ctx: &dyn Component_body_declContextAttrs<'input>) -> Rc<Component_body_declContextAll<'input>> { Rc::new( Component_body_declContextAll::Component_body_nameContext( BaseParserRuleContext::copy_from(ctx,Component_body_nameContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn component_body_decl(&mut self,) -> Result<Rc<Component_body_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Component_body_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 42, RULE_component_body_decl); let mut _localctx: Rc<Component_body_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { recog.base.set_state(219); recog.err_handler.sync(&mut recog.base)?; match recog.interpreter.adaptive_predict(16,&mut recog.base)? { 1 =>{ let tmp = Component_body_nameContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 1); _localctx = tmp; { /*InvokeRule component_name*/ recog.base.set_state(207); recog.component_name()?; recog.base.set_state(212); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==COMMA { { { recog.base.set_state(208); recog.base.match_token(COMMA,&mut recog.err_handler)?; /*InvokeRule component_name*/ recog.base.set_state(209); recog.component_name()?; } } recog.base.set_state(214); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } } } , 2 =>{ let tmp = Component_body_configContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 2); _localctx = tmp; { /*InvokeRule config_key*/ recog.base.set_state(215); recog.config_key()?; recog.base.set_state(216); recog.base.match_token(COLON,&mut recog.err_handler)?; /*InvokeRule config_value*/ recog.base.set_state(217); recog.config_value()?; } } _ => {} } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- layout_decl ---------------- pub type Layout_declContextAll<'input> = Layout_declContext<'input>; pub type Layout_declContext<'input> = BaseParserRuleContext<'input,Layout_declContextExt<'input>>; #[derive(Clone)] pub struct Layout_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Layout_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Layout_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_layout_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_layout_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Layout_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_layout_decl(self); } } impl<'input> CustomRuleContext<'input> for Layout_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_layout_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_layout_decl } } antlr_rust::type_id!{Layout_declContextExt<'a>} impl<'input> Layout_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Layout_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Layout_declContextExt{ ph:PhantomData }), ) } } pub trait Layout_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Layout_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token LAYOUT /// Returns `None` if there is no child corresponding to token LAYOUT fn LAYOUT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LAYOUT, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn flex_child_all(&self) -> Vec<Rc<Flex_childContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn flex_child(&self, i: usize) -> Option<Rc<Flex_childContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Layout_declContextAttrs<'input> for Layout_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn layout_decl(&mut self,) -> Result<Rc<Layout_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Layout_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 44, RULE_layout_decl); let mut _localctx: Rc<Layout_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(221); recog.base.match_token(LAYOUT,&mut recog.err_handler)?; recog.base.set_state(222); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; recog.base.set_state(223); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(227); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==T__3 || _la==T__4 { { { /*InvokeRule flex_child*/ recog.base.set_state(224); recog.flex_child()?; } } recog.base.set_state(229); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(230); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- flex_child ---------------- #[derive(Debug)] pub enum Flex_childContextAll<'input>{ Flex_component_useContext(Flex_component_useContext<'input>), Empty_lineContext(Empty_lineContext<'input>), Error(Flex_childContext<'input>) } antlr_rust::type_id!{Flex_childContextAll<'a>} impl<'input> antlr_rust::parser_rule_context::DerefSeal for Flex_childContextAll<'input>{} impl<'input> DesignParserContext<'input> for Flex_childContextAll<'input>{} impl<'input> Deref for Flex_childContextAll<'input>{ type Target = dyn Flex_childContextAttrs<'input> + 'input; fn deref(&self) -> &Self::Target{ use Flex_childContextAll::*; match self{ Flex_component_useContext(inner) => inner, Empty_lineContext(inner) => inner, Error(inner) => inner } } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Flex_childContextAll<'input>{ fn accept(&self, visitor: &mut (dyn DesignVisitor<'input> + 'a)) { self.deref().accept(visitor) } } impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Flex_childContextAll<'input>{ fn enter(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().enter(listener) } fn exit(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().exit(listener) } } pub type Flex_childContext<'input> = BaseParserRuleContext<'input,Flex_childContextExt<'input>>; #[derive(Clone)] pub struct Flex_childContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Flex_childContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Flex_childContext<'input>{ } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Flex_childContext<'input>{ } impl<'input> CustomRuleContext<'input> for Flex_childContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_flex_child } //fn type_rule_index() -> usize where Self: Sized { RULE_flex_child } } antlr_rust::type_id!{Flex_childContextExt<'a>} impl<'input> Flex_childContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Flex_childContextAll<'input>> { Rc::new( Flex_childContextAll::Error( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Flex_childContextExt{ ph:PhantomData }), ) ) } } pub trait Flex_childContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Flex_childContextExt<'input>>{ } impl<'input> Flex_childContextAttrs<'input> for Flex_childContext<'input>{} pub type Flex_component_useContext<'input> = BaseParserRuleContext<'input,Flex_component_useContextExt<'input>>; pub trait Flex_component_useContextAttrs<'input>: DesignParserContext<'input>{ fn component_use_decl_all(&self) -> Vec<Rc<Component_use_declContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn component_use_decl(&self, i: usize) -> Option<Rc<Component_use_declContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Flex_component_useContextAttrs<'input> for Flex_component_useContext<'input>{} pub struct Flex_component_useContextExt<'input>{ base:Flex_childContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Flex_component_useContextExt<'a>} impl<'input> DesignParserContext<'input> for Flex_component_useContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Flex_component_useContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_flex_component_use(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_flex_component_use(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Flex_component_useContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_flex_component_use(self); } } impl<'input> CustomRuleContext<'input> for Flex_component_useContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_flex_child } //fn type_rule_index() -> usize where Self: Sized { RULE_flex_child } } impl<'input> Borrow<Flex_childContextExt<'input>> for Flex_component_useContext<'input>{ fn borrow(&self) -> &Flex_childContextExt<'input> { &self.base } } impl<'input> BorrowMut<Flex_childContextExt<'input>> for Flex_component_useContext<'input>{ fn borrow_mut(&mut self) -> &mut Flex_childContextExt<'input> { &mut self.base } } impl<'input> Flex_childContextAttrs<'input> for Flex_component_useContext<'input> {} impl<'input> Flex_component_useContextExt<'input>{ fn new(ctx: &dyn Flex_childContextAttrs<'input>) -> Rc<Flex_childContextAll<'input>> { Rc::new( Flex_childContextAll::Flex_component_useContext( BaseParserRuleContext::copy_from(ctx,Flex_component_useContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Empty_lineContext<'input> = BaseParserRuleContext<'input,Empty_lineContextExt<'input>>; pub trait Empty_lineContextAttrs<'input>: DesignParserContext<'input>{ } impl<'input> Empty_lineContextAttrs<'input> for Empty_lineContext<'input>{} pub struct Empty_lineContextExt<'input>{ base:Flex_childContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Empty_lineContextExt<'a>} impl<'input> DesignParserContext<'input> for Empty_lineContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Empty_lineContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_empty_line(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_empty_line(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Empty_lineContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_empty_line(self); } } impl<'input> CustomRuleContext<'input> for Empty_lineContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_flex_child } //fn type_rule_index() -> usize where Self: Sized { RULE_flex_child } } impl<'input> Borrow<Flex_childContextExt<'input>> for Empty_lineContext<'input>{ fn borrow(&self) -> &Flex_childContextExt<'input> { &self.base } } impl<'input> BorrowMut<Flex_childContextExt<'input>> for Empty_lineContext<'input>{ fn borrow_mut(&mut self) -> &mut Flex_childContextExt<'input> { &mut self.base } } impl<'input> Flex_childContextAttrs<'input> for Empty_lineContext<'input> {} impl<'input> Empty_lineContextExt<'input>{ fn new(ctx: &dyn Flex_childContextAttrs<'input>) -> Rc<Flex_childContextAll<'input>> { Rc::new( Flex_childContextAll::Empty_lineContext( BaseParserRuleContext::copy_from(ctx,Empty_lineContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn flex_child(&mut self,) -> Result<Rc<Flex_childContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Flex_childContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 46, RULE_flex_child); let mut _localctx: Rc<Flex_childContextAll> = _localctx; let result: Result<(), ANTLRError> = try { let mut _alt: isize; recog.base.set_state(251); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { T__3 => { let tmp = Empty_lineContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 1); _localctx = tmp; { recog.base.set_state(232); recog.base.match_token(T__3,&mut recog.err_handler)?; recog.base.set_state(236); recog.err_handler.sync(&mut recog.base)?; _alt = recog.interpreter.adaptive_predict(18,&mut recog.base)?; while { _alt!=2 && _alt!=INVALID_ALT } { if _alt==1 { { { recog.base.set_state(233); recog.base.match_token(T__3,&mut recog.err_handler)?; } } } recog.base.set_state(238); recog.err_handler.sync(&mut recog.base)?; _alt = recog.interpreter.adaptive_predict(18,&mut recog.base)?; } } } T__4 => { let tmp = Flex_component_useContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 2); _localctx = tmp; { { recog.base.set_state(239); recog.base.match_token(T__4,&mut recog.err_handler)?; /*InvokeRule component_use_decl*/ recog.base.set_state(240); recog.component_use_decl()?; } recog.base.set_state(246); recog.err_handler.sync(&mut recog.base)?; _alt = recog.interpreter.adaptive_predict(19,&mut recog.base)?; while { _alt!=2 && _alt!=INVALID_ALT } { if _alt==1 { { { recog.base.set_state(242); recog.base.match_token(T__4,&mut recog.err_handler)?; /*InvokeRule component_use_decl*/ recog.base.set_state(243); recog.component_use_decl()?; } } } recog.base.set_state(248); recog.err_handler.sync(&mut recog.base)?; _alt = recog.interpreter.adaptive_predict(19,&mut recog.base)?; } recog.base.set_state(249); recog.base.match_token(T__4,&mut recog.err_handler)?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- component_use_decl ---------------- #[derive(Debug)] pub enum Component_use_declContextAll<'input>{ Component_use_name_valueContext(Component_use_name_valueContext<'input>), Component_use_decimalContext(Component_use_decimalContext<'input>), Component_use_stringContext(Component_use_stringContext<'input>), Component_use_positionContext(Component_use_positionContext<'input>), Error(Component_use_declContext<'input>) } antlr_rust::type_id!{Component_use_declContextAll<'a>} impl<'input> antlr_rust::parser_rule_context::DerefSeal for Component_use_declContextAll<'input>{} impl<'input> DesignParserContext<'input> for Component_use_declContextAll<'input>{} impl<'input> Deref for Component_use_declContextAll<'input>{ type Target = dyn Component_use_declContextAttrs<'input> + 'input; fn deref(&self) -> &Self::Target{ use Component_use_declContextAll::*; match self{ Component_use_name_valueContext(inner) => inner, Component_use_decimalContext(inner) => inner, Component_use_stringContext(inner) => inner, Component_use_positionContext(inner) => inner, Error(inner) => inner } } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_declContextAll<'input>{ fn accept(&self, visitor: &mut (dyn DesignVisitor<'input> + 'a)) { self.deref().accept(visitor) } } impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_declContextAll<'input>{ fn enter(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().enter(listener) } fn exit(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().exit(listener) } } pub type Component_use_declContext<'input> = BaseParserRuleContext<'input,Component_use_declContextExt<'input>>; #[derive(Clone)] pub struct Component_use_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Component_use_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_declContext<'input>{ } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_declContext<'input>{ } impl<'input> CustomRuleContext<'input> for Component_use_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_use_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_use_decl } } antlr_rust::type_id!{Component_use_declContextExt<'a>} impl<'input> Component_use_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Component_use_declContextAll<'input>> { Rc::new( Component_use_declContextAll::Error( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Component_use_declContextExt{ ph:PhantomData }), ) ) } } pub trait Component_use_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Component_use_declContextExt<'input>>{ } impl<'input> Component_use_declContextAttrs<'input> for Component_use_declContext<'input>{} pub type Component_use_name_valueContext<'input> = BaseParserRuleContext<'input,Component_use_name_valueContextExt<'input>>; pub trait Component_use_name_valueContextAttrs<'input>: DesignParserContext<'input>{ fn component_name(&self) -> Option<Rc<Component_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token LPAREN /// Returns `None` if there is no child corresponding to token LPAREN fn LPAREN(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LPAREN, 0) } fn component_parameter_all(&self) -> Vec<Rc<Component_parameterContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn component_parameter(&self, i: usize) -> Option<Rc<Component_parameterContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } /// Retrieves first TerminalNode corresponding to token RPAREN /// Returns `None` if there is no child corresponding to token RPAREN fn RPAREN(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RPAREN, 0) } /// Retrieves all `TerminalNode`s corresponding to token COMMA in current rule fn COMMA_all(&self) -> Vec<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.children_of_type() } /// Retrieves 'i's TerminalNode corresponding to token COMMA, starting from 0. /// Returns `None` if number of children corresponding to token COMMA is less or equal than `i`. fn COMMA(&self, i: usize) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COMMA, i) } } impl<'input> Component_use_name_valueContextAttrs<'input> for Component_use_name_valueContext<'input>{} pub struct Component_use_name_valueContextExt<'input>{ base:Component_use_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_use_name_valueContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_use_name_valueContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_name_valueContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_use_name_value(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_use_name_value(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_name_valueContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_use_name_value(self); } } impl<'input> CustomRuleContext<'input> for Component_use_name_valueContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_use_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_use_decl } } impl<'input> Borrow<Component_use_declContextExt<'input>> for Component_use_name_valueContext<'input>{ fn borrow(&self) -> &Component_use_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_use_declContextExt<'input>> for Component_use_name_valueContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_use_declContextExt<'input> { &mut self.base } } impl<'input> Component_use_declContextAttrs<'input> for Component_use_name_valueContext<'input> {} impl<'input> Component_use_name_valueContextExt<'input>{ fn new(ctx: &dyn Component_use_declContextAttrs<'input>) -> Rc<Component_use_declContextAll<'input>> { Rc::new( Component_use_declContextAll::Component_use_name_valueContext( BaseParserRuleContext::copy_from(ctx,Component_use_name_valueContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Component_use_decimalContext<'input> = BaseParserRuleContext<'input,Component_use_decimalContextExt<'input>>; pub trait Component_use_decimalContextAttrs<'input>: DesignParserContext<'input>{ /// Retrieves first TerminalNode corresponding to token DECIMAL_LITERAL /// Returns `None` if there is no child corresponding to token DECIMAL_LITERAL fn DECIMAL_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DECIMAL_LITERAL, 0) } } impl<'input> Component_use_decimalContextAttrs<'input> for Component_use_decimalContext<'input>{} pub struct Component_use_decimalContextExt<'input>{ base:Component_use_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_use_decimalContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_use_decimalContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_decimalContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_use_decimal(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_use_decimal(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_decimalContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_use_decimal(self); } } impl<'input> CustomRuleContext<'input> for Component_use_decimalContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_use_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_use_decl } } impl<'input> Borrow<Component_use_declContextExt<'input>> for Component_use_decimalContext<'input>{ fn borrow(&self) -> &Component_use_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_use_declContextExt<'input>> for Component_use_decimalContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_use_declContextExt<'input> { &mut self.base } } impl<'input> Component_use_declContextAttrs<'input> for Component_use_decimalContext<'input> {} impl<'input> Component_use_decimalContextExt<'input>{ fn new(ctx: &dyn Component_use_declContextAttrs<'input>) -> Rc<Component_use_declContextAll<'input>> { Rc::new( Component_use_declContextAll::Component_use_decimalContext( BaseParserRuleContext::copy_from(ctx,Component_use_decimalContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Component_use_stringContext<'input> = BaseParserRuleContext<'input,Component_use_stringContextExt<'input>>; pub trait Component_use_stringContextAttrs<'input>: DesignParserContext<'input>{ /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } } impl<'input> Component_use_stringContextAttrs<'input> for Component_use_stringContext<'input>{} pub struct Component_use_stringContextExt<'input>{ base:Component_use_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_use_stringContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_use_stringContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_stringContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_use_string(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_use_string(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_stringContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_use_string(self); } } impl<'input> CustomRuleContext<'input> for Component_use_stringContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_use_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_use_decl } } impl<'input> Borrow<Component_use_declContextExt<'input>> for Component_use_stringContext<'input>{ fn borrow(&self) -> &Component_use_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_use_declContextExt<'input>> for Component_use_stringContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_use_declContextExt<'input> { &mut self.base } } impl<'input> Component_use_declContextAttrs<'input> for Component_use_stringContext<'input> {} impl<'input> Component_use_stringContextExt<'input>{ fn new(ctx: &dyn Component_use_declContextAttrs<'input>) -> Rc<Component_use_declContextAll<'input>> { Rc::new( Component_use_declContextAll::Component_use_stringContext( BaseParserRuleContext::copy_from(ctx,Component_use_stringContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Component_use_positionContext<'input> = BaseParserRuleContext<'input,Component_use_positionContextExt<'input>>; pub trait Component_use_positionContextAttrs<'input>: DesignParserContext<'input>{ /// Retrieves first TerminalNode corresponding to token POSITION /// Returns `None` if there is no child corresponding to token POSITION fn POSITION(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(POSITION, 0) } } impl<'input> Component_use_positionContextAttrs<'input> for Component_use_positionContext<'input>{} pub struct Component_use_positionContextExt<'input>{ base:Component_use_declContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Component_use_positionContextExt<'a>} impl<'input> DesignParserContext<'input> for Component_use_positionContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_use_positionContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_use_position(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_use_position(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_use_positionContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_use_position(self); } } impl<'input> CustomRuleContext<'input> for Component_use_positionContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_use_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_component_use_decl } } impl<'input> Borrow<Component_use_declContextExt<'input>> for Component_use_positionContext<'input>{ fn borrow(&self) -> &Component_use_declContextExt<'input> { &self.base } } impl<'input> BorrowMut<Component_use_declContextExt<'input>> for Component_use_positionContext<'input>{ fn borrow_mut(&mut self) -> &mut Component_use_declContextExt<'input> { &mut self.base } } impl<'input> Component_use_declContextAttrs<'input> for Component_use_positionContext<'input> {} impl<'input> Component_use_positionContextExt<'input>{ fn new(ctx: &dyn Component_use_declContextAttrs<'input>) -> Rc<Component_use_declContextAll<'input>> { Rc::new( Component_use_declContextAll::Component_use_positionContext( BaseParserRuleContext::copy_from(ctx,Component_use_positionContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn component_use_decl(&mut self,) -> Result<Rc<Component_use_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Component_use_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 48, RULE_component_use_decl); let mut _localctx: Rc<Component_use_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { recog.base.set_state(270); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { DECIMAL_LITERAL => { let tmp = Component_use_decimalContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 1); _localctx = tmp; { recog.base.set_state(253); recog.base.match_token(DECIMAL_LITERAL,&mut recog.err_handler)?; } } POSITION => { let tmp = Component_use_positionContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 2); _localctx = tmp; { recog.base.set_state(254); recog.base.match_token(POSITION,&mut recog.err_handler)?; } } IDENTIFIER => { let tmp = Component_use_name_valueContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 3); _localctx = tmp; { /*InvokeRule component_name*/ recog.base.set_state(255); recog.component_name()?; recog.base.set_state(267); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if _la==LPAREN { { recog.base.set_state(256); recog.base.match_token(LPAREN,&mut recog.err_handler)?; /*InvokeRule component_parameter*/ recog.base.set_state(257); recog.component_parameter()?; recog.base.set_state(262); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==COMMA { { { recog.base.set_state(258); recog.base.match_token(COMMA,&mut recog.err_handler)?; /*InvokeRule component_parameter*/ recog.base.set_state(259); recog.component_parameter()?; } } recog.base.set_state(264); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(265); recog.base.match_token(RPAREN,&mut recog.err_handler)?; } } } } STRING_LITERAL => { let tmp = Component_use_stringContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 4); _localctx = tmp; { recog.base.set_state(269); recog.base.match_token(STRING_LITERAL,&mut recog.err_handler)?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- component_parameter ---------------- pub type Component_parameterContextAll<'input> = Component_parameterContext<'input>; pub type Component_parameterContext<'input> = BaseParserRuleContext<'input,Component_parameterContextExt<'input>>; #[derive(Clone)] pub struct Component_parameterContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Component_parameterContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Component_parameterContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_component_parameter(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_component_parameter(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Component_parameterContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_component_parameter(self); } } impl<'input> CustomRuleContext<'input> for Component_parameterContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_component_parameter } //fn type_rule_index() -> usize where Self: Sized { RULE_component_parameter } } antlr_rust::type_id!{Component_parameterContextExt<'a>} impl<'input> Component_parameterContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Component_parameterContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Component_parameterContextExt{ ph:PhantomData }), ) } } pub trait Component_parameterContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Component_parameterContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token DIGITS_IDENTIFIER /// Returns `None` if there is no child corresponding to token DIGITS_IDENTIFIER fn DIGITS_IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DIGITS_IDENTIFIER, 0) } /// Retrieves first TerminalNode corresponding to token POSITION /// Returns `None` if there is no child corresponding to token POSITION fn POSITION(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(POSITION, 0) } /// Retrieves first TerminalNode corresponding to token STRING_LITERAL /// Returns `None` if there is no child corresponding to token STRING_LITERAL fn STRING_LITERAL(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STRING_LITERAL, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Component_parameterContextAttrs<'input> for Component_parameterContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn component_parameter(&mut self,) -> Result<Rc<Component_parameterContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Component_parameterContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 50, RULE_component_parameter); let mut _localctx: Rc<Component_parameterContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(272); _la = recog.base.input.la(1); if { !((((_la) & !0x3f) == 0 && ((1usize << _la) & ((1usize << POSITION) | (1usize << STRING_LITERAL) | (1usize << IDENTIFIER) | (1usize << DIGITS_IDENTIFIER))) != 0)) } { recog.err_handler.recover_inline(&mut recog.base)?; } else { if recog.base.input.la(1)==TOKEN_EOF { recog.base.matched_eof = true }; recog.err_handler.report_match(&mut recog.base); recog.base.consume(&mut recog.err_handler); } } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- style_decl ---------------- pub type Style_declContextAll<'input> = Style_declContext<'input>; pub type Style_declContext<'input> = BaseParserRuleContext<'input,Style_declContextExt<'input>>; #[derive(Clone)] pub struct Style_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Style_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Style_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_style_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_style_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Style_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_style_decl(self); } } impl<'input> CustomRuleContext<'input> for Style_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_style_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_style_decl } } antlr_rust::type_id!{Style_declContextExt<'a>} impl<'input> Style_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Style_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Style_declContextExt{ ph:PhantomData }), ) } } pub trait Style_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Style_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token STYLE /// Returns `None` if there is no child corresponding to token STYLE fn STYLE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(STYLE, 0) } fn style_name(&self) -> Option<Rc<Style_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } fn style_body(&self) -> Option<Rc<Style_bodyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } } impl<'input> Style_declContextAttrs<'input> for Style_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn style_decl(&mut self,) -> Result<Rc<Style_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Style_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 52, RULE_style_decl); let mut _localctx: Rc<Style_declContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(274); recog.base.match_token(STYLE,&mut recog.err_handler)?; /*InvokeRule style_name*/ recog.base.set_state(275); recog.style_name()?; recog.base.set_state(276); recog.base.match_token(LBRACE,&mut recog.err_handler)?; /*InvokeRule style_body*/ recog.base.set_state(277); recog.style_body()?; recog.base.set_state(278); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- style_name ---------------- pub type Style_nameContextAll<'input> = Style_nameContext<'input>; pub type Style_nameContext<'input> = BaseParserRuleContext<'input,Style_nameContextExt<'input>>; #[derive(Clone)] pub struct Style_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Style_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Style_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_style_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_style_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Style_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_style_name(self); } } impl<'input> CustomRuleContext<'input> for Style_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_style_name } //fn type_rule_index() -> usize where Self: Sized { RULE_style_name } } antlr_rust::type_id!{Style_nameContextExt<'a>} impl<'input> Style_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Style_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Style_nameContextExt{ ph:PhantomData }), ) } } pub trait Style_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Style_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Style_nameContextAttrs<'input> for Style_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn style_name(&mut self,) -> Result<Rc<Style_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Style_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 54, RULE_style_name); let mut _localctx: Rc<Style_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(280); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- style_body ---------------- pub type Style_bodyContextAll<'input> = Style_bodyContext<'input>; pub type Style_bodyContext<'input> = BaseParserRuleContext<'input,Style_bodyContextExt<'input>>; #[derive(Clone)] pub struct Style_bodyContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Style_bodyContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Style_bodyContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_style_body(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_style_body(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Style_bodyContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_style_body(self); } } impl<'input> CustomRuleContext<'input> for Style_bodyContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_style_body } //fn type_rule_index() -> usize where Self: Sized { RULE_style_body } } antlr_rust::type_id!{Style_bodyContextExt<'a>} impl<'input> Style_bodyContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Style_bodyContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Style_bodyContextExt{ ph:PhantomData }), ) } } pub trait Style_bodyContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Style_bodyContextExt<'input>>{ fn config_decl_all(&self) -> Vec<Rc<Config_declContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn config_decl(&self, i: usize) -> Option<Rc<Config_declContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Style_bodyContextAttrs<'input> for Style_bodyContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn style_body(&mut self,) -> Result<Rc<Style_bodyContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Style_bodyContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 56, RULE_style_body); let mut _localctx: Rc<Style_bodyContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(287); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==IDENTIFIER { { { /*InvokeRule config_decl*/ recog.base.set_state(282); recog.config_decl()?; recog.base.set_state(283); recog.base.match_token(T__5,&mut recog.err_handler)?; } } recog.base.set_state(289); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- library_name ---------------- pub type Library_nameContextAll<'input> = Library_nameContext<'input>; pub type Library_nameContext<'input> = BaseParserRuleContext<'input,Library_nameContextExt<'input>>; #[derive(Clone)] pub struct Library_nameContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Library_nameContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_nameContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_library_name(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_library_name(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_nameContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_library_name(self); } } impl<'input> CustomRuleContext<'input> for Library_nameContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_library_name } //fn type_rule_index() -> usize where Self: Sized { RULE_library_name } } antlr_rust::type_id!{Library_nameContextExt<'a>} impl<'input> Library_nameContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Library_nameContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Library_nameContextExt{ ph:PhantomData }), ) } } pub trait Library_nameContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Library_nameContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Library_nameContextAttrs<'input> for Library_nameContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn library_name(&mut self,) -> Result<Rc<Library_nameContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Library_nameContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 58, RULE_library_name); let mut _localctx: Rc<Library_nameContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(290); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- library_decl ---------------- pub type Library_declContextAll<'input> = Library_declContext<'input>; pub type Library_declContext<'input> = BaseParserRuleContext<'input,Library_declContextExt<'input>>; #[derive(Clone)] pub struct Library_declContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Library_declContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_declContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_library_decl(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_library_decl(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_declContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_library_decl(self); } } impl<'input> CustomRuleContext<'input> for Library_declContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_library_decl } //fn type_rule_index() -> usize where Self: Sized { RULE_library_decl } } antlr_rust::type_id!{Library_declContextExt<'a>} impl<'input> Library_declContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Library_declContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Library_declContextExt{ ph:PhantomData }), ) } } pub trait Library_declContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Library_declContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token LIBRARY /// Returns `None` if there is no child corresponding to token LIBRARY fn LIBRARY(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LIBRARY, 0) } fn library_name(&self) -> Option<Rc<Library_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn library_exp_all(&self) -> Vec<Rc<Library_expContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn library_exp(&self, i: usize) -> Option<Rc<Library_expContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Library_declContextAttrs<'input> for Library_declContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn library_decl(&mut self,) -> Result<Rc<Library_declContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Library_declContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 60, RULE_library_decl); let mut _localctx: Rc<Library_declContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(292); recog.base.match_token(LIBRARY,&mut recog.err_handler)?; /*InvokeRule library_name*/ recog.base.set_state(293); recog.library_name()?; recog.base.set_state(294); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(298); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==IDENTIFIER { { { /*InvokeRule library_exp*/ recog.base.set_state(295); recog.library_exp()?; } } recog.base.set_state(300); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(301); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- library_exp ---------------- #[derive(Debug)] pub enum Library_expContextAll<'input>{ Library_objectContext(Library_objectContext<'input>), Library_configContext(Library_configContext<'input>), Error(Library_expContext<'input>) } antlr_rust::type_id!{Library_expContextAll<'a>} impl<'input> antlr_rust::parser_rule_context::DerefSeal for Library_expContextAll<'input>{} impl<'input> DesignParserContext<'input> for Library_expContextAll<'input>{} impl<'input> Deref for Library_expContextAll<'input>{ type Target = dyn Library_expContextAttrs<'input> + 'input; fn deref(&self) -> &Self::Target{ use Library_expContextAll::*; match self{ Library_objectContext(inner) => inner, Library_configContext(inner) => inner, Error(inner) => inner } } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_expContextAll<'input>{ fn accept(&self, visitor: &mut (dyn DesignVisitor<'input> + 'a)) { self.deref().accept(visitor) } } impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_expContextAll<'input>{ fn enter(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().enter(listener) } fn exit(&self, listener: &mut (dyn DesignListener<'input> + 'a)) { self.deref().exit(listener) } } pub type Library_expContext<'input> = BaseParserRuleContext<'input,Library_expContextExt<'input>>; #[derive(Clone)] pub struct Library_expContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Library_expContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_expContext<'input>{ } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_expContext<'input>{ } impl<'input> CustomRuleContext<'input> for Library_expContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_library_exp } //fn type_rule_index() -> usize where Self: Sized { RULE_library_exp } } antlr_rust::type_id!{Library_expContextExt<'a>} impl<'input> Library_expContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Library_expContextAll<'input>> { Rc::new( Library_expContextAll::Error( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Library_expContextExt{ ph:PhantomData }), ) ) } } pub trait Library_expContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Library_expContextExt<'input>>{ } impl<'input> Library_expContextAttrs<'input> for Library_expContext<'input>{} pub type Library_objectContext<'input> = BaseParserRuleContext<'input,Library_objectContextExt<'input>>; pub trait Library_objectContextAttrs<'input>: DesignParserContext<'input>{ fn preset_key(&self) -> Option<Rc<Preset_keyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token LBRACE /// Returns `None` if there is no child corresponding to token LBRACE fn LBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACE, 0) } /// Retrieves first TerminalNode corresponding to token RBRACE /// Returns `None` if there is no child corresponding to token RBRACE fn RBRACE(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACE, 0) } fn key_value_all(&self) -> Vec<Rc<Key_valueContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn key_value(&self, i: usize) -> Option<Rc<Key_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } } impl<'input> Library_objectContextAttrs<'input> for Library_objectContext<'input>{} pub struct Library_objectContextExt<'input>{ base:Library_expContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Library_objectContextExt<'a>} impl<'input> DesignParserContext<'input> for Library_objectContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_objectContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_library_object(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_library_object(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_objectContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_library_object(self); } } impl<'input> CustomRuleContext<'input> for Library_objectContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_library_exp } //fn type_rule_index() -> usize where Self: Sized { RULE_library_exp } } impl<'input> Borrow<Library_expContextExt<'input>> for Library_objectContext<'input>{ fn borrow(&self) -> &Library_expContextExt<'input> { &self.base } } impl<'input> BorrowMut<Library_expContextExt<'input>> for Library_objectContext<'input>{ fn borrow_mut(&mut self) -> &mut Library_expContextExt<'input> { &mut self.base } } impl<'input> Library_expContextAttrs<'input> for Library_objectContext<'input> {} impl<'input> Library_objectContextExt<'input>{ fn new(ctx: &dyn Library_expContextAttrs<'input>) -> Rc<Library_expContextAll<'input>> { Rc::new( Library_expContextAll::Library_objectContext( BaseParserRuleContext::copy_from(ctx,Library_objectContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } pub type Library_configContext<'input> = BaseParserRuleContext<'input,Library_configContextExt<'input>>; pub trait Library_configContextAttrs<'input>: DesignParserContext<'input>{ fn preset_key(&self) -> Option<Rc<Preset_keyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn preset_value(&self) -> Option<Rc<Preset_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn preset_array(&self) -> Option<Rc<Preset_arrayContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Library_configContextAttrs<'input> for Library_configContext<'input>{} pub struct Library_configContextExt<'input>{ base:Library_expContextExt<'input>, ph:PhantomData<&'input str> } antlr_rust::type_id!{Library_configContextExt<'a>} impl<'input> DesignParserContext<'input> for Library_configContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Library_configContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_library_config(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_library_config(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Library_configContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_library_config(self); } } impl<'input> CustomRuleContext<'input> for Library_configContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_library_exp } //fn type_rule_index() -> usize where Self: Sized { RULE_library_exp } } impl<'input> Borrow<Library_expContextExt<'input>> for Library_configContext<'input>{ fn borrow(&self) -> &Library_expContextExt<'input> { &self.base } } impl<'input> BorrowMut<Library_expContextExt<'input>> for Library_configContext<'input>{ fn borrow_mut(&mut self) -> &mut Library_expContextExt<'input> { &mut self.base } } impl<'input> Library_expContextAttrs<'input> for Library_configContext<'input> {} impl<'input> Library_configContextExt<'input>{ fn new(ctx: &dyn Library_expContextAttrs<'input>) -> Rc<Library_expContextAll<'input>> { Rc::new( Library_expContextAll::Library_configContext( BaseParserRuleContext::copy_from(ctx,Library_configContextExt{ base: ctx.borrow().clone(), ph:PhantomData }) ) ) } } impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn library_exp(&mut self,) -> Result<Rc<Library_expContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Library_expContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 62, RULE_library_exp); let mut _localctx: Rc<Library_expContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { recog.base.set_state(322); recog.err_handler.sync(&mut recog.base)?; match recog.interpreter.adaptive_predict(29,&mut recog.base)? { 1 =>{ let tmp = Library_configContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 1); _localctx = tmp; { /*InvokeRule preset_key*/ recog.base.set_state(303); recog.preset_key()?; recog.base.set_state(304); recog.base.match_token(T__6,&mut recog.err_handler)?; recog.base.set_state(307); recog.err_handler.sync(&mut recog.base)?; match recog.base.input.la(1) { STRING_LITERAL | IDENTIFIER | DIGITS_IDENTIFIER | DECIMAL_LITERAL | FLOAT_LITERAL => { { /*InvokeRule preset_value*/ recog.base.set_state(305); recog.preset_value()?; } } LBRACK => { { /*InvokeRule preset_array*/ recog.base.set_state(306); recog.preset_array()?; } } _ => Err(ANTLRError::NoAltError(NoViableAltError::new(&mut recog.base)))? } recog.base.set_state(310); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); if _la==T__5 { { recog.base.set_state(309); recog.base.match_token(T__5,&mut recog.err_handler)?; } } } } , 2 =>{ let tmp = Library_objectContextExt::new(&**_localctx); recog.base.enter_outer_alt(Some(tmp.clone()), 2); _localctx = tmp; { /*InvokeRule preset_key*/ recog.base.set_state(312); recog.preset_key()?; recog.base.set_state(313); recog.base.match_token(LBRACE,&mut recog.err_handler)?; recog.base.set_state(317); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==IDENTIFIER { { { /*InvokeRule key_value*/ recog.base.set_state(314); recog.key_value()?; } } recog.base.set_state(319); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(320); recog.base.match_token(RBRACE,&mut recog.err_handler)?; } } _ => {} } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- key_value ---------------- pub type Key_valueContextAll<'input> = Key_valueContext<'input>; pub type Key_valueContext<'input> = BaseParserRuleContext<'input,Key_valueContextExt<'input>>; #[derive(Clone)] pub struct Key_valueContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Key_valueContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Key_valueContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_key_value(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_key_value(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Key_valueContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_key_value(self); } } impl<'input> CustomRuleContext<'input> for Key_valueContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_key_value } //fn type_rule_index() -> usize where Self: Sized { RULE_key_value } } antlr_rust::type_id!{Key_valueContextExt<'a>} impl<'input> Key_valueContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Key_valueContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Key_valueContextExt{ ph:PhantomData }), ) } } pub trait Key_valueContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Key_valueContextExt<'input>>{ fn preset_key(&self) -> Option<Rc<Preset_keyContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } fn preset_value(&self) -> Option<Rc<Preset_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Key_valueContextAttrs<'input> for Key_valueContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn key_value(&mut self,) -> Result<Rc<Key_valueContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Key_valueContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 64, RULE_key_value); let mut _localctx: Rc<Key_valueContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule preset_key*/ recog.base.set_state(324); recog.preset_key()?; recog.base.set_state(325); recog.base.match_token(T__6,&mut recog.err_handler)?; /*InvokeRule preset_value*/ recog.base.set_state(326); recog.preset_value()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- preset_key ---------------- pub type Preset_keyContextAll<'input> = Preset_keyContext<'input>; pub type Preset_keyContext<'input> = BaseParserRuleContext<'input,Preset_keyContextExt<'input>>; #[derive(Clone)] pub struct Preset_keyContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Preset_keyContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Preset_keyContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_preset_key(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_preset_key(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Preset_keyContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_preset_key(self); } } impl<'input> CustomRuleContext<'input> for Preset_keyContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_preset_key } //fn type_rule_index() -> usize where Self: Sized { RULE_preset_key } } antlr_rust::type_id!{Preset_keyContextExt<'a>} impl<'input> Preset_keyContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Preset_keyContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Preset_keyContextExt{ ph:PhantomData }), ) } } pub trait Preset_keyContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Preset_keyContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Preset_keyContextAttrs<'input> for Preset_keyContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn preset_key(&mut self,) -> Result<Rc<Preset_keyContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Preset_keyContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 66, RULE_preset_key); let mut _localctx: Rc<Preset_keyContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(328); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- preset_value ---------------- pub type Preset_valueContextAll<'input> = Preset_valueContext<'input>; pub type Preset_valueContext<'input> = BaseParserRuleContext<'input,Preset_valueContextExt<'input>>; #[derive(Clone)] pub struct Preset_valueContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Preset_valueContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Preset_valueContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_preset_value(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_preset_value(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Preset_valueContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_preset_value(self); } } impl<'input> CustomRuleContext<'input> for Preset_valueContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_preset_value } //fn type_rule_index() -> usize where Self: Sized { RULE_preset_value } } antlr_rust::type_id!{Preset_valueContextExt<'a>} impl<'input> Preset_valueContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Preset_valueContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Preset_valueContextExt{ ph:PhantomData }), ) } } pub trait Preset_valueContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Preset_valueContextExt<'input>>{ fn config_value(&self) -> Option<Rc<Config_valueContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } } impl<'input> Preset_valueContextAttrs<'input> for Preset_valueContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn preset_value(&mut self,) -> Result<Rc<Preset_valueContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Preset_valueContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 68, RULE_preset_value); let mut _localctx: Rc<Preset_valueContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule config_value*/ recog.base.set_state(330); recog.config_value()?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- preset_array ---------------- pub type Preset_arrayContextAll<'input> = Preset_arrayContext<'input>; pub type Preset_arrayContext<'input> = BaseParserRuleContext<'input,Preset_arrayContextExt<'input>>; #[derive(Clone)] pub struct Preset_arrayContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Preset_arrayContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Preset_arrayContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_preset_array(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_preset_array(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Preset_arrayContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_preset_array(self); } } impl<'input> CustomRuleContext<'input> for Preset_arrayContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_preset_array } //fn type_rule_index() -> usize where Self: Sized { RULE_preset_array } } antlr_rust::type_id!{Preset_arrayContextExt<'a>} impl<'input> Preset_arrayContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Preset_arrayContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Preset_arrayContextExt{ ph:PhantomData }), ) } } pub trait Preset_arrayContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Preset_arrayContextExt<'input>>{ /// Retrieves first TerminalNode corresponding to token LBRACK /// Returns `None` if there is no child corresponding to token LBRACK fn LBRACK(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(LBRACK, 0) } fn preset_call_all(&self) -> Vec<Rc<Preset_callContextAll<'input>>> where Self:Sized{ self.children_of_type() } fn preset_call(&self, i: usize) -> Option<Rc<Preset_callContextAll<'input>>> where Self:Sized{ self.child_of_type(i) } /// Retrieves first TerminalNode corresponding to token RBRACK /// Returns `None` if there is no child corresponding to token RBRACK fn RBRACK(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(RBRACK, 0) } /// Retrieves all `TerminalNode`s corresponding to token COMMA in current rule fn COMMA_all(&self) -> Vec<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.children_of_type() } /// Retrieves 'i's TerminalNode corresponding to token COMMA, starting from 0. /// Returns `None` if number of children corresponding to token COMMA is less or equal than `i`. fn COMMA(&self, i: usize) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(COMMA, i) } } impl<'input> Preset_arrayContextAttrs<'input> for Preset_arrayContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn preset_array(&mut self,) -> Result<Rc<Preset_arrayContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Preset_arrayContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 70, RULE_preset_array); let mut _localctx: Rc<Preset_arrayContextAll> = _localctx; let mut _la: isize; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { recog.base.set_state(332); recog.base.match_token(LBRACK,&mut recog.err_handler)?; /*InvokeRule preset_call*/ recog.base.set_state(333); recog.preset_call()?; recog.base.set_state(338); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); while _la==COMMA { { { recog.base.set_state(334); recog.base.match_token(COMMA,&mut recog.err_handler)?; /*InvokeRule preset_call*/ recog.base.set_state(335); recog.preset_call()?; } } recog.base.set_state(340); recog.err_handler.sync(&mut recog.base)?; _la = recog.base.input.la(1); } recog.base.set_state(341); recog.base.match_token(RBRACK,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } //------------------- preset_call ---------------- pub type Preset_callContextAll<'input> = Preset_callContext<'input>; pub type Preset_callContext<'input> = BaseParserRuleContext<'input,Preset_callContextExt<'input>>; #[derive(Clone)] pub struct Preset_callContextExt<'input>{ ph:PhantomData<&'input str> } impl<'input> DesignParserContext<'input> for Preset_callContext<'input>{} impl<'input,'a> Listenable<dyn DesignListener<'input> + 'a> for Preset_callContext<'input>{ fn enter(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.enter_every_rule(self); listener.enter_preset_call(self); } fn exit(&self,listener: &mut (dyn DesignListener<'input> + 'a)) { listener.exit_preset_call(self); listener.exit_every_rule(self); } } impl<'input,'a> Visitable<dyn DesignVisitor<'input> + 'a> for Preset_callContext<'input>{ fn accept(&self,visitor: &mut (dyn DesignVisitor<'input> + 'a)) { visitor.visit_preset_call(self); } } impl<'input> CustomRuleContext<'input> for Preset_callContextExt<'input>{ type TF = LocalTokenFactory<'input>; type Ctx = DesignParserContextType; fn get_rule_index(&self) -> usize { RULE_preset_call } //fn type_rule_index() -> usize where Self: Sized { RULE_preset_call } } antlr_rust::type_id!{Preset_callContextExt<'a>} impl<'input> Preset_callContextExt<'input>{ fn new(parent: Option<Rc<dyn DesignParserContext<'input> + 'input > >, invoking_state: isize) -> Rc<Preset_callContextAll<'input>> { Rc::new( BaseParserRuleContext::new_parser_ctx(parent, invoking_state,Preset_callContextExt{ ph:PhantomData }), ) } } pub trait Preset_callContextAttrs<'input>: DesignParserContext<'input> + BorrowMut<Preset_callContextExt<'input>>{ fn library_name(&self) -> Option<Rc<Library_nameContextAll<'input>>> where Self:Sized{ self.child_of_type(0) } /// Retrieves first TerminalNode corresponding to token DOT /// Returns `None` if there is no child corresponding to token DOT fn DOT(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(DOT, 0) } /// Retrieves first TerminalNode corresponding to token IDENTIFIER /// Returns `None` if there is no child corresponding to token IDENTIFIER fn IDENTIFIER(&self) -> Option<Rc<TerminalNode<'input,DesignParserContextType>>> where Self:Sized{ self.get_token(IDENTIFIER, 0) } } impl<'input> Preset_callContextAttrs<'input> for Preset_callContext<'input>{} impl<'input, I, H> DesignParser<'input, I, H> where I: TokenStream<'input, TF = LocalTokenFactory<'input> > + TidAble<'input>, H: ErrorStrategy<'input,BaseParserType<'input,I>> { pub fn preset_call(&mut self,) -> Result<Rc<Preset_callContextAll<'input>>,ANTLRError> { let mut recog = self; let _parentctx = recog.ctx.take(); let mut _localctx = Preset_callContextExt::new(_parentctx.clone(), recog.base.get_state()); recog.base.enter_rule(_localctx.clone(), 72, RULE_preset_call); let mut _localctx: Rc<Preset_callContextAll> = _localctx; let result: Result<(), ANTLRError> = try { //recog.base.enter_outer_alt(_localctx.clone(), 1); recog.base.enter_outer_alt(None, 1); { /*InvokeRule library_name*/ recog.base.set_state(343); recog.library_name()?; recog.base.set_state(344); recog.base.match_token(DOT,&mut recog.err_handler)?; recog.base.set_state(345); recog.base.match_token(IDENTIFIER,&mut recog.err_handler)?; } }; match result { Ok(_)=>{}, Err(e @ ANTLRError::FallThrough(_)) => return Err(e), Err(ref re) => { //_localctx.exception = re; recog.err_handler.report_error(&mut recog.base, re); recog.err_handler.recover(&mut recog.base, re)?; } } recog.base.exit_rule(); Ok(_localctx) } } lazy_static! { static ref _ATN: Arc<ATN> = Arc::new(ATNDeserializer::new(None).deserialize(_serializedATN.chars())); static ref _decision_to_DFA: Arc<Vec<antlr_rust::RwLock<DFA>>> = { let mut dfa = Vec::new(); let size = _ATN.decision_to_state.len(); for i in 0..size { dfa.push(DFA::new( _ATN.clone(), _ATN.get_decision_state(i), i as isize, ).into()) } Arc::new(dfa) }; } const _serializedATN:&'static str = "\x03\u{608b}\u{a72a}\u{8133}\u{b9ed}\u{417c}\u{3be7}\u{7786}\u{5964}\x03\ \x2f\u{15e}\x04\x02\x09\x02\x04\x03\x09\x03\x04\x04\x09\x04\x04\x05\x09\ \x05\x04\x06\x09\x06\x04\x07\x09\x07\x04\x08\x09\x08\x04\x09\x09\x09\x04\ \x0a\x09\x0a\x04\x0b\x09\x0b\x04\x0c\x09\x0c\x04\x0d\x09\x0d\x04\x0e\x09\ \x0e\x04\x0f\x09\x0f\x04\x10\x09\x10\x04\x11\x09\x11\x04\x12\x09\x12\x04\ \x13\x09\x13\x04\x14\x09\x14\x04\x15\x09\x15\x04\x16\x09\x16\x04\x17\x09\ \x17\x04\x18\x09\x18\x04\x19\x09\x19\x04\x1a\x09\x1a\x04\x1b\x09\x1b\x04\ \x1c\x09\x1c\x04\x1d\x09\x1d\x04\x1e\x09\x1e\x04\x1f\x09\x1f\x04\x20\x09\ \x20\x04\x21\x09\x21\x04\x22\x09\x22\x04\x23\x09\x23\x04\x24\x09\x24\x04\ \x25\x09\x25\x04\x26\x09\x26\x03\x02\x07\x02\x4e\x0a\x02\x0c\x02\x0e\x02\ \x51\x0b\x02\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\x03\ \x03\x03\x03\x05\x03\x5c\x0a\x03\x03\x04\x03\x04\x03\x04\x03\x04\x03\x05\ \x03\x05\x03\x06\x03\x06\x05\x06\x66\x0a\x06\x03\x06\x03\x06\x05\x06\x6a\ \x0a\x06\x03\x06\x03\x06\x05\x06\x6e\x0a\x06\x03\x06\x03\x06\x03\x06\x05\ \x06\x73\x0a\x06\x03\x06\x05\x06\x76\x0a\x06\x03\x07\x03\x07\x03\x08\x03\ \x08\x03\x08\x03\x08\x07\x08\x7e\x0a\x08\x0c\x08\x0e\x08\u{81}\x0b\x08\x03\ \x08\x03\x08\x03\x09\x03\x09\x03\x09\x05\x09\u{88}\x0a\x09\x03\x0a\x03\x0a\ \x03\x0a\x03\x0a\x03\x0a\x05\x0a\u{8f}\x0a\x0a\x03\x0b\x03\x0b\x03\x0b\x03\ \x0b\x03\x0b\x03\x0b\x03\x0b\x03\x0b\x03\x0c\x03\x0c\x05\x0c\u{9b}\x0a\x0c\ \x03\x0c\x03\x0c\x03\x0c\x05\x0c\u{a0}\x0a\x0c\x03\x0d\x03\x0d\x03\x0d\x03\ \x0d\x03\x0d\x03\x0d\x03\x0e\x03\x0e\x05\x0e\u{aa}\x0a\x0e\x03\x0f\x03\x0f\ \x03\x0f\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x11\x03\x11\x03\x12\ \x03\x12\x03\x13\x03\x13\x03\x14\x03\x14\x03\x15\x03\x15\x03\x15\x03\x15\ \x07\x15\u{c0}\x0a\x15\x0c\x15\x0e\x15\u{c3}\x0b\x15\x03\x15\x03\x15\x03\ \x16\x03\x16\x03\x16\x03\x16\x07\x16\u{cb}\x0a\x16\x0c\x16\x0e\x16\u{ce}\ \x0b\x16\x03\x16\x03\x16\x03\x17\x03\x17\x03\x17\x07\x17\u{d5}\x0a\x17\x0c\ \x17\x0e\x17\u{d8}\x0b\x17\x03\x17\x03\x17\x03\x17\x03\x17\x05\x17\u{de}\ \x0a\x17\x03\x18\x03\x18\x03\x18\x03\x18\x07\x18\u{e4}\x0a\x18\x0c\x18\x0e\ \x18\u{e7}\x0b\x18\x03\x18\x03\x18\x03\x19\x03\x19\x07\x19\u{ed}\x0a\x19\ \x0c\x19\x0e\x19\u{f0}\x0b\x19\x03\x19\x03\x19\x03\x19\x03\x19\x03\x19\x07\ \x19\u{f7}\x0a\x19\x0c\x19\x0e\x19\u{fa}\x0b\x19\x03\x19\x03\x19\x05\x19\ \u{fe}\x0a\x19\x03\x1a\x03\x1a\x03\x1a\x03\x1a\x03\x1a\x03\x1a\x03\x1a\x07\ \x1a\u{107}\x0a\x1a\x0c\x1a\x0e\x1a\u{10a}\x0b\x1a\x03\x1a\x03\x1a\x05\x1a\ \u{10e}\x0a\x1a\x03\x1a\x05\x1a\u{111}\x0a\x1a\x03\x1b\x03\x1b\x03\x1c\x03\ \x1c\x03\x1c\x03\x1c\x03\x1c\x03\x1c\x03\x1d\x03\x1d\x03\x1e\x03\x1e\x03\ \x1e\x07\x1e\u{120}\x0a\x1e\x0c\x1e\x0e\x1e\u{123}\x0b\x1e\x03\x1f\x03\x1f\ \x03\x20\x03\x20\x03\x20\x03\x20\x07\x20\u{12b}\x0a\x20\x0c\x20\x0e\x20\ \u{12e}\x0b\x20\x03\x20\x03\x20\x03\x21\x03\x21\x03\x21\x03\x21\x05\x21\ \u{136}\x0a\x21\x03\x21\x05\x21\u{139}\x0a\x21\x03\x21\x03\x21\x03\x21\x07\ \x21\u{13e}\x0a\x21\x0c\x21\x0e\x21\u{141}\x0b\x21\x03\x21\x03\x21\x05\x21\ \u{145}\x0a\x21\x03\x22\x03\x22\x03\x22\x03\x22\x03\x23\x03\x23\x03\x24\ \x03\x24\x03\x25\x03\x25\x03\x25\x03\x25\x07\x25\u{153}\x0a\x25\x0c\x25\ \x0e\x25\u{156}\x0b\x25\x03\x25\x03\x25\x03\x26\x03\x26\x03\x26\x03\x26\ \x03\x26\x02\x02\x27\x02\x04\x06\x08\x0a\x0c\x0e\x10\x12\x14\x16\x18\x1a\ \x1c\x1e\x20\x22\x24\x26\x28\x2a\x2c\x2e\x30\x32\x34\x36\x38\x3a\x3c\x3e\ \x40\x42\x44\x46\x48\x4a\x02\x04\x03\x02\x03\x05\x06\x02\x17\x17\x19\x19\ \x26\x26\x28\x28\x02\u{162}\x02\x4f\x03\x02\x02\x02\x04\x5b\x03\x02\x02\ \x02\x06\x5d\x03\x02\x02\x02\x08\x61\x03\x02\x02\x02\x0a\x75\x03\x02\x02\ \x02\x0c\x77\x03\x02\x02\x02\x0e\x79\x03\x02\x02\x02\x10\u{87}\x03\x02\x02\ \x02\x12\u{89}\x03\x02\x02\x02\x14\u{90}\x03\x02\x02\x02\x16\u{98}\x03\x02\ \x02\x02\x18\u{a1}\x03\x02\x02\x02\x1a\u{a9}\x03\x02\x02\x02\x1c\u{ab}\x03\ \x02\x02\x02\x1e\u{ae}\x03\x02\x02\x02\x20\u{b3}\x03\x02\x02\x02\x22\u{b5}\ \x03\x02\x02\x02\x24\u{b7}\x03\x02\x02\x02\x26\u{b9}\x03\x02\x02\x02\x28\ \u{bb}\x03\x02\x02\x02\x2a\u{c6}\x03\x02\x02\x02\x2c\u{dd}\x03\x02\x02\x02\ \x2e\u{df}\x03\x02\x02\x02\x30\u{fd}\x03\x02\x02\x02\x32\u{110}\x03\x02\ \x02\x02\x34\u{112}\x03\x02\x02\x02\x36\u{114}\x03\x02\x02\x02\x38\u{11a}\ \x03\x02\x02\x02\x3a\u{121}\x03\x02\x02\x02\x3c\u{124}\x03\x02\x02\x02\x3e\ \u{126}\x03\x02\x02\x02\x40\u{144}\x03\x02\x02\x02\x42\u{146}\x03\x02\x02\ \x02\x44\u{14a}\x03\x02\x02\x02\x46\u{14c}\x03\x02\x02\x02\x48\u{14e}\x03\ \x02\x02\x02\x4a\u{159}\x03\x02\x02\x02\x4c\x4e\x05\x04\x03\x02\x4d\x4c\ \x03\x02\x02\x02\x4e\x51\x03\x02\x02\x02\x4f\x4d\x03\x02\x02\x02\x4f\x50\ \x03\x02\x02\x02\x50\x52\x03\x02\x02\x02\x51\x4f\x03\x02\x02\x02\x52\x53\ \x07\x02\x02\x03\x53\x03\x03\x02\x02\x02\x54\x5c\x05\x06\x04\x02\x55\x5c\ \x05\x0e\x08\x02\x56\x5c\x05\x28\x15\x02\x57\x5c\x05\x36\x1c\x02\x58\x5c\ \x05\x2a\x16\x02\x59\x5c\x05\x3e\x20\x02\x5a\x5c\x05\x2e\x18\x02\x5b\x54\ \x03\x02\x02\x02\x5b\x55\x03\x02\x02\x02\x5b\x56\x03\x02\x02\x02\x5b\x57\ \x03\x02\x02\x02\x5b\x58\x03\x02\x02\x02\x5b\x59\x03\x02\x02\x02\x5b\x5a\ \x03\x02\x02\x02\x5c\x05\x03\x02\x02\x02\x5d\x5e\x05\x08\x05\x02\x5e\x5f\ \x07\x22\x02\x02\x5f\x60\x05\x0a\x06\x02\x60\x07\x03\x02\x02\x02\x61\x62\ \x07\x26\x02\x02\x62\x09\x03\x02\x02\x02\x63\x65\x07\x28\x02\x02\x64\x66\ \x05\x0c\x07\x02\x65\x64\x03\x02\x02\x02\x65\x66\x03\x02\x02\x02\x66\x76\ \x03\x02\x02\x02\x67\x69\x07\x29\x02\x02\x68\x6a\x05\x0c\x07\x02\x69\x68\ \x03\x02\x02\x02\x69\x6a\x03\x02\x02\x02\x6a\x76\x03\x02\x02\x02\x6b\x6d\ \x07\x2a\x02\x02\x6c\x6e\x05\x0c\x07\x02\x6d\x6c\x03\x02\x02\x02\x6d\x6e\ \x03\x02\x02\x02\x6e\x76\x03\x02\x02\x02\x6f\x72\x07\x26\x02\x02\x70\x71\ \x07\x24\x02\x02\x71\x73\x07\x26\x02\x02\x72\x70\x03\x02\x02\x02\x72\x73\ \x03\x02\x02\x02\x73\x76\x03\x02\x02\x02\x74\x76\x07\x19\x02\x02\x75\x63\ \x03\x02\x02\x02\x75\x67\x03\x02\x02\x02\x75\x6b\x03\x02\x02\x02\x75\x6f\ \x03\x02\x02\x02\x75\x74\x03\x02\x02\x02\x76\x0b\x03\x02\x02\x02\x77\x78\ \x09\x02\x02\x02\x78\x0d\x03\x02\x02\x02\x79\x7a\x07\x0d\x02\x02\x7a\x7b\ \x07\x26\x02\x02\x7b\x7f\x07\x1c\x02\x02\x7c\x7e\x05\x10\x09\x02\x7d\x7c\ \x03\x02\x02\x02\x7e\u{81}\x03\x02\x02\x02\x7f\x7d\x03\x02\x02\x02\x7f\u{80}\ \x03\x02\x02\x02\u{80}\u{82}\x03\x02\x02\x02\u{81}\x7f\x03\x02\x02\x02\u{82}\ \u{83}\x07\x1d\x02\x02\u{83}\x0f\x03\x02\x02\x02\u{84}\u{88}\x05\x12\x0a\ \x02\u{85}\u{88}\x05\x14\x0b\x02\u{86}\u{88}\x05\x16\x0c\x02\u{87}\u{84}\ \x03\x02\x02\x02\u{87}\u{85}\x03\x02\x02\x02\u{87}\u{86}\x03\x02\x02\x02\ \u{88}\x11\x03\x02\x02\x02\u{89}\u{8e}\x07\x0e\x02\x02\u{8a}\u{8f}\x07\x26\ \x02\x02\u{8b}\u{8c}\x07\x19\x02\x02\u{8c}\u{8d}\x07\x23\x02\x02\u{8d}\u{8f}\ \x05\x22\x12\x02\u{8e}\u{8a}\x03\x02\x02\x02\u{8e}\u{8b}\x03\x02\x02\x02\ \u{8f}\x13\x03\x02\x02\x02\u{90}\u{91}\x07\x0f\x02\x02\u{91}\u{92}\x07\x1e\ \x02\x02\u{92}\u{93}\x05\x20\x11\x02\u{93}\u{94}\x07\x1f\x02\x02\u{94}\u{95}\ \x07\x19\x02\x02\u{95}\u{96}\x07\x23\x02\x02\u{96}\u{97}\x05\x22\x12\x02\ \u{97}\x15\x03\x02\x02\x02\u{98}\u{9a}\x07\x10\x02\x02\u{99}\u{9b}\x05\x24\ \x13\x02\u{9a}\u{99}\x03\x02\x02\x02\u{9a}\u{9b}\x03\x02\x02\x02\u{9b}\u{9c}\ \x03\x02\x02\x02\u{9c}\u{9d}\x07\x22\x02\x02\u{9d}\u{9f}\x05\x1a\x0e\x02\ \u{9e}\u{a0}\x05\x18\x0d\x02\u{9f}\u{9e}\x03\x02\x02\x02\u{9f}\u{a0}\x03\ \x02\x02\x02\u{a0}\x17\x03\x02\x02\x02\u{a1}\u{a2}\x07\x11\x02\x02\u{a2}\ \u{a3}\x07\x12\x02\x02\u{a3}\u{a4}\x07\x1a\x02\x02\u{a4}\u{a5}\x05\x26\x14\ \x02\u{a5}\u{a6}\x07\x1b\x02\x02\u{a6}\x19\x03\x02\x02\x02\u{a7}\u{aa}\x05\ \x1c\x0f\x02\u{a8}\u{aa}\x05\x1e\x10\x02\u{a9}\u{a7}\x03\x02\x02\x02\u{a9}\ \u{a8}\x03\x02\x02\x02\u{aa}\x1b\x03\x02\x02\x02\u{ab}\u{ac}\x07\x0b\x02\ \x02\u{ac}\u{ad}\x05\x22\x12\x02\u{ad}\x1d\x03\x02\x02\x02\u{ae}\u{af}\x07\ \x0c\x02\x02\u{af}\u{b0}\x07\x19\x02\x02\u{b0}\u{b1}\x07\x23\x02\x02\u{b1}\ \u{b2}\x05\x22\x12\x02\u{b2}\x1f\x03\x02\x02\x02\u{b3}\u{b4}\x07\x26\x02\ \x02\u{b4}\x21\x03\x02\x02\x02\u{b5}\u{b6}\x07\x26\x02\x02\u{b6}\x23\x03\ \x02\x02\x02\u{b7}\u{b8}\x07\x26\x02\x02\u{b8}\x25\x03\x02\x02\x02\u{b9}\ \u{ba}\x07\x26\x02\x02\u{ba}\x27\x03\x02\x02\x02\u{bb}\u{bc}\x07\x13\x02\ \x02\u{bc}\u{bd}\x07\x26\x02\x02\u{bd}\u{c1}\x07\x1c\x02\x02\u{be}\u{c0}\ \x05\x2c\x17\x02\u{bf}\u{be}\x03\x02\x02\x02\u{c0}\u{c3}\x03\x02\x02\x02\ \u{c1}\u{bf}\x03\x02\x02\x02\u{c1}\u{c2}\x03\x02\x02\x02\u{c2}\u{c4}\x03\ \x02\x02\x02\u{c3}\u{c1}\x03\x02\x02\x02\u{c4}\u{c5}\x07\x1d\x02\x02\u{c5}\ \x29\x03\x02\x02\x02\u{c6}\u{c7}\x07\x15\x02\x02\u{c7}\u{c8}\x07\x26\x02\ \x02\u{c8}\u{cc}\x07\x1c\x02\x02\u{c9}\u{cb}\x05\x2c\x17\x02\u{ca}\u{c9}\ \x03\x02\x02\x02\u{cb}\u{ce}\x03\x02\x02\x02\u{cc}\u{ca}\x03\x02\x02\x02\ \u{cc}\u{cd}\x03\x02\x02\x02\u{cd}\u{cf}\x03\x02\x02\x02\u{ce}\u{cc}\x03\ \x02\x02\x02\u{cf}\u{d0}\x07\x1d\x02\x02\u{d0}\x2b\x03\x02\x02\x02\u{d1}\ \u{d6}\x05\x22\x12\x02\u{d2}\u{d3}\x07\x24\x02\x02\u{d3}\u{d5}\x05\x22\x12\ \x02\u{d4}\u{d2}\x03\x02\x02\x02\u{d5}\u{d8}\x03\x02\x02\x02\u{d6}\u{d4}\ \x03\x02\x02\x02\u{d6}\u{d7}\x03\x02\x02\x02\u{d7}\u{de}\x03\x02\x02\x02\ \u{d8}\u{d6}\x03\x02\x02\x02\u{d9}\u{da}\x05\x08\x05\x02\u{da}\u{db}\x07\ \x22\x02\x02\u{db}\u{dc}\x05\x0a\x06\x02\u{dc}\u{de}\x03\x02\x02\x02\u{dd}\ \u{d1}\x03\x02\x02\x02\u{dd}\u{d9}\x03\x02\x02\x02\u{de}\x2d\x03\x02\x02\ \x02\u{df}\u{e0}\x07\x16\x02\x02\u{e0}\u{e1}\x07\x26\x02\x02\u{e1}\u{e5}\ \x07\x1c\x02\x02\u{e2}\u{e4}\x05\x30\x19\x02\u{e3}\u{e2}\x03\x02\x02\x02\ \u{e4}\u{e7}\x03\x02\x02\x02\u{e5}\u{e3}\x03\x02\x02\x02\u{e5}\u{e6}\x03\ \x02\x02\x02\u{e6}\u{e8}\x03\x02\x02\x02\u{e7}\u{e5}\x03\x02\x02\x02\u{e8}\ \u{e9}\x07\x1d\x02\x02\u{e9}\x2f\x03\x02\x02\x02\u{ea}\u{ee}\x07\x06\x02\ \x02\u{eb}\u{ed}\x07\x06\x02\x02\u{ec}\u{eb}\x03\x02\x02\x02\u{ed}\u{f0}\ \x03\x02\x02\x02\u{ee}\u{ec}\x03\x02\x02\x02\u{ee}\u{ef}\x03\x02\x02\x02\ \u{ef}\u{fe}\x03\x02\x02\x02\u{f0}\u{ee}\x03\x02\x02\x02\u{f1}\u{f2}\x07\ \x07\x02\x02\u{f2}\u{f3}\x05\x32\x1a\x02\u{f3}\u{f8}\x03\x02\x02\x02\u{f4}\ \u{f5}\x07\x07\x02\x02\u{f5}\u{f7}\x05\x32\x1a\x02\u{f6}\u{f4}\x03\x02\x02\ \x02\u{f7}\u{fa}\x03\x02\x02\x02\u{f8}\u{f6}\x03\x02\x02\x02\u{f8}\u{f9}\ \x03\x02\x02\x02\u{f9}\u{fb}\x03\x02\x02\x02\u{fa}\u{f8}\x03\x02\x02\x02\ \u{fb}\u{fc}\x07\x07\x02\x02\u{fc}\u{fe}\x03\x02\x02\x02\u{fd}\u{ea}\x03\ \x02\x02\x02\u{fd}\u{f1}\x03\x02\x02\x02\u{fe}\x31\x03\x02\x02\x02\u{ff}\ \u{111}\x07\x29\x02\x02\u{100}\u{111}\x07\x17\x02\x02\u{101}\u{10d}\x05\ \x22\x12\x02\u{102}\u{103}\x07\x1a\x02\x02\u{103}\u{108}\x05\x34\x1b\x02\ \u{104}\u{105}\x07\x24\x02\x02\u{105}\u{107}\x05\x34\x1b\x02\u{106}\u{104}\ \x03\x02\x02\x02\u{107}\u{10a}\x03\x02\x02\x02\u{108}\u{106}\x03\x02\x02\ \x02\u{108}\u{109}\x03\x02\x02\x02\u{109}\u{10b}\x03\x02\x02\x02\u{10a}\ \u{108}\x03\x02\x02\x02\u{10b}\u{10c}\x07\x1b\x02\x02\u{10c}\u{10e}\x03\ \x02\x02\x02\u{10d}\u{102}\x03\x02\x02\x02\u{10d}\u{10e}\x03\x02\x02\x02\ \u{10e}\u{111}\x03\x02\x02\x02\u{10f}\u{111}\x07\x19\x02\x02\u{110}\u{ff}\ \x03\x02\x02\x02\u{110}\u{100}\x03\x02\x02\x02\u{110}\u{101}\x03\x02\x02\ \x02\u{110}\u{10f}\x03\x02\x02\x02\u{111}\x33\x03\x02\x02\x02\u{112}\u{113}\ \x09\x03\x02\x02\u{113}\x35\x03\x02\x02\x02\u{114}\u{115}\x07\x18\x02\x02\ \u{115}\u{116}\x05\x38\x1d\x02\u{116}\u{117}\x07\x1c\x02\x02\u{117}\u{118}\ \x05\x3a\x1e\x02\u{118}\u{119}\x07\x1d\x02\x02\u{119}\x37\x03\x02\x02\x02\ \u{11a}\u{11b}\x07\x26\x02\x02\u{11b}\x39\x03\x02\x02\x02\u{11c}\u{11d}\ \x05\x06\x04\x02\u{11d}\u{11e}\x07\x08\x02\x02\u{11e}\u{120}\x03\x02\x02\ \x02\u{11f}\u{11c}\x03\x02\x02\x02\u{120}\u{123}\x03\x02\x02\x02\u{121}\ \u{11f}\x03\x02\x02\x02\u{121}\u{122}\x03\x02\x02\x02\u{122}\x3b\x03\x02\ \x02\x02\u{123}\u{121}\x03\x02\x02\x02\u{124}\u{125}\x07\x26\x02\x02\u{125}\ \x3d\x03\x02\x02\x02\u{126}\u{127}\x07\x14\x02\x02\u{127}\u{128}\x05\x3c\ \x1f\x02\u{128}\u{12c}\x07\x1c\x02\x02\u{129}\u{12b}\x05\x40\x21\x02\u{12a}\ \u{129}\x03\x02\x02\x02\u{12b}\u{12e}\x03\x02\x02\x02\u{12c}\u{12a}\x03\ \x02\x02\x02\u{12c}\u{12d}\x03\x02\x02\x02\u{12d}\u{12f}\x03\x02\x02\x02\ \u{12e}\u{12c}\x03\x02\x02\x02\u{12f}\u{130}\x07\x1d\x02\x02\u{130}\x3f\ \x03\x02\x02\x02\u{131}\u{132}\x05\x44\x23\x02\u{132}\u{135}\x07\x09\x02\ \x02\u{133}\u{136}\x05\x46\x24\x02\u{134}\u{136}\x05\x48\x25\x02\u{135}\ \u{133}\x03\x02\x02\x02\u{135}\u{134}\x03\x02\x02\x02\u{136}\u{138}\x03\ \x02\x02\x02\u{137}\u{139}\x07\x08\x02\x02\u{138}\u{137}\x03\x02\x02\x02\ \u{138}\u{139}\x03\x02\x02\x02\u{139}\u{145}\x03\x02\x02\x02\u{13a}\u{13b}\ \x05\x44\x23\x02\u{13b}\u{13f}\x07\x1c\x02\x02\u{13c}\u{13e}\x05\x42\x22\ \x02\u{13d}\u{13c}\x03\x02\x02\x02\u{13e}\u{141}\x03\x02\x02\x02\u{13f}\ \u{13d}\x03\x02\x02\x02\u{13f}\u{140}\x03\x02\x02\x02\u{140}\u{142}\x03\ \x02\x02\x02\u{141}\u{13f}\x03\x02\x02\x02\u{142}\u{143}\x07\x1d\x02\x02\ \u{143}\u{145}\x03\x02\x02\x02\u{144}\u{131}\x03\x02\x02\x02\u{144}\u{13a}\ \x03\x02\x02\x02\u{145}\x41\x03\x02\x02\x02\u{146}\u{147}\x05\x44\x23\x02\ \u{147}\u{148}\x07\x09\x02\x02\u{148}\u{149}\x05\x46\x24\x02\u{149}\x43\ \x03\x02\x02\x02\u{14a}\u{14b}\x07\x26\x02\x02\u{14b}\x45\x03\x02\x02\x02\ \u{14c}\u{14d}\x05\x0a\x06\x02\u{14d}\x47\x03\x02\x02\x02\u{14e}\u{14f}\ \x07\x1e\x02\x02\u{14f}\u{154}\x05\x4a\x26\x02\u{150}\u{151}\x07\x24\x02\ \x02\u{151}\u{153}\x05\x4a\x26\x02\u{152}\u{150}\x03\x02\x02\x02\u{153}\ \u{156}\x03\x02\x02\x02\u{154}\u{152}\x03\x02\x02\x02\u{154}\u{155}\x03\ \x02\x02\x02\u{155}\u{157}\x03\x02\x02\x02\u{156}\u{154}\x03\x02\x02\x02\ \u{157}\u{158}\x07\x1f\x02\x02\u{158}\x49\x03\x02\x02\x02\u{159}\u{15a}\ \x05\x3c\x1f\x02\u{15a}\u{15b}\x07\x23\x02\x02\u{15b}\u{15c}\x07\x26\x02\ \x02\u{15c}\x4b\x03\x02\x02\x02\x21\x4f\x5b\x65\x69\x6d\x72\x75\x7f\u{87}\ \u{8e}\u{9a}\u{9f}\u{a9}\u{c1}\u{cc}\u{d6}\u{dd}\u{e5}\u{ee}\u{f8}\u{fd}\ \u{108}\u{10d}\u{110}\u{121}\u{12c}\u{135}\u{138}\u{13f}\u{144}\u{154}";
//! Displays spheres with physically based materials. extern crate amethyst; extern crate cgmath; extern crate futures; extern crate genmesh; use amethyst::assets::{AssetFuture, BoxedErr}; use amethyst::ecs::rendering::{AmbientColor, Factory, LightComponent, MaterialComponent, MeshComponent, RenderBundle}; use amethyst::ecs::transform::Transform; use amethyst::prelude::*; use amethyst::renderer::Config as DisplayConfig; use amethyst::renderer::prelude::*; use cgmath::{Deg, Matrix4, Vector3}; use cgmath::prelude::InnerSpace; use futures::{Future, IntoFuture}; use genmesh::{MapToVertices, Triangulate, Vertices}; use genmesh::generators::SphereUV; struct Example; fn load_proc_asset<T, F>(engine: &mut Engine, f: F) -> AssetFuture<T::Item> where T: IntoFuture<Error = BoxedErr>, T::Future: 'static, F: FnOnce(&mut Engine) -> T, { let future = f(engine).into_future(); let future: Box<Future<Item = T::Item, Error = BoxedErr>> = Box::new(future); AssetFuture(future.shared()) } impl State for Example { fn on_start(&mut self, engine: &mut Engine) { let verts = gen_sphere(32, 32); let mesh = Mesh::build(verts); let tex = Texture::from_color_val([1.0, 1.0, 1.0, 1.0]); let mtl = MaterialBuilder::new().with_albedo(tex); println!("Load mesh"); let mesh = load_proc_asset(engine, move |engine| { let factory = engine.world.read_resource::<Factory>(); factory .create_mesh(mesh) .map(MeshComponent::new) .map_err(BoxedErr::new) }); println!("Create spheres"); for i in 0..5 { for j in 0..5 { let roughness = 1.0f32 * (i as f32 / 4.0f32); let metallic = 1.0f32 * (j as f32 / 4.0f32); let pos = Matrix4::from_translation( [2.0f32 * (i - 2) as f32, 2.0f32 * (j - 2) as f32, 0.0].into(), ); let metallic = Texture::from_color_val([metallic, metallic, metallic, 1.0]); let roughness = Texture::from_color_val([roughness, roughness, roughness, 1.0]); let mtl = mtl.clone() .with_metallic(metallic) .with_roughness(roughness); let mtl = load_proc_asset(engine, move |engine| { let factory = engine.world.read_resource::<Factory>(); factory .create_material(mtl) .map(MaterialComponent) .map_err(BoxedErr::new) }); engine .world .create_entity() .with(Transform(pos.into())) .with(mesh.clone()) .with(mtl) .build(); } } println!("Create lights"); engine .world .create_entity() .with(LightComponent( PointLight { center: [6.0, 6.0, -6.0].into(), intensity: 6.0, color: [0.8, 0.0, 0.0].into(), ..PointLight::default() }.into(), )) .build(); engine .world .create_entity() .with(LightComponent( PointLight { center: [6.0, -6.0, -6.0].into(), intensity: 5.0, color: [0.0, 0.3, 0.7].into(), ..PointLight::default() }.into(), )) .build(); println!("Put camera"); engine.world.add_resource(Camera { eye: [0.0, 0.0, -12.0].into(), proj: Projection::perspective(1.3, Deg(60.0)).into(), forward: [0.0, 0.0, 1.0].into(), right: [1.0, 0.0, 0.0].into(), up: [0.0, 1.0, 0.0].into(), }); } fn handle_event(&mut self, _: &mut Engine, event: Event) -> Trans { match event { Event::WindowEvent { event, .. } => match event { WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Escape), .. }, .. } | WindowEvent::Closed => Trans::Quit, _ => Trans::None, }, _ => Trans::None, } } } type DrawPbm = pass::DrawPbm< PosNormTangTex, AmbientColor, MeshComponent, MaterialComponent, Transform, LightComponent, >; fn run() -> Result<(), amethyst::Error> { let path = format!( "{}/examples/06_material/resources/config.ron", env!("CARGO_MANIFEST_DIR") ); let config = DisplayConfig::load(&path); let mut game = Application::build(Example)? .with_bundle( RenderBundle::new( Pipeline::build().with_stage( Stage::with_backbuffer() .clear_target([0.0, 0.0, 0.0, 1.0], 1.0) .with_pass(DrawPbm::new()), ), ).with_config(config), )? .build()?; Ok(game.run()) } fn main() { if let Err(e) = run() { println!("Failed to execute example: {}", e); ::std::process::exit(1); } } fn gen_sphere(u: usize, v: usize) -> Vec<PosNormTangTex> { SphereUV::new(u, v) .vertex(|(x, y, z)| { let normal = Vector3::from([x, y, z]).normalize(); let up = Vector3::from([0.0, 1.0, 0.0]); let tangent = normal.cross(up).cross(normal); PosNormTangTex { position: [x, y, z], normal: normal.into(), tangent: tangent.into(), tex_coord: [0.1, 0.1], } }) .triangulate() .vertices() .collect() }
use crate::solutions::Solution; pub struct Day2 {} impl Day2 { fn run(&self, input: String, layout: impl Layout) { let mut code = String::new(); let mut key_pad = KeyPad::new(layout); for sequence in parse_input(&input) { key_pad.steps(sequence); code.push(key_pad.as_char()); } println!("{}", code.to_ascii_uppercase()); } } impl Solution for Day2 { fn part1(&self, input: String) { self.run(input, Square::new()); } fn part2(&self, input: String) { self.run(input, Diamond::new()); } } #[derive(Copy, Clone)] struct KeyPad<T: Layout> { digit: u32, layout: T, } impl<T: Layout> KeyPad<T> { fn new(layout: T) -> KeyPad<T> { KeyPad { digit: 5, layout } } fn steps(&mut self, directions: impl Iterator<Item = Direction>) { for direction in directions { self.step(direction) } } fn step(&mut self, direction: Direction) { use Direction::*; self.digit = match direction { Up => self.layout.up(self.digit), Down => self.layout.down(self.digit), Right => self.layout.right(self.digit), Left => self.layout.left(self.digit), } } fn as_char(&self) -> char { std::char::from_digit(self.digit, 16).unwrap() } } trait Layout { fn up(&self, digit: u32) -> u32; fn down(&self, digit: u32) -> u32; fn left(&self, digit: u32) -> u32; fn right(&self, digit: u32) -> u32; } struct Square {} impl Square { fn new() -> Square { Square {} } } impl Layout for Square { fn up(&self, digit: u32) -> u32 { if digit > 3 { digit - 3 } else { digit } } fn down(&self, digit: u32) -> u32 { if digit < 7 { digit + 3 } else { digit } } fn right(&self, digit: u32) -> u32 { if digit % 3 != 0 { digit + 1 } else { digit } } fn left(&self, digit: u32) -> u32 { if digit % 3 != 1 { digit - 1 } else { digit } } } struct Diamond {} impl Diamond { fn new() -> Diamond { Diamond {} } } impl Layout for Diamond { fn up(&self, digit: u32) -> u32 { match digit { 5 | 2 | 1 | 4 | 9 => digit, 3 => 1, 6 | 7 | 8 | 0xA | 0xB | 0xC => digit - 4, 0xD => 0xB, _ => panic!("unreachable"), } } fn down(&self, digit: u32) -> u32 { match digit { 5 | 0xA | 0xD | 0xC | 9 => digit, 0xB => 0xD, 2 | 3 | 4 | 6 | 7 | 8 => digit + 4, 1 => 3, _ => panic!("unreachable"), } } fn right(&self, digit: u32) -> u32 { match digit { 1 | 4 | 9 | 0xC | 0xD => digit, 8 | 7 | 6 | 5 | 3 | 2 | 0xA | 0xB => digit + 1, _ => panic!("unreachable"), } } fn left(&self, digit: u32) -> u32 { match digit { 1 | 2 | 5 | 0xA | 0xD => digit, 3 | 4 | 6 | 7 | 8 | 9 | 0xB | 0xC => digit - 1, _ => panic!("unreachable"), } } } #[derive(Copy, Clone)] enum Direction { Left, Right, Up, Down, } impl Direction { fn from(l: char) -> Direction { use Direction::*; match l { 'L' => Left, 'R' => Right, 'U' => Up, 'D' => Down, _ => panic!("{:?} is an invalid Direction literal.", l), } } } fn parse_input(input: &str) -> impl Iterator<Item = impl Iterator<Item = Direction> + '_> + '_ { input .split('\n') .map(|line| line.chars().map(Direction::from)) }
use proconio::{fastout, input}; #[fastout] fn main() { input! { n: usize, k: usize, mut p_vec: [usize; n], c_vec: [i64; n], }; for i in 0..n { p_vec[i] -= 1; } let mut ans = i64::MIN; for i in 0..n { let mut x = i; let mut s_vec: Vec<i64> = Vec::new(); let mut tot: i64 = 0; loop { x = p_vec[x]; s_vec.push(c_vec[x]); tot += c_vec[x]; if x == i { break; } } // println!("test"); let l = s_vec.len(); let mut t = 0; for ii in 0..l { t += s_vec[ii]; if (ii + 1) > k { break; } let mut now = t; if tot > 0 { let e = (k - (ii + 1)) / l; now += tot * e as i64; // println!("{}", now); } ans = ans.max(now); } } println!("{}", ans); }
use super::{ Action, ToExile}; use super::settings; use rapier3d::{ dynamics::{ RigidBodyBuilder, BodyStatus, RigidBodySet, RigidBodyHandle, JointSet, }, geometry::{ ColliderSet, ColliderBuilder, }, na::{ Vector3, geometry::UnitQuaternion, }, na, }; use dotrix::{ Transform, Pipeline, pbr:: { Model, Material, }, services::{ Assets, World, Camera, Input, }, math::{ Point3, Vec3, Quat, }, ecs::{ Mut, Const, Entity, }, }; use std::f32::consts::PI; use crate::beam; #[derive(Debug)] pub struct Stats { pub is_player: bool, pub charge: f32, // drone battery state of charge (0-100%) pub strike_charge: f32, // energy to be used when strike is activated (0-100%) pub health: f32, pub x: f32, pub y: f32, pub z: f32, pub dist_to_beam: f32 } impl Default for Stats { fn default() -> Self { Self { is_player: false, charge: 0.0, strike_charge: 0.0, health: 100.0, x: 0.0, y: 0.0, z: 0.0, dist_to_beam: 0.0 } } } const D_CHARGE: f32 = 0.5; const D_HEALTH: f32 = 0.2; const D_MOVE_CHARGE: f32 = 0.05; const D_ACC_CHARGE: f32 = 0.25; const D_STRIKE_CHARGE: f32 = 0.5; const MAX_CHARGE: f32 = 100.0; const VELO_MIN: f32 = 10.0; pub fn control( world: Const<World>, mut bodies: Mut<RigidBodySet>, input: Const<Input>, mut camera: Mut<Camera>, settings: Const<settings::Settings>, mut to_exile: Mut<ToExile>, ) { // Query drone entities let query = world.query::<( &Entity, &mut Transform, &mut RigidBodyHandle, &mut Stats )>(); for (entity, transform, rigid_body, stats) in query { let body = bodies.get_mut(*rigid_body).unwrap(); let position = body.position().translation; //TO DO: rethink dw1 and dw2 usage let dw1 = UnitQuaternion::from_euler_angles(0.0, 0.0, -PI/2.0); let rotation = body.position().rotation * dw1.inverse(); if stats.is_player { let target_xz_angle = camera.xz_angle; let target_y_angle = camera.y_angle; //TO DO: rethink PI/2.0 shift let target_rotation = UnitQuaternion::from_euler_angles( 0.0, -target_xz_angle, PI/2.0 - target_y_angle ); let delta_rotation = target_rotation * rotation.inverse(); let delta_axis = match delta_rotation.axis() { Some(x) => Vector3::new( x.into_inner().data[0], x.into_inner().data[1], x.into_inner().data[2], ), None => Vector3::new(0.0, 0.0, 0.0), }; let delta_angle = delta_rotation.angle(); let rotation_euler = rotation.euler_angles(); let fwd = Vector3::new( -rotation_euler.2.sin() * rotation_euler.1.cos(), rotation_euler.1.sin(), -rotation_euler.2.cos() * rotation_euler.1.cos(), ); let side = Vector3::new( (-PI/2.0 + rotation_euler.2).sin(), 0.0, (-PI/2.0 + rotation_euler.2).cos() ); let spd = if input.is_action_hold(Action::Accelerate) & (stats.charge >= D_ACC_CHARGE) { stats.charge = stats.charge - D_ACC_CHARGE; 10.0 } else { 1.0 }; let mut dir = Vector3::new(0.0, 0.0, 0.0); if input.is_action_hold(Action::MoveForward) { dir = dir + fwd; }; if input.is_action_hold(Action::MoveBackward) { dir = dir - fwd; }; if input.is_action_hold(Action::MoveLeft) { dir = dir + side; }; if input.is_action_hold(Action::MoveRight) { dir = dir - side; }; let velo = *body.linvel(); if (dir != Vector3::new(0.0, 0.0, 0.0)) & (stats.charge >= D_MOVE_CHARGE) { dir = dir.normalize(); // compensate movement in other directions if velo != Vector3::new(0.0, 0.0, 0.0) { let comp = velo.normalize().dot(&dir)/dir.dot(&dir)*dir; dir = dir - (velo.normalize() - comp); dir = dir.normalize(); } body.apply_force(dir * spd, true); stats.charge = stats.charge - D_MOVE_CHARGE; } // drag force to limit acceleration let speed = (velo.dot(&velo)).sqrt() - VELO_MIN; if speed > 0.0 { let f_drag = -(0.1*speed + 0.002 * speed.powf(2.0)) * velo.normalize(); body.apply_force(f_drag, true); } body.apply_torque(delta_axis * delta_angle * 50.0, true); // make camera following the player camera.target = Point3::new(position.x, position.y, position.z); if input.is_action_hold(Action::Strike) & (stats.strike_charge < stats.charge) { stats.strike_charge = stats.strike_charge + D_STRIKE_CHARGE; }; if input.is_action_deactivated(Action::Strike) { body.apply_impulse(fwd * stats.strike_charge * 2.0, true); stats.charge = stats.charge - stats.strike_charge; stats.strike_charge = 0.0; }; stats.charge = stats.charge.min(MAX_CHARGE); stats.strike_charge = stats.strike_charge.min(stats.charge); } // interaction with beams let beams_query = world.query::<(&mut RigidBodyHandle, &mut beam::Stats)>(); for (beam_rigid_body, beam_stats) in beams_query { let beam_body = bodies.get_mut(*beam_rigid_body).unwrap(); let beam_position = beam_body.position().translation; let distance = na::distance( &na::Point3::new(position.x, position.y, position.z,), &na::Point3::new( beam_position.x, beam_position.y, beam_position.x) ); if distance < beam_stats.radius_near { stats.charge = stats.charge + D_CHARGE; stats.health = stats.health - D_HEALTH; } else if distance < beam_stats.radius_medium { stats.charge = stats.charge + D_CHARGE / 10.0; } else if distance > beam_stats.radius_far { stats.health = stats.health - D_HEALTH; } stats.dist_to_beam = distance; } //god mode if stats.is_player & settings.god_mode { stats.health = 100.0; } // despawn if stats.health <= 0.0 { to_exile.entity_list.push(*entity); } // apply translation to the model transform.translate.x = position.x; transform.translate.y = position.y; transform.translate.z = position.z; stats.x = position.x; stats.y = position.y; stats.z = position.z; //TO DO: rething dw1 and dw2 usage let dw2 = UnitQuaternion::from_euler_angles(0.0, 0.0, PI/2.0); let rot = rotation * dw2.inverse(); // apply rotation to the model transform.rotate = Quat::new( rot.into_inner().w, rot.into_inner().j, rot.into_inner().k, rot.into_inner().i, ); } } pub fn spawn( world: &mut World, assets: &mut Assets, bodies: &mut RigidBodySet, colliders: &mut ColliderSet, position: Point3, is_player: bool, ) { let texture = assets.register("drone::texture"); let mesh = assets.register("drone::mesh"); let rigid_body = RigidBodyBuilder::new(BodyStatus::Dynamic) .translation(position.x, position.y, position.z) .angular_damping(40.0) .additional_principal_angular_inertia(Vector3::new(0.2, 0.2, 0.2)) .linear_damping(0.0) .build(); let collider = ColliderBuilder::ball(1.0) .density(0.02) .build(); let body_handle = bodies.insert(rigid_body); colliders.insert(collider, body_handle, bodies); world.spawn(Some(( Model::from(mesh), Material { texture, ..Default::default() }, Transform { translate: Vec3::new(position.x, position.y, position.z), scale: Vec3::new(1.18, 1.18, 1.18), ..Default::default() }, body_handle, Stats{ is_player, ..Default::default() }, Pipeline::default(), ))); } pub fn exile( world: Const<World>, to_exile: Const<ToExile>, mut bodies: Mut<RigidBodySet>, mut colliders: Mut<ColliderSet>, mut joints: Mut<JointSet>, ) { // Query drone entities let query = world.query::<( &Entity, &mut RigidBodyHandle, &mut Stats )>(); for (entity, rigid_body, _) in query { for i in 0..to_exile.entity_list.len() { if entity == &to_exile.entity_list[i] { bodies.remove(*rigid_body, &mut colliders, &mut joints); break; } } } }
extern crate lab_common; extern crate rand; use std::process::exit; use rand::Rng; use lab_common::get_user_input; const MAX_NUMBER: usize = 1000; const GUESSES: usize = 10; fn main() { let answer: usize = rand::thread_rng().gen_range(0, MAX_NUMBER); println!("Guess a number from 0 to {}.", MAX_NUMBER); for i in 0..GUESSES { let guess: usize = get_user_input(Some("Guess: ")); match guess { guess if guess == answer => { println!("You win! It took you {} guesses.", i+1); exit(0); }, guess if guess < answer => println!("Higher"), guess if guess > answer => println!("Lower"), _ => unreachable!(), } } println!("You lose! The correct answer was {}.", answer); }
/*! Command-line arguments and command processing */ use gear::system::{Path, PathBuf}; use std::str::FromStr; use structopt::StructOpt; /// Default rules files const RULES_FILES: &str = "Gearfile, Gearfile.js, Gear.js"; /// Default config files const CONFIG_FILES: &str = "gear.json, gear.yaml, gear.toml"; /// Default config file const CONFIG_FILE: &str = "gear.toml"; #[cfg(unix)] const PATHS_DELIMITER: &str = ":"; #[cfg(windows)] const PATHS_DELIMITER: &str = ";"; /// Flexible build tool #[derive(StructOpt, Debug)] pub struct Args { /// Rules file #[structopt( short = "f", long = "file", env = "GEAR_FILE", default_value = RULES_FILES )] pub file: PathBuf, /// Config file #[structopt( short = "i", long = "config", env = "GEAR_CONFIG", default_value = CONFIG_FILES )] pub config: PathBuf, /// ES6 modules paths #[structopt( short = "I", long = "path", alias = "include-dir", env = "GEAR_PATH", value_delimiter = PATHS_DELIMITER, require_delimiter = true )] pub paths: Vec<PathBuf>, /// Base source directory #[structopt( short = "C", long = "base", alias = "directory", env = "GEAR_BASE", default_value = "" )] pub base: PathBuf, /// Destination directory #[structopt( short = "O", long = "dest", env = "GEAR_DEST", default_value = "target" )] pub dest: PathBuf, /// Logging filter /// /// Set log level or filter in form [<topic>=]<level> where <level> is one of trace, debug, info, warn or error. /// You can set an optional <topic> prefix to filter logs by crate. #[structopt( short = "l", long = "log", env = "GEAR_LOG", default_value = "info", require_delimiter = true )] pub log: Vec<String>, /// Generate completions #[structopt(name = "shell", long = "completions", possible_values = &structopt::clap::Shell::variants())] pub completions: Option<structopt::clap::Shell>, /// Number of jobs nurs simultaneously #[structopt(name = "jobs", short = "j", long = "jobs")] pub jobs: Option<usize>, /// Print database /// /// Prints known goals and variables. /// You can use pattern to filter printed data. #[structopt( name = "format", short = "p", long = "print-db", alias = "print-data-base", possible_values = PRINT_VALUES, )] pub print_db: Option<Option<Print>>, /// Do not invoke rules /// /// Check consistency only #[structopt(short = "n", long = "dry-run")] pub dry_run: bool, /// Watch mode /// /// In this mode goals will be updated when updating dependencies. #[cfg(feature = "watch")] #[structopt(short = "w", long = "watch")] pub watch: bool, /// WebUI URL /// /// Start HTTP API and Web-based UI under this URL. /// Both TCP and Unix Domain sockets supported. #[cfg(feature = "webui")] #[structopt(short = "b", long = "webui")] pub webui: Option<tide::http::Url>, /// Targets and variables /// /// You can pass goals to build via command line as `goal1 goal2 ...`. /// You can set variables via `Gear.{toml,yaml,json}` file or via command line as `name1=value1 name2=value2 ...`. Variables passed via command line overrides variables passed via config. /// /// Use `-p` flag to print available goals and variables. #[structopt()] pub input: Vec<Input>, } impl Args { pub fn get_base(&self) -> String { self.base.display().to_string() } pub fn get_dest(&self) -> String { self.dest.display().to_string() } pub async fn find_file(&self) -> Option<String> { self.file_select(&self.base, &self.file, RULES_FILES).await } pub async fn find_config(&self) -> Option<String> { self.file_select(&Path::new(""), &self.config, CONFIG_FILES) .await } pub fn default_config(&self) -> String { Path::new(CONFIG_FILE).to_str().map(String::from).unwrap() } pub fn gen_completions(&self) { if let Some(shell) = self.completions { Self::clap().gen_completions_to(env!("CARGO_PKG_NAME"), shell, &mut std::io::stdout()); } } pub fn get_jobs(&self) -> usize { self.jobs.unwrap_or_else(|| num_cpus::get()) } pub fn get_print(&self) -> Option<Print> { self.print_db.map(|print| print.unwrap_or_default()) } pub fn get_log(&self) -> String { self.log.join(",") } pub fn get_paths<'i>(&'i self) -> impl Iterator<Item = String> + 'i { self.paths.iter().map(|path| path.display().to_string()) } pub fn get_vars<'i>(&'i self) -> impl Iterator<Item = (String, String)> + 'i { self.input.iter().filter_map(|item| item.to_pair()) } pub fn get_goals<'i>(&'i self) -> impl Iterator<Item = String> + 'i { self.input.iter().filter_map(|item| item.to_name()) } async fn file_select(&self, base: &Path, path: &Path, candidates: &str) -> Option<String> { if path != Path::new(candidates) { return path.to_str().map(String::from); } for candidate in candidates.split(", ") { let path = base.join(candidate); if path.is_file().await { return path.to_str().map(String::from); } } None } } #[derive(Clone, Copy, Debug)] pub enum Print { Goals, Graph, } const PRINT_VALUES: &[&str] = &["plain", "dot"]; impl FromStr for Print { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(match s { "graph" | "graphviz" | "dot" => Self::Graph, _ => Self::Goals, }) } } impl Default for Print { fn default() -> Self { Self::Goals } } #[derive(Clone, Debug)] pub enum Input { Pair(String, String), Name(String), } impl FromStr for Input { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(if let Some(p) = s.find('=') { let key = (&s[0..p]).into(); let val = (&s[p + 1..]).into(); Self::Pair(key, val) } else { Self::Name(s.into()) }) } } impl Input { pub fn to_name(&self) -> Option<String> { if let Self::Name(name) = self { Some(name.clone()) } else { None } } pub fn to_pair(&self) -> Option<(String, String)> { if let Self::Pair(key, val) = self { Some((key.clone(), val.clone())) } else { None } } }
#[doc = "Register `CRCCR` reader"] pub type R = crate::R<CRCCR_SPEC>; #[doc = "Register `CRCCR` writer"] pub type W = crate::W<CRCCR_SPEC>; #[doc = "Field `CRC_SECT` reader - Bank 1 CRC sector number"] pub type CRC_SECT_R = crate::FieldReader; #[doc = "Field `CRC_SECT` writer - Bank 1 CRC sector number"] pub type CRC_SECT_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 3, O>; #[doc = "Field `ALL_BANK` reader - Bank 1 CRC select bit"] pub type ALL_BANK_R = crate::BitReader; #[doc = "Field `ALL_BANK` writer - Bank 1 CRC select bit"] pub type ALL_BANK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRC_BY_SECT` reader - Bank 1 CRC sector mode select bit"] pub type CRC_BY_SECT_R = crate::BitReader; #[doc = "Field `CRC_BY_SECT` writer - Bank 1 CRC sector mode select bit"] pub type CRC_BY_SECT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ADD_SECT` reader - Bank 1 CRC sector select bit"] pub type ADD_SECT_R = crate::BitReader; #[doc = "Field `ADD_SECT` writer - Bank 1 CRC sector select bit"] pub type ADD_SECT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CLEAN_SECT` reader - Bank 1 CRC sector list clear bit"] pub type CLEAN_SECT_R = crate::BitReader; #[doc = "Field `CLEAN_SECT` writer - Bank 1 CRC sector list clear bit"] pub type CLEAN_SECT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `START_CRC` reader - Bank 1 CRC start bit"] pub type START_CRC_R = crate::BitReader; #[doc = "Field `START_CRC` writer - Bank 1 CRC start bit"] pub type START_CRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CLEAN_CRC` reader - Bank 1 CRC clear bit"] pub type CLEAN_CRC_R = crate::BitReader; #[doc = "Field `CLEAN_CRC` writer - Bank 1 CRC clear bit"] pub type CLEAN_CRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CRC_BURST` reader - Bank 1 CRC burst size"] pub type CRC_BURST_R = crate::FieldReader; #[doc = "Field `CRC_BURST` writer - Bank 1 CRC burst size"] pub type CRC_BURST_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:2 - Bank 1 CRC sector number"] #[inline(always)] pub fn crc_sect(&self) -> CRC_SECT_R { CRC_SECT_R::new((self.bits & 7) as u8) } #[doc = "Bit 7 - Bank 1 CRC select bit"] #[inline(always)] pub fn all_bank(&self) -> ALL_BANK_R { ALL_BANK_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Bank 1 CRC sector mode select bit"] #[inline(always)] pub fn crc_by_sect(&self) -> CRC_BY_SECT_R { CRC_BY_SECT_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Bank 1 CRC sector select bit"] #[inline(always)] pub fn add_sect(&self) -> ADD_SECT_R { ADD_SECT_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Bank 1 CRC sector list clear bit"] #[inline(always)] pub fn clean_sect(&self) -> CLEAN_SECT_R { CLEAN_SECT_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 16 - Bank 1 CRC start bit"] #[inline(always)] pub fn start_crc(&self) -> START_CRC_R { START_CRC_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Bank 1 CRC clear bit"] #[inline(always)] pub fn clean_crc(&self) -> CLEAN_CRC_R { CLEAN_CRC_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bits 20:21 - Bank 1 CRC burst size"] #[inline(always)] pub fn crc_burst(&self) -> CRC_BURST_R { CRC_BURST_R::new(((self.bits >> 20) & 3) as u8) } } impl W { #[doc = "Bits 0:2 - Bank 1 CRC sector number"] #[inline(always)] #[must_use] pub fn crc_sect(&mut self) -> CRC_SECT_W<CRCCR_SPEC, 0> { CRC_SECT_W::new(self) } #[doc = "Bit 7 - Bank 1 CRC select bit"] #[inline(always)] #[must_use] pub fn all_bank(&mut self) -> ALL_BANK_W<CRCCR_SPEC, 7> { ALL_BANK_W::new(self) } #[doc = "Bit 8 - Bank 1 CRC sector mode select bit"] #[inline(always)] #[must_use] pub fn crc_by_sect(&mut self) -> CRC_BY_SECT_W<CRCCR_SPEC, 8> { CRC_BY_SECT_W::new(self) } #[doc = "Bit 9 - Bank 1 CRC sector select bit"] #[inline(always)] #[must_use] pub fn add_sect(&mut self) -> ADD_SECT_W<CRCCR_SPEC, 9> { ADD_SECT_W::new(self) } #[doc = "Bit 10 - Bank 1 CRC sector list clear bit"] #[inline(always)] #[must_use] pub fn clean_sect(&mut self) -> CLEAN_SECT_W<CRCCR_SPEC, 10> { CLEAN_SECT_W::new(self) } #[doc = "Bit 16 - Bank 1 CRC start bit"] #[inline(always)] #[must_use] pub fn start_crc(&mut self) -> START_CRC_W<CRCCR_SPEC, 16> { START_CRC_W::new(self) } #[doc = "Bit 17 - Bank 1 CRC clear bit"] #[inline(always)] #[must_use] pub fn clean_crc(&mut self) -> CLEAN_CRC_W<CRCCR_SPEC, 17> { CLEAN_CRC_W::new(self) } #[doc = "Bits 20:21 - Bank 1 CRC burst size"] #[inline(always)] #[must_use] pub fn crc_burst(&mut self) -> CRC_BURST_W<CRCCR_SPEC, 20> { CRC_BURST_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "FLASH CRC control register for bank 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`crccr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`crccr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CRCCR_SPEC; impl crate::RegisterSpec for CRCCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`crccr::R`](R) reader structure"] impl crate::Readable for CRCCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`crccr::W`](W) writer structure"] impl crate::Writable for CRCCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CRCCR to value 0"] impl crate::Resettable for CRCCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use iced::alignment::{Horizontal, Vertical}; use iced::widget::scrollable::Direction; use iced::widget::tooltip::Position; use iced::widget::{button, vertical_space}; use iced::widget::{lazy, Column, Container, Row, Scrollable, Text, Tooltip}; use iced::Length::FillPortion; use iced::{Alignment, Font, Length, Renderer}; use crate::countries::country_utils::get_flag_tooltip; use crate::countries::flags_pictures::FLAGS_WIDTH_BIG; use crate::gui::components::header::get_button_settings; use crate::gui::components::tab::get_pages_tabs; use crate::gui::components::types::my_modal::MyModal; use crate::gui::pages::types::settings_page::SettingsPage; use crate::gui::styles::container::ContainerType; use crate::gui::styles::scrollbar::ScrollbarType; use crate::gui::styles::style_constants::{get_font, get_font_headers, FONT_SIZE_FOOTER}; use crate::gui::styles::text::TextType; use crate::gui::types::message::Message; use crate::notifications::types::logged_notification::{ BytesThresholdExceeded, FavoriteTransmitted, LoggedNotification, PacketsThresholdExceeded, }; use crate::translations::translations::{ bytes_exceeded_translation, bytes_exceeded_value_translation, clear_all_translation, favorite_transmitted_translation, incoming_translation, no_notifications_received_translation, no_notifications_set_translation, only_last_30_translation, outgoing_translation, packets_exceeded_translation, packets_exceeded_value_translation, per_second_translation, threshold_translation, }; use crate::utils::formatted_strings::get_formatted_bytes_string_with_b; use crate::utils::types::icon::Icon; use crate::{Language, RunningPage, Sniffer, StyleType}; /// Computes the body of gui notifications page pub fn notifications_page(sniffer: &Sniffer) -> Container<Message, Renderer<StyleType>> { let notifications = sniffer.notifications; let font = get_font(sniffer.style); let font_headers = get_font_headers(sniffer.style); let mut tab_and_body = Column::new() .align_items(Alignment::Center) .height(Length::Fill); let tabs = get_pages_tabs( RunningPage::Notifications, font, font_headers, sniffer.language, sniffer.unread_notifications, ); tab_and_body = tab_and_body .push(tabs) .push(vertical_space(Length::Fixed(15.0))); if notifications.packets_notification.threshold.is_none() && notifications.bytes_notification.threshold.is_none() && !notifications.favorite_notification.notify_on_favorite && sniffer.runtime_data.logged_notifications.is_empty() { let body = body_no_notifications_set(font, sniffer.language); tab_and_body = tab_and_body.push(body); } else if sniffer.runtime_data.logged_notifications.is_empty() { let body = body_no_notifications_received(font, sniffer.language, &sniffer.waiting); tab_and_body = tab_and_body.push(body); } else { let logged_notifications = lazy( ( sniffer.runtime_data.tot_emitted_notifications, sniffer.runtime_data.logged_notifications.len(), sniffer.language, sniffer.style, ), move |_| lazy_logged_notifications(sniffer), ); let body_row = Row::new() .width(Length::Fill) .push( Container::new(if sniffer.runtime_data.logged_notifications.len() < 30 { Text::new("") } else { Text::new(only_last_30_translation(sniffer.language)).font(font) }) .padding(10) .width(Length::FillPortion(1)) .height(Length::Fill) .align_x(Horizontal::Center) .align_y(Vertical::Center), ) .push( Scrollable::new(logged_notifications) .direction(Direction::Vertical(ScrollbarType::properties())), ) .push( Container::new(get_button_clear_all(font, sniffer.language)) .width(Length::FillPortion(1)) .height(Length::Fill) .align_x(Horizontal::Center) .align_y(Vertical::Center), ); tab_and_body = tab_and_body.push(body_row); } Container::new(Column::new().push(tab_and_body)).height(Length::Fill) } fn body_no_notifications_set( font: Font, language: Language, ) -> Column<'static, Message, Renderer<StyleType>> { Column::new() .padding(5) .spacing(5) .align_items(Alignment::Center) .width(Length::Fill) .push(vertical_space(FillPortion(1))) .push( no_notifications_set_translation(language) .horizontal_alignment(Horizontal::Center) .font(font), ) .push(get_button_settings( font, language, SettingsPage::Notifications, )) .push(vertical_space(FillPortion(2))) } fn body_no_notifications_received( font: Font, language: Language, waiting: &str, ) -> Column<'static, Message, Renderer<StyleType>> { Column::new() .padding(5) .spacing(5) .align_items(Alignment::Center) .width(Length::Fill) .push(vertical_space(FillPortion(1))) .push( no_notifications_received_translation(language) .horizontal_alignment(Horizontal::Center) .font(font), ) .push(Text::new(waiting.to_owned()).font(font).size(50)) .push(vertical_space(FillPortion(2))) } fn packets_notification_log( logged_notification: PacketsThresholdExceeded, language: Language, font: Font, ) -> Container<'static, Message, Renderer<StyleType>> { let threshold_str = format!( "{}: {} {}", threshold_translation(language), logged_notification.threshold, per_second_translation(language) ); let mut incoming_str = " - ".to_string(); incoming_str.push_str(incoming_translation(language)); incoming_str.push_str(": "); incoming_str.push_str(&logged_notification.incoming.to_string()); let mut outgoing_str = " - ".to_string(); outgoing_str.push_str(outgoing_translation(language)); outgoing_str.push_str(": "); outgoing_str.push_str(&logged_notification.outgoing.to_string()); let content = Row::new() .align_items(Alignment::Center) .height(Length::Fill) .spacing(30) .push( Tooltip::new( Icon::PacketsThreshold.to_text().size(80), packets_exceeded_translation(language), Position::FollowCursor, ) .font(font) .style(ContainerType::Tooltip), ) .push( Column::new() .spacing(7) .width(Length::Fixed(250.0)) .push( Row::new() .spacing(5) .push(Icon::Clock.to_text()) .push(Text::new(logged_notification.timestamp).font(font)), ) .push( Text::new(packets_exceeded_translation(language)) .style(TextType::Title) .font(font), ) .push( Text::new(threshold_str) .style(TextType::Subtitle) .size(FONT_SIZE_FOOTER) .font(font), ), ) .push( Column::new() .spacing(7) .push( Text::new(packets_exceeded_value_translation( language, logged_notification.incoming + logged_notification.outgoing, )) .font(font), ) .push(Text::new(incoming_str).font(font)) .push(Text::new(outgoing_str).font(font)), ); Container::new(content) .height(Length::Fixed(120.0)) .width(Length::Fixed(800.0)) .padding(10) .style(ContainerType::BorderedRound) } fn bytes_notification_log( logged_notification: BytesThresholdExceeded, language: Language, font: Font, ) -> Container<'static, Message, Renderer<StyleType>> { let mut threshold_str = threshold_translation(language); threshold_str.push_str(": "); threshold_str.push_str(&get_formatted_bytes_string_with_b( (logged_notification.threshold).into(), )); threshold_str.push_str(&format!(" {}", per_second_translation(language))); let mut incoming_str = " - ".to_string(); incoming_str.push_str(incoming_translation(language)); incoming_str.push_str(": "); incoming_str.push_str(&get_formatted_bytes_string_with_b(u128::from( logged_notification.incoming, ))); let mut outgoing_str = " - ".to_string(); outgoing_str.push_str(outgoing_translation(language)); outgoing_str.push_str(": "); outgoing_str.push_str(&get_formatted_bytes_string_with_b(u128::from( logged_notification.outgoing, ))); let content = Row::new() .spacing(30) .align_items(Alignment::Center) .height(Length::Fill) .push( Tooltip::new( Icon::BytesThreshold.to_text().size(80), bytes_exceeded_translation(language), Position::FollowCursor, ) .font(font) .style(ContainerType::Tooltip), ) .push( Column::new() .spacing(7) .width(Length::Fixed(250.0)) .push( Row::new() .spacing(5) .push(Icon::Clock.to_text()) .push(Text::new(logged_notification.timestamp).font(font)), ) .push( Text::new(bytes_exceeded_translation(language)) .style(TextType::Title) .font(font), ) .push( Text::new(threshold_str) .size(FONT_SIZE_FOOTER) .style(TextType::Subtitle) .font(font), ), ) .push( Column::new() .spacing(7) .push( Text::new(bytes_exceeded_value_translation( language, &get_formatted_bytes_string_with_b(u128::from( logged_notification.incoming + logged_notification.outgoing, )), )) .font(font), ) .push(Text::new(incoming_str).font(font)) .push(Text::new(outgoing_str).font(font)), ); Container::new(content) .height(Length::Fixed(120.0)) .width(Length::Fixed(800.0)) .padding(10) .style(ContainerType::BorderedRound) } fn favorite_notification_log( logged_notification: FavoriteTransmitted, language: Language, font: Font, ) -> Container<'static, Message, Renderer<StyleType>> { let domain = logged_notification.host.domain; let country = logged_notification.host.country; let asn = logged_notification.host.asn; let mut domain_asn_str = domain; if !asn.name.is_empty() { domain_asn_str.push_str(&format!(" - {}", asn.name)); } let row_flag_details = Row::new() .align_items(Alignment::Center) .spacing(5) .push(get_flag_tooltip( country, FLAGS_WIDTH_BIG, logged_notification.data_info_host.is_local, logged_notification.data_info_host.traffic_type, language, font, )) .push(Text::new(domain_asn_str).font(font)); let content = Row::new() .spacing(30) .align_items(Alignment::Center) .height(Length::Fill) .push( Tooltip::new( Icon::Star.to_text().size(80), favorite_transmitted_translation(language), Position::FollowCursor, ) .font(font) .style(ContainerType::Tooltip), ) .push( Column::new() .width(Length::Fixed(250.0)) .spacing(7) .push( Row::new() .spacing(5) .push(Icon::Clock.to_text()) .push(Text::new(logged_notification.timestamp).font(font)), ) .push( Text::new(favorite_transmitted_translation(language)) .style(TextType::Title) .font(font), ), ) .push( Column::new() .spacing(7) .width(Length::Fill) .push(row_flag_details), ); Container::new(content) .height(Length::Fixed(120.0)) .width(Length::Fixed(800.0)) .padding(10) .style(ContainerType::BorderedRound) } fn get_button_clear_all( font: Font, language: Language, ) -> Tooltip<'static, Message, Renderer<StyleType>> { let content = button( Icon::Bin .to_text() .size(20) .horizontal_alignment(Horizontal::Center) .vertical_alignment(Vertical::Center), ) .padding(10) .height(Length::Fixed(50.0)) .width(Length::Fixed(75.0)) .on_press(Message::ShowModal(MyModal::ClearAll)); Tooltip::new(content, clear_all_translation(language), Position::Top) .gap(5) .font(font) .style(ContainerType::Tooltip) } fn lazy_logged_notifications(sniffer: &Sniffer) -> Column<'static, Message, Renderer<StyleType>> { let font = get_font(sniffer.style); let mut ret_val = Column::new() .width(Length::Fixed(830.0)) .padding(5) .spacing(10) .align_items(Alignment::Center); for logged_notification in &sniffer.runtime_data.logged_notifications { ret_val = ret_val.push(match logged_notification { LoggedNotification::PacketsThresholdExceeded(packet_threshold_exceeded) => { packets_notification_log(packet_threshold_exceeded.clone(), sniffer.language, font) } LoggedNotification::BytesThresholdExceeded(byte_threshold_exceeded) => { bytes_notification_log(byte_threshold_exceeded.clone(), sniffer.language, font) } LoggedNotification::FavoriteTransmitted(favorite_transmitted) => { favorite_notification_log(favorite_transmitted.clone(), sniffer.language, font) } }); } ret_val }
// TODO: move this to configuration files? // Screen constants pub const SCREEN_WIDTH: f32 = 256.0; pub const SCREEN_HEIGHT: f32 = 256.0; // Some ~physics constants pub const BALL_SPEED_FOR_MINIMUM_COLLISION: f32 = 256.0; pub const BALL_MINIMUM_COLLISION_FACTOR: f32 = 0.3; // Player position constants pub const MAXIMUM_TEAM_SIZE: usize = 5; pub const FORWARD_NUMBER: usize = 0; pub const GOALIE_NUMBER: usize = 1; pub const LEFT_NUMBER: usize = 2; pub const RIGHT_NUMBER: usize = 3; pub const DEFENDER_NUMBER: usize = 4; pub const RESET_PLAYER_POSITIONS: [[f32; 2]; MAXIMUM_TEAM_SIZE] = [ [SCREEN_WIDTH / 2.0, 4.0 * SCREEN_HEIGHT / 9.0], [SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 16.0], [SCREEN_WIDTH / 4.0, SCREEN_HEIGHT / 3.0], [3.0 * SCREEN_WIDTH / 4.0, SCREEN_HEIGHT / 3.0], [SCREEN_WIDTH / 2.0, SCREEN_HEIGHT / 4.0], ];
use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Copy, Serialize, Deserialize, Hash, PartialEq, Eq)] pub struct Evaluation(pub i32);
use std::io; use std::net::SocketAddr; use futures::try_join; use super::copy; use crate::transport::plain::{self, PlainStream, PlainListener}; use crate::transport::{AsyncConnect, AsyncAccept}; async fn bidi_copy<S, C>( res: (PlainStream, SocketAddr), lis: S, conn: C, ) -> io::Result<()> where S: AsyncAccept, C: AsyncConnect, { let (sin, _) = lis.accept(res).await?; let sout = conn.connect().await?; let (ri, wi) = tokio::io::split(sin); let (ro, wo) = tokio::io::split(sout); let _ = try_join!(copy::copy(ri, wo), copy::copy(ro, wi)); Ok(()) } pub async fn proxy<L, C>(lis: L, conn: C) -> io::Result<()> where L: AsyncAccept + 'static, C: AsyncConnect + 'static, { let plain_lis = PlainListener::bind(lis.addr()).unwrap(); loop { if let Ok(res) = plain_lis.accept_plain().await { tokio::spawn(bidi_copy(res, lis.clone(), conn.clone())); } } } // zero copy #[cfg(target_os = "linux")] use super::zero_copy; #[cfg(target_os = "linux")] async fn bidi_zero_copy( mut sin: PlainStream, conn: plain::Connector, ) -> io::Result<()> { let mut sout = conn.connect().await?; let (mut ri, mut wi) = sin.split(); let (mut ro, mut wo) = sout.split(); let _ = try_join!( zero_copy::copy(&mut ri, &mut wo), zero_copy::copy(&mut ro, &mut wi) ); Ok(()) } #[cfg(target_os = "linux")] pub async fn splice( lis: plain::Acceptor, conn: plain::Connector, ) -> io::Result<()> { let plain_lis = PlainListener::bind(lis.addr()).unwrap(); loop { if let Ok((sin, _)) = plain_lis.accept_plain().await { tokio::spawn(bidi_zero_copy(sin, conn.clone())); } } }
use std::collections::{HashMap, HashSet}; const PART2: bool = true; const DIM_COUNT: usize = if PART2 { 4 } else { 3 }; const CYCLES: usize = 6; type CoordType = i8; fn main() { let input = String::from_utf8(std::fs::read("input/day17").unwrap()).unwrap(); let mut active_cubes: HashSet<[CoordType; DIM_COUNT]> = input .split_terminator('\n') .enumerate() .flat_map(|(i, r)| r.chars().enumerate().map(move |(j, c)| ([i, j], c))) .filter_map(|(coords, c)| { let mut result = [0; DIM_COUNT]; result .iter_mut() .zip(coords.iter()) .for_each(|(r, &c)| *r = c as _); Some(result).filter(|_| c == '#') }) .collect(); const ADJACENT_SPAN: CoordType = 3; let adjacent_offsets: Vec<_> = (0..(ADJACENT_SPAN.pow(DIM_COUNT as _))) .filter(|&i| i != ADJACENT_SPAN.pow(DIM_COUNT as _) / 2) .map(|i| { let mut result = [0; DIM_COUNT]; result.iter_mut().enumerate().for_each(|(dim, coord)| { *coord = i % ADJACENT_SPAN.pow((dim + 1) as _) / ADJACENT_SPAN.pow(dim as _) - 1 }); result }) .collect(); let add = |a: &[CoordType; DIM_COUNT], b: &[CoordType; DIM_COUNT]| -> [CoordType; DIM_COUNT] { let mut c = [0; DIM_COUNT]; c.iter_mut() .zip(a.iter().zip(b.iter())) .for_each(|(c, (&a, &b))| *c = a + b); c }; let mut deactivate = Vec::new(); let mut inactive_neighbors = HashMap::<_, usize>::new(); for _ in 0..CYCLES { for cube in active_cubes.iter() { let active_neighbors_count = adjacent_offsets .iter() .map(|o| add(cube, o)) .filter(|neighbor| active_cubes.contains(neighbor)) .take(4) .count(); if active_neighbors_count != 2 && active_neighbors_count != 3 { deactivate.push(cube.clone()); } adjacent_offsets .iter() .map(|o| add(cube, o)) .filter(|neighbor| !active_cubes.contains(neighbor)) .for_each(|inactive_neighbor| { *inactive_neighbors.entry(inactive_neighbor).or_insert(0) += 1 }); } deactivate.drain(..).for_each(|deactivate| { active_cubes.remove(&deactivate); }); inactive_neighbors .drain() .filter_map(|n| Some(n.0).filter(|_| n.1 == 3)) .for_each(|activate| { active_cubes.insert(activate); }); } let answer = active_cubes.len(); println!("{:?}", answer); }
//! Minimal `cortex-m-rt` based program #![deny(unsafe_code)] #![deny(warnings)] #![no_main] #![no_std] extern crate cortex_m_rt as rt; extern crate panic_halt; use rt::entry; // the program entry point #[entry] fn main() -> ! { loop {} }
// Copyright 2019 Fabian Freyer <fabian.freyer@physik.tu-berlin.de> // Copyright 2018 David O'Rourke <david.orourke@gmail.com> // // 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. // Note: // The rctl_api_wrapper function, the usage() function as well as the state // check are based on code from phyber/jail_exporter: // https://github.com/phyber/jail_exporter/blob/6498d628143399fc365fad4217ad85db12348e65/src/rctl/mod.rs //! Resource limits and accounting with `RCTL` and `RACCT` //! //! Large parts of this documentation are adapted from the [`rctl(8)`] manpage. //! //! [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable pub use nix::sys::signal::Signal; use number_prefix::{NumberPrefix, Prefix}; use std::collections::HashMap; use std::ffi::{CStr, CString, NulError}; use std::fmt; use std::io; use std::num; use std::str; use sysctl::Sysctl; use thiserror::Error; // Set to the same value as found in rctl.c in FreeBSD 11.1 const RCTL_DEFAULT_BUFSIZE: usize = 128 * 1024; #[derive(Debug, Error, PartialEq, Clone)] pub enum ParseError { #[error("Unknown subject type: {0}")] UnknownSubjectType(String), #[error("No such user: {0}")] UnknownUser(String), #[error("Unknown resource: {0}")] UnknownResource(String), #[error("Unknown action: {0}")] UnknownAction(String), #[error("Bogus data at end of limit: {0}")] LimitBogusData(String), #[error("Invalid limit literal: {0}")] InvalidLimitLiteral(String), #[error("Invalid numeric value: {0}")] InvalidNumeral(num::ParseIntError), #[error("No subject specified")] NoSubjectGiven, #[error("Bogus data at end of subject: {0}")] SubjectBogusData(String), #[error("Invalid Rule syntax: '{0}'")] InvalidRuleSyntax(String), } #[derive(Debug, Error)] pub enum Error { #[error("Parse Error: {0}")] ParseError(ParseError), #[error("OS Error: {0}")] OsError(io::Error), #[error("An interior Nul byte was found while attempting to construct a CString: {0}")] CStringError(NulError), #[error("The statistics returned by the kernel were invalid.")] InvalidStatistics, #[error("Invalid RCTL / RACCT kernel state: {0}")] InvalidKernelState(State), } /// Helper module containing enums representing [Subjects](Subject) mod subject { use super::ParseError; use std::fmt; use users::{get_user_by_name, get_user_by_uid}; /// Represents a user subject #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct User(pub users::uid_t); impl User { pub fn from_uid(uid: libc::uid_t) -> User { User(uid as users::uid_t) } pub fn from_name(name: &str) -> Result<User, ParseError> { let uid = get_user_by_name(name) .ok_or_else(|| ParseError::UnknownUser(name.into()))? .uid(); Ok(User::from_uid(uid)) } } impl fmt::Display for User { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match get_user_by_uid(self.0) { Some(user) => write!(f, "user:{}", user.name().to_str().ok_or(fmt::Error)?), None => write!(f, "user:{}", self.0), } } } impl<'a> From<&'a User> for String { fn from(user: &'a User) -> String { format!("user:{}", user.0) } } /// Represents a process subject #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct Process(pub libc::pid_t); impl fmt::Display for Process { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "process:{}", self.0) } } impl<'a> From<&'a Process> for String { fn from(proc: &'a Process) -> String { format!("{}", proc) } } /// Represents a jail subject #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct Jail(pub String); impl fmt::Display for Jail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "jail:{}", self.0) } } impl<'a> From<&'a Jail> for String { fn from(jail: &'a Jail) -> String { format!("{}", jail) } } /// Represents a login class subject #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct LoginClass(pub String); impl fmt::Display for LoginClass { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "loginclass:{}", self.0) } } impl<'a> From<&'a LoginClass> for String { fn from(login_class: &'a LoginClass) -> String { format!("{}", login_class) } } #[cfg(test)] mod tests { use super::*; #[test] fn display_jail_name() { assert_eq!( format!("{}", Jail("testjail_rctl_name".into())), "jail:testjail_rctl_name".to_string() ); } #[test] fn display_user() { assert_eq!( format!("{}", User::from_name("nobody").expect("no nobody user")), "user:nobody".to_string() ); assert_eq!(format!("{}", User::from_uid(4242)), "user:4242".to_string()); } #[test] fn display_loginclass() { assert_eq!( format!("{}", LoginClass("test".into())), "loginclass:test".to_string() ); } } } /// A struct representing an RCTL subject. /// /// From [`rctl(8)`]: /// > Subject defines the kind of entity the rule applies to. It can be either /// > process, user, login class, or jail. /// > /// > Subject ID identifies the subject. It can be user name, numerical user ID /// > login class name, or jail name. /// /// [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum Subject { Process(subject::Process), Jail(subject::Jail), User(subject::User), LoginClass(subject::LoginClass), } impl Subject { pub fn process_id(pid: libc::pid_t) -> Self { Subject::Process(subject::Process(pid)) } pub fn user_name(name: &str) -> Result<Self, ParseError> { Ok(Subject::User(subject::User::from_name(name)?)) } pub fn user_id(uid: libc::uid_t) -> Self { Subject::User(subject::User::from_uid(uid)) } pub fn login_class<S: Into<String>>(name: S) -> Self { Subject::LoginClass(subject::LoginClass(name.into())) } pub fn jail_name<S: Into<String>>(name: S) -> Self { Subject::Jail(subject::Jail(name.into())) } /// Get the resource usage for a specific [Subject]. /// /// # Example /// /// ``` /// # extern crate rctl; /// # use rctl; /// # if !rctl::State::check().is_enabled() { /// # return; /// # } /// extern crate libc; /// /// let uid = unsafe { libc::getuid() }; /// let subject = rctl::Subject::user_id(uid); /// /// let usage = subject.usage() /// .expect("Could not get RCTL usage"); /// /// println!("{:#?}", usage); /// ``` pub fn usage(&self) -> Result<HashMap<Resource, usize>, Error> { extern "C" { fn rctl_get_racct( inbufp: *const libc::c_char, inbuflen: libc::size_t, outbufp: *mut libc::c_char, outbuflen: libc::size_t, ) -> libc::c_int; } let filter = Filter::new().subject(self); let rusage = rctl_api_wrapper(rctl_get_racct, &filter)?; let mut map: HashMap<Resource, usize> = HashMap::new(); for statistic in rusage.split(',') { let mut kv = statistic.split('='); let resource = kv .next() .ok_or(Error::InvalidStatistics)? .parse::<Resource>() .map_err(Error::ParseError)?; let value = kv .next() .ok_or(Error::InvalidStatistics)? .parse::<usize>() .map_err(ParseError::InvalidNumeral) .map_err(Error::ParseError)?; map.insert(resource, value); } Ok(map) } /// Get an IntoIterator over the rules that apply to this subject. pub fn limits(&self) -> Result<RuleParsingIntoIter<String>, Error> { extern "C" { fn rctl_get_limits( inbufp: *const libc::c_char, inbuflen: libc::size_t, outbufp: *mut libc::c_char, outbuflen: libc::size_t, ) -> libc::c_int; } let outbuf = rctl_api_wrapper(rctl_get_limits, self)?; Ok(RuleParsingIntoIter { inner: outbuf }) } } impl fmt::Display for Subject { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Subject::Process(p) => write!(f, "{}", p), Subject::User(u) => write!(f, "{}", u), Subject::Jail(j) => write!(f, "{}", j), Subject::LoginClass(c) => write!(f, "{}", c), } } } impl<'a> From<&'a Subject> for String { fn from(subject: &'a Subject) -> String { match subject { Subject::Process(ref p) => p.into(), Subject::User(ref u) => u.into(), Subject::Jail(ref j) => j.into(), Subject::LoginClass(ref c) => c.into(), } } } fn parse_process(s: &str) -> Result<Subject, ParseError> { s.parse::<libc::pid_t>() .map_err(ParseError::InvalidNumeral) .map(Subject::process_id) } fn parse_user(s: &str) -> Result<Subject, ParseError> { match s.parse::<libc::uid_t>() { Ok(uid) => Ok(Subject::user_id(uid)), Err(_) => Ok(Subject::user_name(s)?), } } fn parse_jail(s: &str) -> Subject { Subject::jail_name(s) } fn parse_login_class(s: &str) -> Subject { Subject::login_class(s) } impl str::FromStr for Subject { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let parts: Vec<_> = s.split(':').collect(); let subject_type = parts[0].parse::<SubjectType>()?; match parts.len() { 1 => Err(ParseError::NoSubjectGiven), 2 => match subject_type { SubjectType::Process => parse_process(parts[1]), SubjectType::User => parse_user(parts[1]), SubjectType::LoginClass => Ok(parse_login_class(parts[1])), SubjectType::Jail => Ok(parse_jail(parts[1])), }, _ => Err(ParseError::SubjectBogusData(format!( ":{}", parts[2..].join(":") ))), } } } /// The type of a [Subject]. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum SubjectType { Process, Jail, User, LoginClass, } impl str::FromStr for SubjectType { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "process" => Ok(SubjectType::Process), "jail" => Ok(SubjectType::Jail), "user" => Ok(SubjectType::User), "loginclass" => Ok(SubjectType::LoginClass), _ => Err(ParseError::UnknownSubjectType(s.into())), } } } impl<'a> From<&'a Subject> for SubjectType { fn from(subject: &'a Subject) -> Self { match subject { Subject::Process(_) => SubjectType::Process, Subject::Jail(_) => SubjectType::Jail, Subject::User(_) => SubjectType::User, Subject::LoginClass(_) => SubjectType::LoginClass, } } } impl SubjectType { pub fn as_str(&self) -> &'static str { match self { SubjectType::Process => "process", SubjectType::Jail => "jail", SubjectType::User => "user", SubjectType::LoginClass => "loginclass", } } } impl<'a> From<&'a SubjectType> for &'static str { fn from(subject_type: &'a SubjectType) -> &'static str { subject_type.as_str() } } impl<'a> From<&'a SubjectType> for String { fn from(subject_type: &'a SubjectType) -> String { subject_type.as_str().into() } } impl fmt::Display for SubjectType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let r: &'static str = self.into(); write!(f, "{}", r) } } /// An Enum representing a resource type #[derive(Clone, Copy, Debug, PartialEq, Hash, Eq)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum Resource { /// CPU time, in seconds CpuTime, /// datasize, in bytes DataSize, /// stack size, in bytes /// /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// > The maximum size of a process stack. This alone is not sufficient to /// > limit the amount of memory a program may use, so it should be used in /// > conjunction with other limits. /// /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits StackSize, /// coredump size, in bytes /// /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// > The limit on the size of a core file generated by a program is /// > subordinate to other limits on disk usage, such as filesize or disk /// > quotas. This limit is often used as a less severe method of /// > controlling disk space consumption. Since users do not generate core /// > files and often do not delete them, this setting may save them from /// > running out of disk space should a large program crash. /// /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits CoreDumpSize, /// resident setsize, in bytes MemoryUse, /// locked memory, in bytes /// /// from the [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// > The maximum amount of memory a process may request to be locked into /// > main memory using [`mlock(2)`]. Some system-critical programs, such as /// > [`amd(8)`], lock into main memory so that if the system begins to /// > swap, they do not contribute to disk thrashing. /// /// [`mlock(2)`]: /// https://www.freebsd.org/cgi/man.cgi?query=mlock&sektion=2&manpath=freebsd-release-ports /// [`amd(8)`]: /// https://www.freebsd.org/cgi/man.cgi?query=amd&sektion=8&manpath=freebsd-release-ports /// [FreeBSD Handbook Chapter 13.13 - Resource Limits]: /// https://www.freebsd.org/doc/handbook/security-resourcelimits.html#resource-limits MemoryLocked, /// number of processes MaxProcesses, /// File descriptor table size OpenFiles, /// address space limit, in bytes VMemoryUse, /// number of PTYs PseudoTerminals, /// swapspace that may be reserved or used, in bytes SwapUse, /// number of threads NThreads, /// number of queued SysV messages MsgqQueued, /// SysVmessagequeue size, in bytes MsgqSize, /// number of SysV message queues NMsgq, /// number of SysV semaphores Nsem, /// number of SysV semaphores modified in a single `semop(2)` call NSemop, /// number of SysV shared memorysegments NShm, /// SysVshared memory size, in bytes ShmSize, /// wallclock time, in seconds Wallclock, /// %CPU, in percents of a single CPU core PercentCpu, /// filesystem reads, in bytes per second ReadBps, /// filesystem writes, in bytes per second WriteBps, /// filesystem reads, inoperations per second ReadIops, /// filesystem writes, in operations persecond WriteIops, } impl Resource { /// Return the string representation of the resource /// /// # Examples /// ``` /// use rctl::Resource; /// assert_eq!(Resource::CpuTime.as_str(), "cputime"); /// ``` pub fn as_str(&self) -> &'static str { match self { Resource::CpuTime => "cputime", Resource::DataSize => "datasize", Resource::StackSize => "stacksize", Resource::CoreDumpSize => "coredumpsize", Resource::MemoryUse => "memoryuse", Resource::MemoryLocked => "memorylocked", Resource::MaxProcesses => "maxproc", Resource::OpenFiles => "openfiles", Resource::VMemoryUse => "vmemoryuse", Resource::PseudoTerminals => "pseudoterminals", Resource::SwapUse => "swapuse", Resource::NThreads => "nthr", Resource::MsgqQueued => "msgqqueued", Resource::MsgqSize => "msgqsize", Resource::NMsgq => "nmsgq", Resource::Nsem => "nsem", Resource::NSemop => "nsemop", Resource::NShm => "nshm", Resource::ShmSize => "shmsize", Resource::Wallclock => "wallclock", Resource::PercentCpu => "pcpu", Resource::ReadBps => "readbps", Resource::WriteBps => "writebps", Resource::ReadIops => "readiops", Resource::WriteIops => "writeiops", } } } impl str::FromStr for Resource { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "cputime" => Ok(Resource::CpuTime), "datasize" => Ok(Resource::DataSize), "stacksize" => Ok(Resource::StackSize), "coredumpsize" => Ok(Resource::CoreDumpSize), "memoryuse" => Ok(Resource::MemoryUse), "memorylocked" => Ok(Resource::MemoryLocked), "maxproc" => Ok(Resource::MaxProcesses), "openfiles" => Ok(Resource::OpenFiles), "vmemoryuse" => Ok(Resource::VMemoryUse), "pseudoterminals" => Ok(Resource::PseudoTerminals), "swapuse" => Ok(Resource::SwapUse), "nthr" => Ok(Resource::NThreads), "msgqqueued" => Ok(Resource::MsgqQueued), "msgqsize" => Ok(Resource::MsgqSize), "nmsgq" => Ok(Resource::NMsgq), "nsem" => Ok(Resource::Nsem), "nsemop" => Ok(Resource::NSemop), "nshm" => Ok(Resource::NShm), "shmsize" => Ok(Resource::ShmSize), "wallclock" => Ok(Resource::Wallclock), "pcpu" => Ok(Resource::PercentCpu), "readbps" => Ok(Resource::ReadBps), "writebps" => Ok(Resource::WriteBps), "readiops" => Ok(Resource::ReadIops), "writeiops" => Ok(Resource::WriteIops), _ => Err(ParseError::UnknownResource(s.into())), } } } impl<'a> From<&'a Resource> for &'a str { fn from(resource: &'a Resource) -> &'a str { resource.as_str() } } impl<'a> From<&'a Resource> for String { fn from(resource: &'a Resource) -> String { resource.as_str().to_owned() } } impl fmt::Display for Resource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } } /// Represents the action to be taken when a [Subject] offends against a Rule. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub enum Action { /// Deny the resource allocation /// /// Not supported for the following [Resources]: [`CpuTime`], [`Wallclock`], /// [`ReadBps`], [`WriteBps`], [`ReadIops`], [`WriteIops`] /// /// [`CpuTime`]: Resource::CpuTime /// [`WallClock`]: Resource::Wallclock /// [`ReadBps`]: Resource::ReadBps /// [`WriteBps`]: Resource::WriteBps /// [`ReadIops`]: Resource::ReadIops /// [`WriteIops`]: Resource::WriteIops /// [Resources]: Resource Deny, /// Log a warning to the console Log, /// Send a notification to [`devd(8)`] using `system = "RCTL"`, /// `subsystem = "rule"`, `type = "matched"` /// /// [`devd(8)`]: https://www.freebsd.org/cgi/man.cgi?query=devd&sektion=8&manpath=FreeBSD+11.2-stable DevCtl, /// Send a [signal] to the offending process. /// /// # Example /// ``` /// # extern crate rctl; /// use rctl::Signal; /// use rctl::Action; /// /// let action = Action::Signal(Signal::SIGTERM); /// ``` /// /// [signal]: Signal #[cfg_attr(feature = "serialize", serde(serialize_with = "signal_serialize"))] Signal(Signal), /// Slow down process execution /// /// Only supported for the following [Resources]: /// [`ReadBps`], [`WriteBps`], [`ReadIops`], [`WriteIops`] /// /// [`ReadBps`]: Resource::ReadBps /// [`WriteBps`]: Resource::WriteBps /// [`ReadIops`]: Resource::ReadIops /// [`WriteIops`]: Resource::WriteIops /// [Resources]: Resource Throttle, } impl Action { /// Return the string representation of the Action according to [`rctl(8)`] /// /// # Examples /// ``` /// use rctl::Action; /// assert_eq!(Action::Deny.as_str(), "deny"); /// ``` /// /// Signals are handled by `rctl::Signal`: /// ``` /// # extern crate rctl; /// # use rctl::Action; /// use rctl::Signal; /// assert_eq!(Action::Signal(Signal::SIGKILL).as_str(), "sigkill"); /// ``` /// /// [`rctl(8)`]: https://www.freebsd.org/cgi/man.cgi?query=rctl&sektion=8&manpath=FreeBSD+11.2-stable pub fn as_str(&self) -> &'static str { match self { Action::Deny => "deny", Action::Log => "log", Action::DevCtl => "devctl", Action::Throttle => "throttle", Action::Signal(sig) => match sig { Signal::SIGHUP => "sighup", Signal::SIGINT => "sigint", Signal::SIGQUIT => "sigquit", Signal::SIGILL => "sigill", Signal::SIGTRAP => "sigtrap", Signal::SIGABRT => "sigabrt", Signal::SIGBUS => "sigbus", Signal::SIGFPE => "sigfpe", Signal::SIGKILL => "sigkill", Signal::SIGUSR1 => "sigusr1", Signal::SIGSEGV => "sigsegv", Signal::SIGUSR2 => "sigusr2", Signal::SIGPIPE => "sigpipe", Signal::SIGALRM => "sigalrm", Signal::SIGTERM => "sigterm", Signal::SIGCHLD => "sigchld", Signal::SIGCONT => "sigcont", Signal::SIGSTOP => "sigstop", Signal::SIGTSTP => "sigtstp", Signal::SIGTTIN => "sigttin", Signal::SIGTTOU => "sigttou", Signal::SIGURG => "sigurg", Signal::SIGXCPU => "sigxcpu", Signal::SIGXFSZ => "sigxfsz", Signal::SIGVTALRM => "sigvtalrm", Signal::SIGPROF => "sigprof", Signal::SIGWINCH => "sigwinch", Signal::SIGIO => "sigio", Signal::SIGSYS => "sigsys", Signal::SIGEMT => "sigemt", Signal::SIGINFO => "siginfo", _ => "unknown", }, } } } impl str::FromStr for Action { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "deny" => Ok(Action::Deny), "log" => Ok(Action::Log), "devctl" => Ok(Action::DevCtl), "throttle" => Ok(Action::Throttle), "sighup" => Ok(Action::Signal(Signal::SIGHUP)), "sigint" => Ok(Action::Signal(Signal::SIGINT)), "sigquit" => Ok(Action::Signal(Signal::SIGQUIT)), "sigill" => Ok(Action::Signal(Signal::SIGILL)), "sigtrap" => Ok(Action::Signal(Signal::SIGTRAP)), "sigabrt" => Ok(Action::Signal(Signal::SIGABRT)), "sigbus" => Ok(Action::Signal(Signal::SIGBUS)), "sigfpe" => Ok(Action::Signal(Signal::SIGFPE)), "sigkill" => Ok(Action::Signal(Signal::SIGKILL)), "sigusr1" => Ok(Action::Signal(Signal::SIGUSR1)), "sigsegv" => Ok(Action::Signal(Signal::SIGSEGV)), "sigusr2" => Ok(Action::Signal(Signal::SIGUSR2)), "sigpipe" => Ok(Action::Signal(Signal::SIGPIPE)), "sigalrm" => Ok(Action::Signal(Signal::SIGALRM)), "sigterm" => Ok(Action::Signal(Signal::SIGTERM)), "sigchld" => Ok(Action::Signal(Signal::SIGCHLD)), "sigcont" => Ok(Action::Signal(Signal::SIGCONT)), "sigstop" => Ok(Action::Signal(Signal::SIGSTOP)), "sigtstp" => Ok(Action::Signal(Signal::SIGTSTP)), "sigttin" => Ok(Action::Signal(Signal::SIGTTIN)), "sigttou" => Ok(Action::Signal(Signal::SIGTTOU)), "sigurg" => Ok(Action::Signal(Signal::SIGURG)), "sigxcpu" => Ok(Action::Signal(Signal::SIGXCPU)), "sigxfsz" => Ok(Action::Signal(Signal::SIGXFSZ)), "sigvtalrm" => Ok(Action::Signal(Signal::SIGVTALRM)), "sigprof" => Ok(Action::Signal(Signal::SIGPROF)), "sigwinch" => Ok(Action::Signal(Signal::SIGWINCH)), "sigio" => Ok(Action::Signal(Signal::SIGIO)), "sigsys" => Ok(Action::Signal(Signal::SIGSYS)), "sigemt" => Ok(Action::Signal(Signal::SIGEMT)), "siginfo" => Ok(Action::Signal(Signal::SIGINFO)), _ => Err(ParseError::UnknownAction(s.into())), } } } impl<'a> From<&'a Action> for &'a str { fn from(action: &'a Action) -> &'a str { action.as_str() } } impl<'a> From<&'a Action> for String { fn from(action: &'a Action) -> String { action.as_str().into() } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.as_str()) } } #[cfg(feature = "serialize")] fn signal_serialize<S>(signal: &Signal, s: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { let sig_str = format!("{:?}", signal); s.serialize_str(&sig_str) } /// Defines how much of a [Resource] a process can use beofore the defined /// [Action] triggers. #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct Limit { amount: usize, per: Option<SubjectType>, } impl Limit { /// Construct a limit representing the amount used before an [Action] /// triggers. /// /// The entity the amount gets accounted for defaults to the type of the /// [Subject] of the respective [Rule]. pub fn amount(amount: usize) -> Limit { Limit { amount, per: None } } /// Limit the amount per [SubjectType]. /// /// This defines what entity the amount gets accounted for. /// /// # Examples /// /// For example the following [Rule] means that each process of any user /// belonging to the login class "users" may allocate up to 100 MiB of /// virtual memory: /// ```rust /// # use rctl::{Subject, SubjectType, Resource, Action, Limit, Rule}; /// Rule { /// subject: Subject::login_class("users"), /// resource: Resource::VMemoryUse, /// action: Action::Deny, /// limit: Limit::amount_per(100*1024*1024, SubjectType::Process), /// } /// # ; /// ``` /// /// Setting `per: Some(SubjectType::User)` on the above [Rule] would mean /// that for each user belonging to the login class "users", the sum of /// virtual memory allocated by all the processes of that user will not /// exceed 100 MiB. /// /// Setting `per: Some(SubjectType::LoginClass)` on the above [Rule] would /// mean that the sum of virtual memory allocated by all processes of all /// users belonging to that login class will not exceed 100 MiB. pub fn amount_per(amount: usize, per: SubjectType) -> Limit { Limit { amount, per: Some(per), } } } fn parse_limit_with_suffix(s: &str) -> Result<usize, ParseError> { let s = s.trim().to_lowercase(); if let Ok(v) = s.parse::<usize>() { return Ok(v); } let suffixes = ["k", "m", "g", "t", "p", "e", "z", "y"]; for (i, suffix) in suffixes.iter().enumerate() { match s .split(suffix) .next() .expect("could not split the suffix off") .parse::<usize>() { Err(_) => continue, Ok(v) => return Ok(v * 1024usize.pow((i + 1) as u32)), }; } Err(ParseError::InvalidLimitLiteral(s)) } impl str::FromStr for Limit { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { let parts: Vec<_> = s.split('/').collect(); let val = parse_limit_with_suffix(parts[0])?; match parts.len() { 1 => Ok(Limit::amount(val)), 2 => Ok(Limit::amount_per(val, parts[1].parse::<SubjectType>()?)), _ => Err(ParseError::LimitBogusData(format!( "/{}", parts[2..].join("/") ))), } } } impl fmt::Display for Limit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let amount = match NumberPrefix::binary(self.amount as f64) { NumberPrefix::Standalone(amt) => format!("{}", amt), NumberPrefix::Prefixed(prefix, amt) => { let prefix = match prefix { Prefix::Kibi => "k", Prefix::Mebi => "m", Prefix::Gibi => "g", Prefix::Tebi => "t", Prefix::Pebi => "p", Prefix::Exbi => "e", Prefix::Zebi => "z", Prefix::Yobi => "y", _ => panic!("called binary_prefix but got decimal prefix"), }; format!("{}{}", amt, prefix) } }; let per = match &self.per { Some(ref s) => format!("/{}", s), None => "".to_string(), }; write!(f, "{}{}", amount, per) } } impl<'a> From<&'a Limit> for String { fn from(limit: &'a Limit) -> String { let per = match &limit.per { Some(ref s) => format!("/{}", s), None => "".to_string(), }; format!("{}{}", limit.amount, per) } } /// A rule represents an [Action] to be taken when a particular [Subject] hits /// a [Limit] for a [Resource]. /// /// Syntax for the string representation of a rule is /// `subject:subject-id:resource:action=amount/per`. /// /// # Examples /// /// ```rust /// use rctl::{Subject, SubjectType, Resource, Action, Limit, Rule}; /// let rule = Rule { /// subject: Subject::user_name("nobody").expect("no user 'nobody'"), /// resource: Resource::VMemoryUse, /// action: Action::Deny, /// limit: Limit::amount(1024*1024*1024), /// }; /// /// assert_eq!(rule.to_string(), "user:nobody:vmemoryuse:deny=1g".to_string()); /// ``` #[derive(Debug, Clone, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serialize", derive(serde::Serialize))] pub struct Rule { pub subject: Subject, pub resource: Resource, pub limit: Limit, pub action: Action, } impl Rule { /// Add this rule to the resource limits database. /// /// # Example /// /// ``` /// # extern crate rctl; /// # if !rctl::State::check().is_enabled() { /// # return; /// # } /// use rctl::{Rule, Subject, Resource, Action, Limit}; /// /// let rule = Rule { /// subject: Subject::jail_name("testjail_rctl_rule_apply_method"), /// resource: Resource::VMemoryUse, /// action: Action::Log, /// limit: Limit::amount(100*1024*1024), /// }; /// /// rule.apply(); /// # rule.remove(); /// ``` pub fn apply(&self) -> Result<(), Error> { extern "C" { fn rctl_add_rule( inbufp: *const libc::c_char, inbuflen: libc::size_t, outbufp: *mut libc::c_char, outbuflen: libc::size_t, ) -> libc::c_int; } rctl_api_wrapper(rctl_add_rule, self)?; Ok(()) } /// Attempt to remove this rule from the resource limits database. /// /// # Example /// /// ``` /// # extern crate rctl; /// # if !rctl::State::check().is_enabled() { /// # return; /// # } /// use rctl::{Rule, Subject, Resource, Action, Limit}; /// /// let rule = Rule { /// subject: Subject::jail_name("testjail_rctl_rule_remove_method"), /// resource: Resource::VMemoryUse, /// action: Action::Log, /// limit: Limit::amount(100*1024*1024), /// }; /// /// # rule.apply(); /// rule.remove(); /// ``` pub fn remove(&self) -> Result<(), Error> { let filter: Filter = self.into(); filter.remove_rules() } } impl fmt::Display for Rule { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}:{}:{}={}", self.subject, self.resource, self.action, self.limit ) } } impl<'a> From<&'a Rule> for String { fn from(rule: &'a Rule) -> String { let subject: String = (&rule.subject).into(); let resource: &str = (&rule.resource).into(); let action: &str = (&rule.action).into(); let limit: String = (&rule.limit).into(); format!("{}:{}:{}={}", subject, resource, action, limit) } } impl str::FromStr for Rule { type Err = ParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { // subject:subject-id:resource:action=amount/per let parts: Vec<_> = s.split(':').collect(); if parts.len() != 4 { return Err(ParseError::InvalidRuleSyntax(s.into())); } let subject = format!("{}:{}", parts[0], parts[1]).parse::<Subject>()?; let resource = parts[2].parse::<Resource>()?; let parts: Vec<_> = parts[3].split('=').collect(); if parts.len() != 2 { return Err(ParseError::InvalidRuleSyntax(s.into())); } let action = parts[0].parse::<Action>()?; let limit = parts[1].parse::<Limit>()?; Ok(Rule { subject, resource, action, limit, }) } } /// Adapter over objects parseable into a [Rule] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RuleParserAdapter<I> { inner: I, } impl<'a, I> Iterator for RuleParserAdapter<I> where I: Iterator<Item = &'a str>, { type Item = Rule; fn next(&mut self) -> Option<Rule> { match self.inner.next() { Some(item) => item.parse::<Rule>().ok(), None => None, } } } /// Owning struct implementing IntoIterator, returning a [RuleParserAdapter]. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct RuleParsingIntoIter<S> { inner: S, } impl<'a> IntoIterator for &'a RuleParsingIntoIter<String> { type Item = Rule; type IntoIter = RuleParserAdapter<str::Split<'a, char>>; fn into_iter(self) -> Self::IntoIter { RuleParserAdapter { inner: self.inner.split(','), } } } trait RuleParsingExt<'a>: Sized { fn parse_rules(self) -> RuleParserAdapter<Self>; } impl<'a> RuleParsingExt<'a> for str::Split<'a, &'a str> { fn parse_rules(self) -> RuleParserAdapter<Self> { RuleParserAdapter { inner: self } } } /// A filter can match a set of [Rules](Rule). #[derive(Debug, Default, Clone, PartialEq)] pub struct Filter { subject_type: Option<SubjectType>, subject: Option<Subject>, resource: Option<Resource>, limit: Option<Limit>, action: Option<Action>, limit_per: Option<SubjectType>, } impl Filter { /// Return the filter that matches all rules /// /// # Example /// /// ``` /// # use rctl::Filter; /// let filter = Filter::new(); /// assert_eq!(filter.to_string(), ":".to_string()); /// ``` pub fn new() -> Filter { Filter::default() } /// Constrain the filter to a specific [SubjectType] /// /// If the filter is already constrained to a subject, this is a No-Op. /// /// # Example /// /// ``` /// # use rctl::{Filter, SubjectType}; /// let filter = Filter::new() /// .subject_type(&SubjectType::LoginClass); /// assert_eq!(filter.to_string(), "loginclass:".to_string()); /// ``` pub fn subject_type(mut self: Filter, subject_type: &SubjectType) -> Filter { if self.subject.is_none() { self.subject_type = Some(*subject_type); } self } /// Constrain the filter to a specific [Subject] /// /// Resets the subject type. /// /// # Example /// /// ``` /// # use rctl::{Filter, Subject}; /// let filter = Filter::new() /// .subject(&Subject::user_name("nobody").expect("no user 'nobody'")); /// assert_eq!(filter.to_string(), "user:nobody".to_string()); /// ``` pub fn subject(mut self: Filter, subject: &Subject) -> Filter { self.subject = Some(subject.clone()); self.subject_type = None; self } /// Constrain the filter to a specific [Resource] /// /// # Example /// /// ``` /// # use rctl::{Filter, Resource}; /// let filter = Filter::new() /// .resource(&Resource::MemoryLocked); /// assert_eq!(filter.to_string(), "::memorylocked".to_string()); /// ``` pub fn resource(mut self: Filter, resource: &Resource) -> Filter { self.resource = Some(*resource); self } /// Constrain the filter to a specific [Action] /// /// # Example /// /// ``` /// # use rctl::{Filter, Action}; /// let filter = Filter::new() /// .action(&Action::Deny); /// assert_eq!(filter.to_string(), ":::deny".to_string()); /// ``` pub fn action(mut self: Filter, action: &Action) -> Filter { self.action = Some(*action); self } /// Constrain the filter to the [Deny](Action::Deny) [Action] /// /// # Example /// /// ``` /// # use rctl::{Filter, Action}; /// let filter = Filter::new() /// .deny(); /// assert_eq!(filter, Filter::new().action(&Action::Deny)); /// ``` pub fn deny(self: Filter) -> Filter { self.action(&Action::Deny) } /// Constrain the filter to the [Log](Action::Log) [Action] /// /// # Example /// /// ``` /// # use rctl::{Filter, Action}; /// let filter = Filter::new() /// .log(); /// assert_eq!(filter, Filter::new().action(&Action::Log)); /// ``` pub fn log(self: Filter) -> Filter { self.action(&Action::Log) } /// Constrain the filter to the [DevCtl](Action::DevCtl) [Action] /// /// # Example /// /// ``` /// # use rctl::{Filter, Action}; /// let filter = Filter::new() /// .devctl(); /// assert_eq!(filter, Filter::new().action(&Action::DevCtl)); /// ``` pub fn devctl(self: Filter) -> Filter { self.action(&Action::DevCtl) } /// Constrain the filter to the [Signal](Action::Signal) [Action] /// /// # Example /// /// ``` /// # extern crate rctl; /// # use rctl::{Filter, Action, Signal}; /// let filter = Filter::new() /// .signal(Signal::SIGTERM); /// assert_eq!(filter.to_string(), ":::sigterm".to_string()); /// ``` pub fn signal(self: Filter, signal: Signal) -> Filter { self.action(&Action::Signal(signal)) } /// Constrain the filter to a particular [Limit] /// /// Resets any limit_per, if the given limit has a `per` set. /// /// # Examples /// /// ``` /// # use rctl::{Filter, Limit}; /// let filter = Filter::new() /// .limit(&Limit::amount(100*1024*1024)); /// assert_eq!(filter.to_string(), ":::=100m".to_string()); /// ``` /// /// ``` /// # use rctl::{Filter, Limit, SubjectType}; /// let filter = Filter::new() /// .limit(&Limit::amount_per(100*1024*1024, SubjectType::Process)); /// assert_eq!(filter.to_string(), ":::=100m/process".to_string()); /// ``` pub fn limit(mut self: Filter, limit: &Limit) -> Filter { let mut limit = limit.clone(); // if the limit given doesn't have a `per` set, but we do, move it // into the limit. if let (Some(limit_per), None) = (self.limit_per, limit.per) { limit.per = Some(limit_per); } self.limit_per = None; self.limit = Some(limit); self } fn sanity(&self) { if let (Some(ref subject), Some(ref subject_type)) = (&self.subject, &self.subject_type) { let actual_type: SubjectType = subject.into(); assert_eq!(&actual_type, subject_type); } } /// Return an [IntoIterator] over all [Rules] matching this [Filter]. /// /// # Example /// /// List all rules: /// /// ``` /// use rctl; /// /// let filter = rctl::Filter::new(); /// for rule in filter.rules() { /// println!("{:?}", rule); /// } /// ``` /// /// [Rules]: Rule pub fn rules(&self) -> Result<RuleParsingIntoIter<String>, Error> { extern "C" { fn rctl_get_rules( inbufp: *const libc::c_char, inbuflen: libc::size_t, outbufp: *mut libc::c_char, outbuflen: libc::size_t, ) -> libc::c_int; } let outbuf = rctl_api_wrapper(rctl_get_rules, self)?; Ok(RuleParsingIntoIter { inner: outbuf }) } /// Remove all matching [Rules] from the resource limits database. /// /// # Examples /// /// ``` /// # extern crate rctl; /// # if !rctl::State::check().is_enabled() { /// # return; /// # } /// # use rctl::{Rule, Resource, Action, Limit}; /// use rctl::{Filter, Subject}; /// # let rule = Rule { /// # subject: Subject::jail_name("testjail_rctl_filter_remove"), /// # resource: Resource::VMemoryUse, /// # action: Action::Log, /// # limit: Limit::amount(100*1024*1024), /// # }; /// # rule.apply(); /// # let rule = Rule { /// # subject: Subject::jail_name("testjail_rctl_filter_remove"), /// # resource: Resource::StackSize, /// # action: Action::Log, /// # limit: Limit::amount(100*1024*1024), /// # }; /// # rule.apply(); /// let filter = Filter::new() /// .subject(&Subject::jail_name("testjail_rctl_filter_remove")) /// .remove_rules() /// .expect("Could not remove rules"); /// ``` /// /// Remove all rules, clearing the resource limits database by using the /// default (`':'`) [Filter]: /// ```no_run /// # extern crate rctl; /// # use rctl::{Rule, Subject, Resource, Action, Limit}; /// use rctl; /// /// rctl::Filter::new().remove_rules().expect("Could not remove all rules"); /// ``` /// /// [Rules]: Rule pub fn remove_rules(&self) -> Result<(), Error> { extern "C" { fn rctl_remove_rule( inbufp: *const libc::c_char, inbuflen: libc::size_t, outbufp: *mut libc::c_char, outbuflen: libc::size_t, ) -> libc::c_int; } rctl_api_wrapper(rctl_remove_rule, self)?; Ok(()) } } impl fmt::Display for Filter { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.sanity(); match self { Filter { subject_type: Some(s), .. } => write!(f, "{}:", s), Filter { subject_type: None, subject: Some(ref s), .. } => write!(f, "{}", s), Filter { subject_type: None, subject: None, .. } => write!(f, ":"), }?; // If Resource, Action, and Limit are unset, leave it at this. if let Filter { resource: None, action: None, limit: None, limit_per: None, .. } = self { return Ok(()); } match &self.resource { Some(resource) => write!(f, ":{}", resource), None => write!(f, ":"), }?; // If action, and limit are unset, leave it at this. if let Filter { action: None, limit: None, limit_per: None, .. } = self { return Ok(()); } match &self.action { Some(action) => write!(f, ":{}", action), None => write!(f, ":"), }?; // If limit is unset, leave it at this if let Filter { limit: None, limit_per: None, .. } = self { return Ok(()); } match &self.limit { Some(limit) => write!(f, "={}", limit), None => write!( f, "=/{}", self.limit_per.expect("could not unwrap limit_per") ), } } } impl<'a> From<&'a Filter> for String { fn from(filter: &'a Filter) -> String { let subject: String = match filter.subject { Some(ref s) => s.into(), None => ":".into(), }; let resource: &str = match filter.resource { Some(ref r) => r.into(), None => "", }; let action: &str = match filter.action { Some(ref a) => a.into(), None => "", }; let limit: String = match filter.limit { Some(ref l) => l.into(), None => "".into(), }; format!("{}:{}:{}={}", subject, resource, action, limit) } } impl From<Rule> for Filter { fn from(rule: Rule) -> Self { Filter { subject_type: None, subject: Some(rule.subject), resource: Some(rule.resource), limit: Some(rule.limit), limit_per: None, action: Some(rule.action), } } } impl<'a> From<&'a Rule> for Filter { fn from(rule: &'a Rule) -> Self { let rule = rule.clone(); Filter { subject_type: None, subject: Some(rule.subject), resource: Some(rule.resource), limit: Some(rule.limit), limit_per: None, action: Some(rule.action), } } } impl<'a> From<&'a Subject> for Filter { fn from(subject: &'a Subject) -> Self { Filter::new().subject(subject) } } impl From<Subject> for Filter { fn from(subject: Subject) -> Self { Filter::new().subject(&subject) } } impl<'a> From<&'a SubjectType> for Filter { fn from(subject_type: &'a SubjectType) -> Self { Filter::new().subject_type(subject_type) } } impl From<SubjectType> for Filter { fn from(subject_type: SubjectType) -> Self { Filter::new().subject_type(&subject_type) } } impl<'a> From<&'a Action> for Filter { fn from(action: &'a Action) -> Self { Filter::new().action(action) } } impl From<Action> for Filter { fn from(action: Action) -> Self { Filter::new().action(&action) } } impl<'a> From<&'a Limit> for Filter { fn from(limit: &'a Limit) -> Self { Filter::new().limit(limit) } } impl From<Limit> for Filter { fn from(limit: Limit) -> Self { Filter::new().limit(&limit) } } /// Enum representing the state of `RACCT`/`RCTL` in the kernel. #[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)] pub enum State { /// `RCTL` / `RACCT` is present in the kernel, but is not enabled via the /// `kern.racct.enable` tunable. Disabled, /// `RCTL` / `RACCT` is enabled. Enabled, /// `RCTL` / `RACCT` is disabled. /// /// The kernel does not support `RCTL` / `RACCT`. The following options have /// to be set in the kernel configuration when compiling the kernel to /// add support for `RCTL` / `RACCT`: /// /// ```ignore /// options RACCT /// options RCTL /// ``` NotPresent, /// `RCTL` is not available within a Jail Jailed, } impl State { /// Check the state of the `RCTL` / `RACCT` support. /// /// This queries the `kern.racct.enable` sysctl. If this fails in any way, /// (most probably by the sysctl not being present), the kernel is assumed /// to be compiled without the `RCTL` / `RACCT` options. /// /// # Example /// /// ``` /// # use rctl; /// let state = rctl::State::check(); /// ``` pub fn check() -> State { // RCTL is not available in a jail let jailed = sysctl::Ctl::new("security.jail.jailed"); // If the sysctl call fails (unlikely), we assume we're in a Jail. if jailed.is_err() { return State::Jailed; } match jailed.unwrap().value() { Ok(sysctl::CtlValue::Int(0)) => {} _ => return State::Jailed, }; // Check the kern.racct.enable sysctl. let enable_racct = sysctl::Ctl::new("kern.racct.enable"); // If the sysctl call fails, we assume it to be disabled. if enable_racct.is_err() { return State::NotPresent; } match enable_racct.unwrap().value() { Ok(value) => match value { // FreeBSD 13 returns a U8 as the kernel variable is a bool. sysctl::CtlValue::U8(1) => State::Enabled, // FreeBSD older than 13 returns a Uint as the kernel variable // is an int. sysctl::CtlValue::Uint(1) => State::Enabled, // Other values we assume means RACCT is disabled. _ => State::Disabled, }, // If we could not get the sysctl value, assume it to be disabled. _ => State::NotPresent, } } /// Return `true` if the `RCTL` / `RACCT` support is [Enabled]. /// /// # Examples /// /// ``` /// # use rctl; /// if rctl::State::check().is_enabled() { /// // do things requiring `RCTL` / `RACCT` support. /// } /// ``` /// /// [Enabled]: State::Enabled pub fn is_enabled(&self) -> bool { matches!(self, State::Enabled) } /// Return `true` if the kernel has `RCTL` / `RACCT` support compiled in. /// /// # Examples /// /// ``` /// # use rctl; /// if ! rctl::State::check().is_present() { /// println!("The kernel does not have RCTL / RACCT support"); /// } /// ``` pub fn is_present(&self) -> bool { !matches!(self, State::NotPresent) } } impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { State::Enabled => write!(f, "enabled"), State::Disabled => write!(f, "disabled"), State::NotPresent => write!(f, "not present"), State::Jailed => write!(f, "not available in a jail"), } } } fn rctl_api_wrapper<S: Into<String>>( api: unsafe extern "C" fn( *const libc::c_char, libc::size_t, *mut libc::c_char, libc::size_t, ) -> libc::c_int, input: S, ) -> Result<String, Error> { // Get the input buffer as a C string. let input: String = input.into(); let inputlen = input.len() + 1; let inbuf = CString::new(input).map_err(Error::CStringError)?; // C compatible output buffer. let mut outbuf: Vec<i8> = vec![0; RCTL_DEFAULT_BUFSIZE]; loop { // Unsafe C call to get the jail resource usage. if unsafe { api( inbuf.as_ptr(), inputlen, outbuf.as_mut_ptr() as *mut libc::c_char, outbuf.len(), ) } != 0 { let err = io::Error::last_os_error(); match err.raw_os_error() { Some(libc::ERANGE) => { // if the error code is ERANGE, retry with a larger buffer let current_len = outbuf.len(); outbuf.resize(current_len + RCTL_DEFAULT_BUFSIZE, 0); continue; } Some(libc::EPERM) => { let state = State::check(); break match state.is_enabled() { true => Err(Error::OsError(err)), false => Err(Error::InvalidKernelState(State::check())), }; } Some(libc::ENOSYS) => break Err(Error::InvalidKernelState(State::check())), Some(libc::ESRCH) => break Ok("".into()), _ => break Err(Error::OsError(err)), } } // If everything went well, convert the return C string in the outbuf // back into an easily usable Rust string and return. break Ok( unsafe { CStr::from_ptr(outbuf.as_ptr() as *mut libc::c_char) } .to_string_lossy() .into(), ); } } #[cfg(test)] pub mod tests { use super::*; use std::collections::HashSet; #[test] fn parse_subject_type() { assert_eq!( "user" .parse::<SubjectType>() .expect("could not parse user subject type"), SubjectType::User, ); assert_eq!( "jail" .parse::<SubjectType>() .expect("could not parse jail subject type"), SubjectType::Jail, ); assert!("bogus".parse::<SubjectType>().is_err()); } #[test] fn parse_subject() { assert_eq!( "user:42" .parse::<Subject>() .expect("Could not parse 'user:42' as Subject"), Subject::user_id(42) ); assert_eq!( "user:nobody" .parse::<Subject>() .expect("Could not parse 'user:nobody' as Subject"), Subject::user_name("nobody").expect("no user 'nobody'") ); assert_eq!( "process:42" .parse::<Subject>() .expect("Could not parse 'process:42' as Subject"), Subject::process_id(42) ); assert_eq!( "jail:www" .parse::<Subject>() .expect("Could not parse 'jail:www' as Subject"), Subject::jail_name("www") ); assert_eq!( "loginclass:test" .parse::<Subject>() .expect("Could not parse 'loginclass:test' as Subject"), Subject::login_class("test") ); assert!("".parse::<Subject>().is_err()); assert!(":".parse::<Subject>().is_err()); assert!(":1234".parse::<Subject>().is_err()); assert!("bogus".parse::<Subject>().is_err()); assert!("user".parse::<Subject>().is_err()); assert!("process:bogus".parse::<Subject>().is_err()); assert!("process:".parse::<Subject>().is_err()); assert!("user:test:bogus".parse::<Subject>().is_err()); } #[test] fn parse_resource() { assert_eq!( "vmemoryuse" .parse::<Resource>() .expect("could not parse vmemoryuse resource"), Resource::VMemoryUse, ); assert!("bogus".parse::<Resource>().is_err()); } #[test] fn parse_action() { assert_eq!( "deny" .parse::<Action>() .expect("could not parse deny action"), Action::Deny ); assert_eq!( "log".parse::<Action>().expect("could not parse log action"), Action::Log ); assert_eq!( "throttle" .parse::<Action>() .expect("could not parse throttle action"), Action::Throttle ); assert_eq!( "devctl" .parse::<Action>() .expect("could not parse devctl action"), Action::DevCtl ); assert_eq!( "sigterm" .parse::<Action>() .expect("could not parse sigterm action"), Action::Signal(Signal::SIGTERM) ); assert!("bogus".parse::<Action>().is_err()); } #[test] fn display_limit() { assert_eq!( Limit { amount: 100 * 1024 * 1024, per: None } .to_string(), "100m".to_string() ); assert_eq!( Limit { amount: 100 * 1024 * 1024, per: Some(SubjectType::User) } .to_string(), "100m/user".to_string() ); assert_eq!( Limit { amount: 42, per: Some(SubjectType::LoginClass) } .to_string(), "42/loginclass".to_string() ); } #[test] fn parse_limit() { assert_eq!( "100m" .parse::<Limit>() .expect("Could not parse '100m' as Limit"), Limit::amount(100 * 1024 * 1024), ); assert_eq!( "100m/user" .parse::<Limit>() .expect("Could not parse '100m/user' as Limit"), Limit::amount_per(100 * 1024 * 1024, SubjectType::User), ); assert!("100m/bogus".parse::<Limit>().is_err()); assert!("100m/userbogus".parse::<Limit>().is_err()); assert!("100q".parse::<Limit>().is_err()); assert!("-42".parse::<Limit>().is_err()); assert!("".parse::<Limit>().is_err()); assert!("bogus".parse::<Limit>().is_err()); } #[test] fn parse_rule() { assert_eq!( "user:nobody:vmemoryuse:deny=1g" .parse::<Rule>() .expect("Could not parse 'user:nobody:vmemoryuse:deny=1g' as Rule"), Rule { subject: Subject::user_name("nobody").expect("no user 'nobody'"), resource: Resource::VMemoryUse, action: Action::Deny, limit: Limit::amount(1 * 1024 * 1024 * 1024), } ); assert!(":::=/".parse::<Rule>().is_err()); assert!("user:missing_resource:=100m/user".parse::<Rule>().is_err()); assert!("user:missing_resource=100m/user".parse::<Rule>().is_err()); assert!("user:too:many:colons:vmemoryuse:deny=100m/user" .parse::<Rule>() .is_err()); assert!("loginclass:nolimit:vmemoryuse:deny=" .parse::<Rule>() .is_err()); assert!("loginclass:nolimit:vmemoryuse:deny" .parse::<Rule>() .is_err()); assert!("loginclass:equals:vmemoryuse:deny=123=456" .parse::<Rule>() .is_err()); assert!("-42".parse::<Rule>().is_err()); assert!("".parse::<Rule>().is_err()); assert!("bogus".parse::<Rule>().is_err()); } #[test] fn display_filter() { assert_eq!(Filter::new().to_string(), ":".to_string()); assert_eq!( Filter::new() .subject_type(&SubjectType::LoginClass) .to_string(), "loginclass:".to_string() ); assert_eq!( Filter::new().subject(&Subject::user_id(42)).to_string(), "user:42".to_string() ); assert_eq!( Filter::new().resource(&Resource::MaxProcesses).to_string(), "::maxproc".to_string() ); assert_eq!( Filter::new() .subject(&Subject::user_id(42)) .resource(&Resource::MemoryUse) .to_string(), "user:42:memoryuse".to_string() ); assert_eq!(Filter::new().deny().to_string(), ":::deny".to_string()); } #[test] fn iterate_rules() { if !State::check().is_enabled() { return; } let common_subject = Subject::jail_name("testjail_rctl_rules"); let rule1 = Rule { subject: common_subject.clone(), resource: Resource::VMemoryUse, action: Action::Log, limit: Limit::amount(100 * 1024 * 1024), }; rule1.apply().expect("Could not apply rule 1"); let rule2 = Rule { subject: common_subject.clone(), resource: Resource::StackSize, action: Action::Log, limit: Limit::amount(100 * 1024 * 1024), }; rule2.apply().expect("Could not apply rule 2"); let filter = Filter::new().subject(&common_subject); let rules: HashSet<_> = filter .rules() .expect("Could not get rules matching filter") .into_iter() .collect(); assert!(rules.contains(&rule1)); assert!(rules.contains(&rule2)); filter.remove_rules().expect("Could not remove rules"); } #[cfg(feature = "serialize")] #[test] fn serialize_rule() { let rule = "process:23:vmemoryuse:sigterm=100m" .parse::<Rule>() .expect("Could not parse rule"); let serialized = serde_json::to_string(&rule).expect("Could not serialize rule"); let rule_map: serde_json::Value = serde_json::from_str(&serialized).expect("Could not load serialized rule"); assert_eq!(rule_map["subject"]["Process"], 23); assert_eq!(rule_map["resource"], "VMemoryUse"); assert_eq!(rule_map["action"]["Signal"], "SIGTERM"); assert_eq!(rule_map["limit"]["amount"], 100 * 1024 * 1024) } }