text
stringlengths
8
4.13M
use pwasm_test::{ext_get, ext_reset, Endpoint}; use pwasm_abi::eth::EndpointInterface; use pwasm_abi_derive::eth_abi; use pwasm_abi::types::{H160, U256}; type Address = H160; #[eth_abi(TestEndpoint, Client)] pub trait TestContract { fn constructor(&mut self, _p: bool); fn baz(&mut self, _p1: u32, _p2: bool); fn boo(&mut self, _arg: u32) -> u32; fn sam(&mut self, _p1: Vec<u8>, _p2: bool, _p3: Vec<U256>); #[event] fn baz_fired(&mut self, indexed_p1: u32, p2: u32); } const PAYLOAD_SAMPLE_1: &[u8] = &[ 0xcd, 0xcd, 0x77, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, ]; const PAYLOAD_SAMPLE_2: &[u8] = &[ 0xa5, 0x64, 0x3b, 0xf2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x64, 0x61, 0x76, 0x65, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, ]; const PAYLOAD_SAMPLE_3: &[u8] = &[ 0x5d, 0xda, 0xb4, 0xd4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x45, ]; #[test] fn baz_dispatch() { #[derive(Default)] struct TestContractInstance { called: bool, called_wrong: bool, } impl TestContract for TestContractInstance { fn constructor(&mut self, _p1: bool) { } fn baz(&mut self, p1: u32, p2: bool) { assert_eq!(p1, 69); assert_eq!(p2, true); self.called = true; } fn boo(&mut self, _arg: u32) -> u32 { self.called_wrong = true; 0 } fn sam(&mut self, _p1: Vec<u8>, _p2: bool, _p3: Vec<U256>) { self.called_wrong = true; } } let mut endpoint = TestEndpoint::new(TestContractInstance::default()); let result = endpoint.dispatch(PAYLOAD_SAMPLE_1); assert_eq!(result, Vec::new()); assert!(endpoint.inner.called, "`baz` method was not invoked"); assert!(!endpoint.inner.called_wrong, "wrong method was invoked"); } #[test] fn sam_dispatch() { #[derive(Default)] struct TestContractInstance { called: bool, called_wrong: bool, } impl TestContract for TestContractInstance { fn constructor(&mut self, _p1: bool) { } fn sam(&mut self, p1: Vec<u8>, p2: bool, p3: Vec<U256>) { assert_eq!(p1, vec![100, 97, 118, 101]); assert_eq!(p2, true); assert_eq!(p3, vec![ U256::from("1"), U256::from("2"), U256::from("3"), ]); self.called = true; } fn baz(&mut self, _p1: u32, _p2: bool) { self.called_wrong = true; } fn boo(&mut self, _arg: u32) -> u32 { self.called_wrong = true; 0 } } let mut endpoint = TestEndpoint::new(TestContractInstance::default()); let result = endpoint.dispatch(PAYLOAD_SAMPLE_2); assert_eq!(result, Vec::new()); assert!(endpoint.inner.called, "`sam` method was not invoked"); assert!(!endpoint.inner.called_wrong, "wrong method was invoked"); } #[test] fn boo_dispatch() { #[derive(Default)] struct TestContractInstance { called: bool, called_wrong: bool, } impl TestContract for TestContractInstance { fn constructor(&mut self, _p1: bool) { } fn sam(&mut self, _p1: Vec<u8>, _p2: bool, _p3: Vec<U256>) { self.called_wrong = true; } fn baz(&mut self, _p1: u32, _p2: bool) { self.called_wrong = true; } fn boo(&mut self, arg: u32) -> u32 { self.called = true; assert_eq!(arg, 69); 255 } } let mut endpoint = TestEndpoint::new(TestContractInstance::default()); let result = endpoint.dispatch(PAYLOAD_SAMPLE_3); assert_eq!(&result[28..32], &[0x00, 0x00, 0x00, 0xff]); assert!(endpoint.inner.called, "`boo` method was not invoked"); assert!(!endpoint.inner.called_wrong, "wrong method was invoked"); } #[allow(dead_code)] mod contract { use pwasm_abi_derive::eth_abi; #[eth_abi(EmptyEndpoint, _EmptyClient)] trait EmptyContract { fn constructor(&mut self, _p: bool); } pub struct EmptyContractInstance { pub called: bool, pub p: bool } impl EmptyContract for EmptyContractInstance { fn constructor(&mut self, p1: bool) { self.called = true; self.p = p1; } } } #[test] fn dispatch_empty_abi() { let mut endpoint = contract::EmptyEndpoint::new(contract::EmptyContractInstance{called: false, p: false}); endpoint.dispatch_ctor(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01]); assert!(endpoint.inner.called); assert!(endpoint.inner.p); } #[test] fn baz_call() { ext_reset(|e| e.endpoint(Address::zero(), Endpoint::ok())); let mut client = Client::new(Address::zero()); client.baz(69, true); assert_eq!(ext_get().calls()[0].input.as_ref(), PAYLOAD_SAMPLE_1); }
#[macro_use] extern crate hyper; extern crate rustc_serialize; pub mod oauth; pub mod oauth_web; pub mod notifications;
use std::collections::LinkedList; use serde_json::value::{Value, to_value}; use context::{ValueRender, ValueNumber, ValueTruthy, get_json_pointer}; use template::Template; use errors::TeraResult; use errors::TeraError::*; use parser::Node; use parser::Node::*; use tera::Tera; // we need to have some data in the renderer for when we are in a ForLoop // For example, accessing the local variable would fail when // looking it up in the context #[derive(Debug)] struct ForLoop { variable_name: String, current: usize, values: Vec<Value> } impl ForLoop { pub fn new(local: String, values: Vec<Value>) -> ForLoop { ForLoop { variable_name: local, current: 0, values: values } } pub fn increment(&mut self) { self.current += 1; } pub fn get(&self) -> Option<&Value> { self.values.get(self.current) } pub fn len(&self) -> usize { self.values.len() } pub fn is_empty(&self) -> bool { self.len() == 0 } } #[derive(Debug)] pub struct Renderer<'a> { template: &'a Template, context: Value, tera: &'a Tera, for_loops: Vec<ForLoop>, } impl<'a> Renderer<'a> { pub fn new(tpl: &'a Template, tera: &'a Tera, context: Value) -> Renderer<'a> { Renderer { template: tpl, tera: tera, context: context, for_loops: vec![], } } // Lookup a variable name from the context and takes into // account for loops variables fn lookup_variable(&self, key: &str) -> TeraResult<Value> { // Look in the plain context if we aren't in a for loop if self.for_loops.is_empty() { return self.context.pointer(&get_json_pointer(key)).cloned() .ok_or_else(|| FieldNotFound(key.to_string())); } for for_loop in self.for_loops.iter().rev() { if key.starts_with(&for_loop.variable_name) { let value = match for_loop.get() { Some(f) => f, None => { return Ok(to_value(&"")); } }; // might be a struct or some nested structure if key.contains('.') { let new_key = key.split_terminator('.').skip(1).collect::<Vec<&str>>().join("."); return value.pointer(&get_json_pointer(&new_key)) .cloned() .ok_or_else(|| FieldNotFound(key.to_string())); } else { return Ok(value.clone()); } } else { match key { "loop.index" => { return Ok(to_value(&(for_loop.current + 1))); }, "loop.index0" => { return Ok(to_value(&for_loop.current)); }, "loop.first" => { return Ok(to_value(&(for_loop.current == 0))); }, "loop.last" => { return Ok(to_value(&(for_loop.current == for_loop.len() - 1))); }, _ => () }; } } // can get there when looking a variable in the global context while in a forloop self.context.pointer(&get_json_pointer(key)).cloned() .ok_or_else(|| FieldNotFound(key.to_string())) } // Gets an identifier and return its json value // If there is no filter, it's itself, otherwise call the filters in order // an return their result fn eval_ident(&self, node: &Node) -> TeraResult<Value> { match *node { Identifier { ref name, ref filters } => { let mut value = try!(self.lookup_variable(name)); if let Some(ref _filters) = *filters { for filter in _filters { match *filter { Filter { ref name, ref args, ref args_ident } => { let filter_fn = try!(self.tera.get_filter(name)); let mut all_args = args.clone(); for (arg_name, ident_name) in args_ident { all_args.insert(arg_name.to_string(), try!(self.lookup_variable(ident_name))); } value = try!(filter_fn(value, all_args)); }, _ => unreachable!(), }; } return Ok(value); } Ok(value) }, _ => unreachable!() } } fn eval_math(&self, node: &Node) -> TeraResult<f32> { match *node { Identifier { ref name, .. } => { let value = try!(self.eval_ident(node)); match value.to_number() { Ok(v) => Ok(v), Err(_) => Err(NotANumber(name.to_string())) } }, Int(s) => Ok(s as f32), Float(s) => Ok(s), Math { ref lhs, ref rhs, ref operator } => { let l = try!(self.eval_math(lhs)); let r = try!(self.eval_math(rhs)); let mut result = match operator.as_str() { "*" => l * r, "/" => l / r, "+" => l + r, "-" => l - r, _ => unreachable!() }; // TODO: fix properly // TODO: add tests for float maths arithmetics if result.fract() < 0.01 { result = result.round(); } Ok(result) } _ => unreachable!() } } fn eval_expression(&self, node: Node) -> TeraResult<Value> { match node { Identifier { .. } => { let value = try!(self.eval_ident(&node)); Ok(value) }, l @ Logic { .. } => { let value = try!(self.eval_condition(l)); Ok(Value::Bool(value)) }, m @ Math { .. } => { let result = try!(self.eval_math(&m)); Ok(Value::F64(result as f64)) }, Int(val) => { Ok(Value::I64(val as i64)) }, Float(val) => { Ok(Value::F64(val as f64)) }, Bool(b) => { Ok(Value::Bool(b)) }, _ => unreachable!() } } fn eval_condition(&self, node: Node) -> TeraResult<bool> { match node { Identifier { .. } => { Ok(self.eval_ident(&node).map(|v| v.is_truthy()).unwrap_or(false)) }, Test { expression, name, params } => { let tester = try!(self.tera.get_tester(&name)); let mut value_params = vec![]; for param in params { value_params.push(try!(self.eval_expression(param))); } tester(&name, self.eval_expression(*expression).ok(), value_params) }, Logic { lhs, rhs, operator } => { match operator.as_str() { "or" => { let result = try!(self.eval_condition(*lhs)) || try!(self.eval_condition(*rhs)); Ok(result) }, "and" => { let result = try!(self.eval_condition(*lhs)) && try!(self.eval_condition(*rhs)); Ok(result) }, ">=" | ">" | "<=" | "<" => { let l = try!(self.eval_math(&lhs)); let r = try!(self.eval_math(&rhs)); let result = match operator.as_str() { ">=" => l >= r, ">" => l > r, "<=" => l <= r, "<" => l < r, _ => unreachable!() }; Ok(result) }, "==" | "!=" => { let mut lhs_val = try!(self.eval_expression(*lhs)); let mut rhs_val = try!(self.eval_expression(*rhs)); // Monomorphize number vals. if lhs_val.is_number() || rhs_val.is_number() { if !lhs_val.is_number() || !rhs_val.is_number() { return Ok(false); } // Since Tera only support 32 bit integers, this // actually preserves all of the precision. If Tera // switches to 64-bit values, use std::f32::EPSILON // to get an approximation as before. lhs_val = Value::F64(lhs_val.as_f64().unwrap()); rhs_val = Value::F64(rhs_val.as_f64().unwrap()); } let result = match operator.as_str() { "==" => lhs_val == rhs_val, "!=" => lhs_val != rhs_val, _ => unreachable!() }; Ok(result) }, _ => unreachable!() } } _ => unreachable!() } } // eval all the values in a {{ }} block fn render_variable_block(&mut self, node: Node) -> TeraResult<String> { match node { Identifier { .. } => { let value = try!(self.eval_ident(&node)); Ok(value.render()) }, Math { .. } => { let result = try!(self.eval_math(&node)); Ok(result.to_string()) } _ => unreachable!() } } // evaluates conditions and render bodies accordingly fn render_if(&mut self, condition_nodes: LinkedList<Node>, else_node: Option<Box<Node>>) -> TeraResult<String> { let mut skip_else = false; let mut output = String::new(); for node in condition_nodes { match node { Conditional {condition, body } => { if try!(self.eval_condition(*condition)) { skip_else = true; // Remove if/elif whitespace output.push_str(try!(self.render_node(*body.clone())).trim_left()); } }, _ => unreachable!() } } if skip_else { // Remove endif whitespace return Ok(output.trim_right().to_string()); } if let Some(e) = else_node { // Remove else whitespace output.push_str(try!(self.render_node(*e)).trim_left()); }; // Remove endif whitespace Ok(output.trim_right().to_string()) } fn render_for(&mut self, variable_name: String, array_name: String, body: Box<Node>) -> TeraResult<String> { let list = try!(self.lookup_variable(&array_name)); if !list.is_array() { return Err(NotAnArray(array_name.to_string())); } // Safe unwrap let deserialized = list.as_array().unwrap(); let length = deserialized.len(); self.for_loops.push(ForLoop::new(variable_name, deserialized.clone())); let mut i = 0; let mut output = String::new(); if length > 0 { loop { output.push_str(try!(self.render_node(*body.clone())).trim_left()); // Safe unwrap self.for_loops.last_mut().unwrap().increment(); if i == length - 1 { // Don't forget to pop the for_loop is we are done // otherwise it would just replay the last loop // see https://github.com/Keats/tera/issues/51 self.for_loops.pop(); break; } i += 1; } output = output.trim_right().to_string(); } else { self.for_loops.pop(); } Ok(output.trim_right().to_string()) } pub fn render_node(&mut self, node: Node) -> TeraResult<String> { match node { Include(p) => { let ast = try!(self.tera.get_template(&p)).ast.get_children(); let mut output = String::new(); for node in ast { output.push_str(&try!(self.render_node(node))); } Ok(output) }, Text(s) => Ok(s), Raw(s) => Ok(s.trim().to_string()), VariableBlock(exp) => self.render_variable_block(*exp), If {condition_nodes, else_node} => { self.render_if(condition_nodes, else_node) }, List(body) => { let mut output = String::new(); for n in body { output.push_str(&try!(self.render_node(n))); } Ok(output) }, For {variable, array, body} => { self.render_for(variable, array, body) }, Block {name, body} => { match self.template.blocks.get(&name) { Some(b) => { match b.clone() { Block {body, ..} => { self.render_node(*body.clone()) }, _ => unreachable!() } }, None => { self.render_node(*body) } } }, _ => unreachable!() } } pub fn render(&mut self) -> TeraResult<String> { let ast = match self.template.parent { Some(ref p) => { let parent = try!(self.tera.get_template(p)); parent.ast.get_children() }, None => self.template.ast.get_children() }; let mut output = String::new(); for node in ast { output.push_str(&try!(self.render_node(node))); } Ok(output) } } #[cfg(test)] mod tests { use context::Context; use errors::TeraResult; use tera::Tera; fn render_template(content: &str, context: Context) -> TeraResult<String> { let mut tera = Tera::default(); tera.add_template("hello", content); tera.render("hello", context) } #[test] fn test_render_include() { let mut tera = Tera::default(); tera.add_template("world", "world"); tera.add_template("hello", "<h1>Hello {% include \"world\" %}</h1>"); let result = tera.render("hello", Context::new()); assert_eq!(result.unwrap(), "<h1>Hello world</h1>".to_owned()); } #[test] fn test_render_simple_string() { let result = render_template("<h1>Hello world</h1>", Context::new()); assert_eq!(result.unwrap(), "<h1>Hello world</h1>".to_owned()); } #[test] fn test_render_math() { let result = render_template("This is {{ 2000 + 16 }}.", Context::new()); assert_eq!(result.unwrap(), "This is 2016.".to_owned()); } #[test] fn test_render_basic_variable() { let mut context = Context::new(); context.add("name", &"Vincent"); let result = render_template("My name is {{ name }}.", context); assert_eq!(result.unwrap(), "My name is Vincent.".to_owned()); } #[test] fn test_render_math_with_variable() { let mut context = Context::new(); context.add("vat_rate", &0.20); let result = render_template("Vat: £{{ 100 * vat_rate }}.", context); assert_eq!(result.unwrap(), "Vat: £20.".to_owned()); } #[test] fn test_render_comment() { let result = render_template("<h1>Hello {# comment #} world</h1>", Context::new()); assert_eq!(result.unwrap(), "<h1>Hello world</h1>".to_owned()); } #[test] fn test_render_nested_comment() { let result = render_template("<h1>Hello {# comment {# nested #} world</h1>", Context::new()); assert_eq!(result.unwrap(), "<h1>Hello world</h1>".to_owned()); } #[test] fn test_ignore_variable_in_comment() { let mut context = Context::new(); context.add("name", &"Vincent"); let result = render_template("My name {# was {{ name }} #} is No One.", context); assert_eq!(result.unwrap(), "My name is No One.".to_owned()); } #[test] fn test_render_if_simple() { let mut context = Context::new(); context.add("is_admin", &true); let result = render_template("{% if is_admin %}Admin{% endif %}", context); assert_eq!(result.unwrap(), "Admin".to_owned()); } #[test] fn test_render_if_or_conditions() { let mut context = Context::new(); context.add("is_adult", &false); context.add("age", &18); let result = render_template("{% if is_adult or age + 1 > 18 %}Adult{% endif %}", context); assert_eq!(result.unwrap(), "Adult".to_owned()); } #[test] fn test_render_if_and_conditions_with_equality() { let mut context = Context::new(); context.add("is_adult", &true); context.add("age", &18); let result = render_template("{% if is_adult and age == 18 %}Adult{% endif %}", context); assert_eq!(result.unwrap(), "Adult".to_owned()); } #[test] fn test_render_basic_for() { let mut context = Context::new(); context.add("data", &vec![1,2,3]); let result = render_template("{% for i in data %}{{i}}{% endfor %}", context); assert_eq!(result.unwrap(), "123".to_owned()); } #[test] fn test_render_loop_variables() { let mut context = Context::new(); context.add("data", &vec![1,2,3]); let result = render_template( "{% for i in data %}{{loop.index}}{{loop.index0}}{{loop.first}}{{loop.last}}{% endfor %}", context ); assert_eq!(result.unwrap(), "10truefalse21falsefalse32falsetrue".to_owned()); } #[test] fn test_render_nested_loop_simple() { let mut context = Context::new(); context.add("vectors", &vec![vec![0, 3, 6], vec![1, 4, 7]]); let result = render_template( "{% for vector in vectors %}{% for j in vector %}{{ j }}{% endfor %}{% endfor %}", context ); assert_eq!(result.unwrap(), "036147".to_owned()); } #[test] fn test_render_nested_loop_with_empty_vec() { let mut context = Context::new(); context.add("vectors", &vec![vec![0, 3, 6], vec![], vec![1, 4, 7]]); let result = render_template( "{% for vector in vectors %}{% for j in vector %}{{ j }}{% endfor %}{% endfor %}", context ); assert_eq!(result.unwrap(), "036147".to_owned()); } #[test] fn test_render_filter() { let mut context = Context::new(); context.add("greeting", &"hello"); let result = render_template( "{{ greeting | upper }}", context ); assert_eq!(result.unwrap(), "HELLO".to_owned()); } #[test] fn test_render_index_array() { let mut context = Context::new(); context.add("my_arr", &vec![1, 2, 3]); context.add("my_arr2", &vec![(1,2,3), (1,2,3), (1,2,3)]); let result = render_template( "{{ my_arr.1 }}{{ my_arr2.1.1 }}", context ); assert_eq!(result.unwrap(), "22".to_owned()); } // this was a regression in 0.3.0 #[test] fn test_render_if_in_for() { let mut context = Context::new(); context.add("sel", &2u32); context.add("seq", &vec![1,2,3]); let result = render_template( "{% for val in seq %} {% if val == sel %} on {% else %} off {% endif %} {% endfor %}", context ); assert_eq!(result.unwrap(), "off on off".to_string()); } }
//! Data Link Layer packets pub mod ethernet; pub mod arp;
use std::sync::Arc; use vulkano::command_buffer::{ AutoCommandBufferBuilder, CommandBufferUsage, PrimaryAutoCommandBuffer, SecondaryCommandBuffer, SubpassContents, }; use vulkano::device::Queue; use vulkano::format::{ClearValue, Format}; use vulkano::image::view::ImageView; use vulkano::image::{AttachmentImage, ImageAccess, ImageUsage}; use vulkano::render_pass::{Framebuffer, FramebufferAbstract, RenderPass, Subpass}; use vulkano::sync::GpuFuture; use error::{DrawPassExecuteError, FrameCreationError, FrameSystemCreationError, NextPassError}; use crate::{graphics::utils, window::Size}; pub mod error; /// System that contains the necessary facilities for rendering a single frame. pub struct FrameSystem { /// Queue to render everything. graphics_queue: Arc<Queue>, /// Render pass used for the drawing. render_pass: Arc<RenderPass>, /// Intermediate render target that will contain the depth of each pixel of the scene. /// This is a traditional depth buffer. `0.0` means "near", and `1.0` means "far". depth_buffer: Option<Arc<AttachmentImage>>, } impl FrameSystem { /// Creates the frame system. pub fn new( graphics_queue: Arc<Queue>, final_output_format: Format, ) -> Result<Self, FrameSystemCreationError> { // Check queue for graphics support. if !graphics_queue.family().supports_graphics() { return Err(FrameSystemCreationError::QueueFamilyNotSupported); } let device = graphics_queue.device().clone(); let depth_format = utils::suitable_depth_stencil_format(device.physical_device()); // TODO: vulkano error: https://github.com/vulkano-rs/vulkano/issues/1665 let render_pass = Arc::new(vulkano::ordered_passes_renderpass! { graphics_queue.device().clone(), attachments: { color: { load: Clear, store: Store, format: final_output_format, samples: 1, }, depth: { load: Clear, store: DontCare, format: depth_format, samples: 1, initial_layout: ImageLayout::Undefined, final_layout: ImageLayout::DepthStencilAttachmentOptimal, } }, passes: [ // Subpass for complex rendering. { color: [color], depth_stencil: {depth}, input: [] }, // Subpass for UI rendering. { color: [color], depth_stencil: {}, input: [] } ] }?); Ok(Self { graphics_queue, render_pass, depth_buffer: None, }) } /// Retrieve subpass for object rendering. pub fn object_subpass(&self) -> Subpass { Subpass::from(self.render_pass.clone(), 0).unwrap() } /// Retrieve subpass for UI rendering. pub fn ui_subpass(&self) -> Subpass { Subpass::from(self.render_pass.clone(), 1).unwrap() } /// Starts drawing a new frame. pub fn frame<F, I>( &mut self, before_future: F, final_image: Arc<I>, ) -> Result<Frame, FrameCreationError> where F: GpuFuture + Send + Sync + 'static, I: ImageAccess + Send + Sync + 'static, { let device = self.graphics_queue.device().clone(); let dimensions = final_image.dimensions().width_height(); let old_dimensions = self .depth_buffer .as_ref() .map(|b| b.dimensions().width_height()); // If there is no depth buffer (first call after initialization) // or dimensions are incompatible, (re)create buffers. if old_dimensions.is_none() || old_dimensions.unwrap() != dimensions { // (Re)create depth buffer. let depth_buffer = { let depth_format = utils::suitable_depth_stencil_format(device.physical_device()); AttachmentImage::with_usage( device.clone(), dimensions, depth_format, ImageUsage::depth_stencil_attachment(), )? }; self.depth_buffer = Some(depth_buffer.clone()); } // Create framebuffer. let framebuffer = { let image_view = ImageView::new(final_image.clone())?; let depth_buffer_view = { let depth_buffer = self.depth_buffer.as_ref().unwrap().clone(); ImageView::new(depth_buffer)? }; Arc::new( Framebuffer::start(self.render_pass.clone()) .add(image_view)? .add(depth_buffer_view)? .build()?, ) }; let clear_values = [ ClearValue::Float([0.0, 0.0, 0.0, 1.0]), ClearValue::Depth(1.0), ]; // Build primary command buffer that will execute secondary command buffers // in rendering process. let mut builder = AutoCommandBufferBuilder::primary( device, self.graphics_queue.family(), CommandBufferUsage::OneTimeSubmit, )?; builder.begin_render_pass( framebuffer.clone(), SubpassContents::SecondaryCommandBuffers, clear_values, )?; Ok(Frame { system: self, subpass_number: 0, before_future: Some(Box::new(before_future)), framebuffer, command_buffer_builder: Some(builder), }) } } /// Represents the active process of rendering a frame. pub struct Frame<'a> { /// The borrowed `FrameSystem`. system: &'a mut FrameSystem, /// The active pass we are in. This keeps track of the step we are in. subpass_number: u8, /// Future to wait upon before the main rendering. before_future: Option<Box<dyn GpuFuture + Send + Sync>>, /// Framebuffer that was used when starting the render pass. framebuffer: Arc<dyn FramebufferAbstract + Send + Sync>, /// The command buffer builder that will be built during the lifetime of this object. command_buffer_builder: Option<AutoCommandBufferBuilder<PrimaryAutoCommandBuffer>>, } impl<'a> Frame<'a> { /// Returns an enumeration containing the next pass of the rendering. pub fn next_pass<'f>(&'f mut self) -> Result<Option<Pass<'f, 'a>>, NextPassError> { match { let current_pass = self.subpass_number; self.subpass_number += 1; current_pass } { // If we are in the pass 0 then we haven't start anything yet. // We return an object that will allow the user to draw objects on the scene. 0 => Ok(Some(Pass::Deferred(DrawPass { frame: self }))), // If we are in the pass 1 then we have finished drawing the objects on the scene. 1 => { self.command_buffer_builder .as_mut() .unwrap() .next_subpass(SubpassContents::SecondaryCommandBuffers)?; // Returning an object that will allow the user to render UI. Ok(Some(Pass::UI(DrawPass { frame: self }))) } // If we are in pass 2 then we have finished rendering UI. 2 => { self.command_buffer_builder .as_mut() .unwrap() .end_render_pass()?; let command_buffer = self.command_buffer_builder.take().unwrap().build()?; // Extract `before_future` and append the command buffer execution to it. let after_future = self .before_future .take() .unwrap() .then_execute(self.system.graphics_queue.clone(), command_buffer)?; // We obtain `after_future`, which we give to the user. Ok(Some(Pass::Finished(Box::new(after_future)))) } // The frame is in the finished state and we can't do anything. _ => Ok(None), } } } /// Struct provided to the user that allows them to customize or handle the pass. pub enum Pass<'f, 's: 'f> { /// We are in the pass where we draw objects on the scene. /// The `DrawPass` allows the user to draw the objects. Deferred(DrawPass<'f, 's>), /// We are in the pass where we draw UI on the screen. /// The `DrawPass` allows the user to draw the UI. UI(DrawPass<'f, 's>), /// The frame has been fully prepared, and here is the future that will perform the drawing /// on the image. Finished(Box<dyn GpuFuture + Send + Sync>), } /// Allows the user to draw objects on the scene. pub struct DrawPass<'f, 's: 'f> { frame: &'f mut Frame<'s>, } impl<'f, 's: 'f> DrawPass<'f, 's> { /// Appends a command that executes a secondary command buffer that performs drawing. pub fn execute<C>(&mut self, secondary_command_buffer: C) -> Result<(), DrawPassExecuteError> where C: SecondaryCommandBuffer + Send + Sync + 'static, { self.frame .command_buffer_builder .as_mut() .unwrap() .execute_commands(secondary_command_buffer)?; Ok(()) } /// Returns the dimensions in pixels of the viewport. pub fn viewport_size(&self) -> Size { let dimensions = self.frame.framebuffer.dimensions(); Size::new(dimensions[0], dimensions[1]) } }
#![feature(test)] use dev_util::impl_benchmark; impl_benchmark!(md4, Md4);
// mod counting { // pub mod check { // pub fn digits() { // println!("We are in check function of counting mod"); // for counting in 1..11 { // println!("{}",counting); // } // } // } // } mod lib; // using lib.rs file fn main() { // println!("Calling of mod in fn main function"); // crate::counting::check::digits(); lib::welcome::checking::digits(); //calling sub-module function named digits() in main.rs for execution }
#[derive(Debug)] pub enum Regex { Concat(Box<Regex>, Box<Regex>), Or(Box<Regex>, Box<Regex>), Quantified(Quantifier, Box<Regex>), Char(char), } #[derive(Debug)] pub enum Quantifier { Kleene, }
// Copyright 2020 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT use super::{decode, encode}; use bitvec::prelude::{BitVec, Lsb0}; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; /// Wrapper for serializing bit vector with RLE+ encoding pub struct BitVecSer<'a>(pub &'a BitVec<Lsb0, u8>); /// Wrapper for deserializing bit vector with RLE+ decoding from bytes. pub struct BitVecDe(pub BitVec<Lsb0, u8>); impl Serialize for BitVecSer<'_> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // This serialize will encode into rle+ before serializing serde_bytes::serialize(encode(self.0).as_slice(), serializer) } } impl<'de> Deserialize<'de> for BitVecDe { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { // Deserialize will decode using rle+ decompression let bz: Vec<u8> = serde_bytes::deserialize(deserializer)?; let compressed = BitVec::from_vec(bz); Ok(BitVecDe(decode(&compressed).map_err(de::Error::custom)?)) } } #[cfg(test)] mod tests { use super::*; use bitvec::bitvec; use encoding::{from_slice, to_vec}; #[test] fn serialize_node_symmetric() { let bit_vec = bitvec![Lsb0, u8; 0, 1, 0, 1, 1, 1, 1, 1, 1]; let cbor_bz = to_vec(&BitVecSer(&bit_vec)).unwrap(); let BitVecDe(deserialized) = from_slice::<BitVecDe>(&cbor_bz).unwrap(); assert_eq!(deserialized.count_ones(), 7); assert_eq!(deserialized.as_slice(), bit_vec.as_slice()); } #[test] // ported test from specs-actors `bitfield_test.go` with added vector fn bit_vec_unset_vector() { let mut bv: BitVec<Lsb0, u8> = BitVec::with_capacity(6); bv.resize(6, false); bv.set(1, true); bv.set(2, true); bv.set(3, true); bv.set(4, true); bv.set(5, true); bv.set(3, false); assert_ne!(bv.get(3), Some(&true)); assert_eq!(bv.count_ones(), 4); // Test cbor marshal and unmarshal let cbor_bz = to_vec(&BitVecSer(&bv)).unwrap(); assert_eq!(&cbor_bz, &[0x43, 0xa8, 0x54, 0x0]); let BitVecDe(deserialized) = from_slice::<BitVecDe>(&cbor_bz).unwrap(); assert_eq!(deserialized.count_ones(), 4); assert_ne!(bv.get(3), Some(&true)); } }
use super::{Environment, Modifications, System}; use crate::errors::Error; use serde::{Deserialize, Serialize}; mod lightloop; mod normal; mod off; mod quiet; mod silent; mod sleep; mod wakeup; pub use lightloop::LightLoop; pub use normal::Normal; pub use off::Off; pub use quiet::Quiet; pub use silent::Silent; pub use sleep::Sleep; pub use wakeup::{WakeUp, WakeUpStateError}; #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub enum State { Normal, LightLoop, WakeUp, Sleep, Silent, Quiet, Off, } pub trait RoomState { fn update( &mut self, mods: &mut Modifications, system: &mut System, env: &mut Environment, ) -> Result<Option<State>, Error>; fn breakdown(&self, mods: &mut Modifications, system: &mut System) -> Result<(), Error>; fn state(&self) -> State; }
mod ffi { use libc::{c_void, size_t}; #[allow(non_camel_case_types)] type XXH32_hash_t = u32; #[allow(non_camel_case_types)] type XXH64_hash_t = u64; extern "C" { pub fn XXH32(input: *const c_void, length: size_t, seed: u32) -> XXH32_hash_t; pub fn XXH64(input: *const c_void, length: size_t, seed: u64) -> XXH64_hash_t; } } pub fn hash32(data: &[u8], seed: u32) -> u32 { unsafe { ffi::XXH32(data.as_ptr() as *const libc::c_void, data.len(), seed) } } pub fn hash64(data: &[u8], seed: u64) -> u64 { unsafe { ffi::XXH64(data.as_ptr() as *const libc::c_void, data.len(), seed) } }
use druid::{kurbo::Affine, PaintCtx}; use druid::{Data, Point, RenderContext, Size, Vec2}; use crate::plane::{PlaneIndex, Planes}; use crate::{image_utils, plane::Plane}; use crate::{Paintable, Selection}; use anyhow::Result; use std::sync::Arc; #[derive(Debug, Data, Clone)] enum SelectionBinder { Unbind(Selection), Bind(Selection, PlaneIndex), } // FIXME: Change name to Layer #[derive(Debug, Data, Clone)] pub struct CanvasData { path: Arc<std::path::PathBuf>, selection: Option<SelectionBinder>, planes: Planes, transform: Vec2, size: Size, } impl CanvasData { pub fn new(path: impl Into<std::path::PathBuf>, img: image::DynamicImage) -> CanvasData { let mut planes = Planes::new(); let size = img.paint_size().unwrap(); planes.push(Plane::Image(Arc::new(img))); CanvasData { selection: None, planes, path: Arc::new(path.into()), transform: Vec2::default(), size, } } pub fn path(&self) -> &std::path::Path { self.path.as_ref() } pub fn save(&mut self, path: &std::path::Path) -> Result<()> { let img = self.merged(); img.save(path)?; self.path = Arc::new(path.into()); Ok(()) } pub fn selection(&self) -> Option<&Selection> { match self.selection.as_ref()? { SelectionBinder::Unbind(it) => Some(it), SelectionBinder::Bind(it, _) => Some(it), } } pub fn merged(&self) -> Arc<image::DynamicImage> { if self.transform == Vec2::ZERO { let img = self.planes.merged().expect("There is at least plane in Canvas"); return img; } // Create partial image based on offset and size let output = image_utils::transparent_image(self.size.width as u32, self.size.height as u32); self.planes.merged_to(output, self.transform) } pub fn select(&mut self, sel: impl Into<Selection>) { let sel = sel.into(); if sel.area() == 0.0 { self.selection = None; } else { self.selection = Some(SelectionBinder::Unbind(sel)); } } pub(crate) fn paste(&mut self, img: Arc<image::DynamicImage>) { let idx = self.planes.push(Plane::Image(img)); // FIXME: we don't need to mov the pasted image if we are using layer. self.planes.move_with_index(idx, -self.transform); } //FIXME: should be move layer, when we implemented layer pub(crate) fn move_canvas(&mut self, offset: Vec2) { self.transform += offset; if let Some(selection) = &self.selection { match selection { SelectionBinder::Unbind(it) => { let sel = it.transform(offset); self.selection = Some(SelectionBinder::Unbind(sel)); } SelectionBinder::Bind(it, idx) => { let sel = it.transform(offset); self.selection = Some(SelectionBinder::Bind(sel, *idx)); } } } } pub(crate) fn draw_with_brush(&mut self, pos: &Vec<Vec2>) { self.planes.draw_with_brush(pos); } pub(crate) fn move_selection(&mut self, offset: Vec2) { if let Some(selection) = &self.selection { let (selection, index) = match selection { SelectionBinder::Unbind(it) => { // Bind the selection let sel = it.transform(-self.transform); (it, self.planes.bind_selection(&sel)) } SelectionBinder::Bind(it, index) => (it, *index), }; let sel = selection.transform(offset); self.planes.move_with_index(index, offset); self.selection = Some(SelectionBinder::Bind(sel, index)); } } pub fn position(&self) -> Point { self.transform.to_point() } } impl Paintable for CanvasData { fn paint(&self, paint_ctx: &mut PaintCtx) { paint_ctx.with_save(|ctx| { ctx.transform(Affine::translate(self.transform)); self.planes.paint(ctx); }); } fn paint_size(&self) -> Option<Size> { Some(self.size) } } #[cfg(test)] mod test { use super::*; use crate::image_utils::{colors::*, make_color_img}; use crate::test_utils::canvas_fixture; use image::GenericImageView; #[test] fn canvas_data_merged_should_works() { let mut canvas = canvas_fixture(16, 16, WHITE); let black = make_color_img(4, 4, BLACK); canvas.paste(Arc::new(black)); let merged = canvas.merged(); assert_eq!(merged.get_pixel(0, 0), BLACK); assert_eq!(merged.get_pixel(8, 8), WHITE); } #[test] fn canvas_data_merged_should_works_with_moved() { let mut canvas = canvas_fixture(16, 16, WHITE); canvas.move_canvas(Vec2::new(4.0, 4.0)); let black = make_color_img(4, 4, BLACK); canvas.paste(Arc::new(black)); let merged = canvas.merged(); assert_eq!(merged.get_pixel(0, 0), BLACK); assert_eq!(merged.get_pixel(8, 8), WHITE); assert_eq!(merged.get_pixel(0, 8), TRANSPARENT); assert_eq!(merged.get_pixel(8, 0), TRANSPARENT); } }
use std::borrow::Cow; use crate::grid::{ config::{ColoredConfig, SpannedConfig}, dimension::{Dimension, Estimate, SpannedGridDimension}, records::Records, }; /// CompleteDimension is a [`Dimension`] implementation for a [`Table`] /// /// [`Table`]: crate::Table #[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord, Clone)] pub struct CompleteDimension<'a> { width: Option<Cow<'a, [usize]>>, height: Option<Cow<'a, [usize]>>, } impl CompleteDimension<'_> { /// Checks whether is the dimensions is set. pub fn is_complete(&self) -> bool { self.width.is_some() && self.height.is_some() } /// Checks whether is nothing was set. pub fn is_empty(&self) -> bool { self.width.is_none() && self.height.is_none() } /// Set column widths. /// /// In general the method is only considered to be useful to a [`TableOption`]. /// /// BE CAREFUL WITH THIS METHOD as it supposed that the content is not bigger than the provided widths. /// /// [`TableOption`]: crate::settings::TableOption pub fn set_widths(&mut self, columns: Vec<usize>) -> bool { self.width = Some(Cow::Owned(columns)); true } /// Set rows heights. /// /// In general the method is only considered to be useful to a [`TableOption`]. /// /// BE CAREFUL WITH THIS METHOD as it supposed that the content is not bigger than the provided heights. /// /// [`TableOption`]: crate::settings::TableOption pub fn set_heights(&mut self, rows: Vec<usize>) -> bool { self.height = Some(Cow::Owned(rows)); true } /// Force width estimation. pub fn clear_width(&mut self) { self.width = None; } /// Force height estimation. pub fn clear_height(&mut self) { self.height = None; } /// Copies a reference from self. pub fn from_origin(&self) -> CompleteDimension<'_> { let width = self.width.as_deref().map(Cow::Borrowed); let height = self.height.as_deref().map(Cow::Borrowed); CompleteDimension { width, height } } } impl Dimension for CompleteDimension<'_> { fn get_width(&self, column: usize) -> usize { let width = self .width .as_ref() .expect("It must always be Some at this point"); width[column] } fn get_height(&self, row: usize) -> usize { let height = self .height .as_ref() .expect("It must always be Some at this point"); height[row] } } impl<R: Records> Estimate<R, SpannedConfig> for CompleteDimension<'_> { fn estimate(&mut self, records: R, cfg: &SpannedConfig) { match (self.width.is_some(), self.height.is_some()) { (true, true) => {} (true, false) => { self.height = Some(Cow::Owned(SpannedGridDimension::height(records, cfg))); } (false, true) => { self.width = Some(Cow::Owned(SpannedGridDimension::width(records, cfg))); } (false, false) => { let mut dims = SpannedGridDimension::default(); dims.estimate(records, cfg); let (width, height) = dims.get_values(); self.width = Some(Cow::Owned(width)); self.height = Some(Cow::Owned(height)); } } } } impl<R: Records> Estimate<R, ColoredConfig> for CompleteDimension<'_> { fn estimate(&mut self, records: R, cfg: &ColoredConfig) { match (self.width.is_some(), self.height.is_some()) { (true, true) => {} (true, false) => { self.height = Some(Cow::Owned(SpannedGridDimension::height(records, cfg))); } (false, true) => { self.width = Some(Cow::Owned(SpannedGridDimension::width(records, cfg))); } (false, false) => { let mut dims = SpannedGridDimension::default(); dims.estimate(records, cfg); let (width, height) = dims.get_values(); self.width = Some(Cow::Owned(width)); self.height = Some(Cow::Owned(height)); } } } }
extern crate time; use std::time::SystemTime; fn main() { let now = SystemTime::now(); let mut array: [bool; 1000000] = [true;1000000]; array[0] = false; array[1] = false; for x in 2..1000 { if array[x] { let mut temp: u64 = x as u64; temp = temp * (x as u64); let add: u64 = x as u64; while temp < 1000000 { array[temp as usize] = false; temp = temp + add; } } } let mut total = 0; for x in 0..1000000 { if array[x] { //println!("Prime: {}", x); let num = String::from(format!("{}",x)); let len = num.len(); let mut valid: bool = true; for y in 1..len { let front: String = format!("{}",&num[y..num.len()]); let back: String = format!("{}",&num[0..y]); let i: usize = format!("{}{}",front,back).parse().unwrap(); let is_prime: bool = array[i]; if !is_prime { valid = false; break; } } if valid { total = total + 1; } } } println!("Total: {}",total); match now.elapsed() { Ok(elapsed) => { let nanos = elapsed.subsec_nanos() as u64; println!("Time Taken: {}ms", (1000*1000*1000* elapsed.as_secs() + nanos)/(1000*1000)); } Err(e) => { println!("Error: {:?}", e); } } }
use crate::common::snitches::Messages; use common::async_trait::async_trait; use models::{server::UdpTuple, transport::TransportMsg}; use sip_server::{SipBuilder, SipManager, Transaction, Transport, CoreLayer}; use std::any::Any; use std::sync::{Arc, Weak}; use tokio::sync::Mutex; #[derive(Debug)] pub struct CoreSnitch { sip_manager: Weak<SipManager>, pub messages: Messages, } #[async_trait] impl CoreLayer for CoreSnitch { fn new(sip_manager: Weak<SipManager>) -> Self { Self { sip_manager: sip_manager.clone(), messages: Default::default(), } } async fn process_incoming_message(&self, msg: TransportMsg) { self.messages.push(msg).await; } async fn send(&self, msg: TransportMsg) { match self.sip_manager().transport.send(msg).await { Ok(_) => (), Err(err) => common::log::error!("failed to send message: {:?}", err), } } async fn run(&self) {} fn as_any(&self) -> &dyn Any { self } } impl CoreSnitch { fn sip_manager(&self) -> Arc<SipManager> { self.sip_manager.upgrade().expect("sip manager is missing!") } } #[derive(Debug)] pub struct CorePanic; #[async_trait] impl CoreLayer for CorePanic { fn new(sip_manager: Weak<SipManager>) -> Self { Self } async fn process_incoming_message(&self, msg: TransportMsg) { p!(self) } async fn send(&self, msg: TransportMsg) { p!(self) } async fn run(&self) {} fn as_any(&self) -> &dyn Any { self } }
#![deny( dead_code, nonstandard_style, unused_imports, unused_mut, unused_variables, unused_unsafe, unreachable_patterns )] #[macro_use] extern crate wasmer_runtime_core; // extern crate wasmer_emscripten; #[macro_use] pub mod update; pub mod utils; pub mod webassembly;
use crate::fft::*; use crate::Opt; use anyhow::Result; use rustfft::num_traits::Zero; use std::{fs::File, io::Read, path::PathBuf, slice}; use wgpu::util::DeviceExt; use winit::{event::*, window::Window}; #[repr(transparent)] #[derive(Copy, Clone)] struct PodComplex(FftSample); unsafe impl bytemuck::Zeroable for PodComplex {} /// Safety: Complex<f32> is a repr(C) struct of two f32, and has alignment 4. unsafe impl bytemuck::Pod for PodComplex {} // PodComplex is casted to vec2 and requires alignment 8 when sent to the GPU. // This is not a problem as long as the start position within the Buffer is aligned. type PodVec = Vec<PodComplex>; type PodSlice = [PodComplex]; fn fft_as_pod(my_slice: &FftSlice) -> &PodSlice { unsafe { std::slice::from_raw_parts(my_slice.as_ptr() as *const _, my_slice.len()) } } /// Sent to GPU. Controls FFT layout and options. #[repr(C)] #[derive(Copy, Clone)] struct GpuRenderParameters { /// Screen size. screen_wx: u32, screen_hy: u32, /// Samples per second. sample_rate: u32, /// Number of FFT bins between 0 and Nyquist inclusive. /// Equals nsamp/2 + 1. fft_out_size: u32, } unsafe impl bytemuck::Zeroable for GpuRenderParameters {} unsafe impl bytemuck::Pod for GpuRenderParameters {} /// The longest allowed FFT is ???. /// The real FFT produces ??? complex bins. fn fft_out_size(fft_input_size: usize) -> usize { fft_input_size / 2 + 1 } // Docs: https://sotrh.github.io/learn-wgpu/beginner/tutorial2-swapchain/ // Code: https://github.com/sotrh/learn-wgpu/blob/master/code/beginner/tutorial2-swapchain/src/main.rs // - https://github.com/sotrh/learn-wgpu/blob/3a46a215/code/beginner/tutorial2-swapchain/src/main.rs pub struct State { surface: wgpu::Surface, device: wgpu::Device, queue: wgpu::Queue, sc_desc: wgpu::SwapChainDescriptor, swap_chain: wgpu::SwapChain, size: winit::dpi::PhysicalSize<u32>, render_pipeline: wgpu::RenderPipeline, render_parameters: GpuRenderParameters, fft_vec: PodVec, render_parameters_buffer: wgpu::Buffer, fft_vec_buffer: wgpu::Buffer, bind_group: wgpu::BindGroup, } fn load_from_file(fname: &str) -> Result<String> { let mut buf: Vec<u8> = vec![]; File::open(PathBuf::from(fname))?.read_to_end(&mut buf)?; Ok(String::from_utf8(buf)?) } impl State { // Creating some of the wgpu types requires async code pub async fn new(window: &Window, opt: &Opt, sample_rate: u32) -> anyhow::Result<State> { let size = window.inner_size(); // The instance is a handle to our GPU // BackendBit::PRIMARY => Vulkan + Metal + DX12 + Browser WebGPU let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); let surface = unsafe { instance.create_surface(window) }; let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::Default, compatible_surface: Some(&surface), }) .await .unwrap(); let (device, queue) = adapter .request_device( &wgpu::DeviceDescriptor { features: wgpu::Features::empty(), limits: wgpu::Limits::default(), shader_validation: true, }, None, // Trace path ) .await .unwrap(); let sc_desc = wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: size.width, height: size.height, present_mode: wgpu::PresentMode::Fifo, // TODO change to Mailbox? }; let swap_chain = device.create_swap_chain(&surface, &sc_desc); let vs_src = load_from_file("shaders/shader.vert")?; let fs_src = load_from_file("shaders/shader.frag")?; let mut compiler = shaderc::Compiler::new().unwrap(); let vs_spirv = compiler.compile_into_spirv( &vs_src, shaderc::ShaderKind::Vertex, "shader.vert", "main", None, )?; let fs_spirv = compiler.compile_into_spirv( &fs_src, shaderc::ShaderKind::Fragment, "shader.frag", "main", None, )?; let vs_module = device.create_shader_module(wgpu::util::make_spirv(&vs_spirv.as_binary_u8())); let fs_module = device.create_shader_module(wgpu::util::make_spirv(&fs_spirv.as_binary_u8())); // # FFT SSBO let fft_out_size = fft_out_size(opt.fft_size); let render_parameters = GpuRenderParameters { screen_wx: size.width, screen_hy: size.height, fft_out_size: fft_out_size as u32, sample_rate, }; let fft_vec: PodVec = vec![PodComplex(FftSample::zero()); fft_out_size]; let render_param_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("FFT layout (size)"), contents: bytemuck::cast_slice(slice::from_ref(&render_parameters)), usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, }); let fft_vec_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("FFT data"), contents: bytemuck::cast_slice(&fft_vec), usage: wgpu::BufferUsage::STORAGE | wgpu::BufferUsage::COPY_DST, }); let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::UniformBuffer { dynamic: false, min_binding_size: None, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::StorageBuffer { dynamic: false, readonly: true, min_binding_size: None, }, count: None, }, ], label: Some("bind_group_layout"), }); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { layout: &bind_group_layout, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer(render_param_buffer.slice(..)), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Buffer(fft_vec_buffer.slice(..)), }, ], label: Some("bind_group"), }); // # Shader pipeline let render_pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Render Pipeline Layout"), bind_group_layouts: &[&bind_group_layout], push_constant_ranges: &[], }); let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Render Pipeline"), layout: Some(&render_pipeline_layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", // 1. }, fragment_stage: Some(wgpu::ProgrammableStageDescriptor { // 2. module: &fs_module, entry_point: "main", }), rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw, cull_mode: wgpu::CullMode::Back, clamp_depth: false, depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, }), color_states: &[wgpu::ColorStateDescriptor { format: sc_desc.format, color_blend: wgpu::BlendDescriptor::REPLACE, alpha_blend: wgpu::BlendDescriptor::REPLACE, write_mask: wgpu::ColorWrite::ALL, }], primitive_topology: wgpu::PrimitiveTopology::TriangleList, // 1. depth_stencil_state: None, // 2. vertex_state: wgpu::VertexStateDescriptor { index_format: wgpu::IndexFormat::Uint16, // 3. vertex_buffers: &[], // 4. }, sample_count: 1, // 5. sample_mask: !0, // 6. alpha_to_coverage_enabled: false, // 7. }); Ok(State { surface, device, queue, sc_desc, swap_chain, size, render_pipeline, render_parameters, fft_vec, render_parameters_buffer: render_param_buffer, fft_vec_buffer, bind_group, }) } pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) { self.size = new_size; self.sc_desc.width = new_size.width; self.sc_desc.height = new_size.height; self.swap_chain = self.device.create_swap_chain(&self.surface, &self.sc_desc); } pub fn input(&mut self, event: &WindowEvent) -> bool { false } pub fn update(&mut self, spectrum: &FftSlice) { self.render_parameters = GpuRenderParameters { screen_wx: self.size.width, screen_hy: self.size.height, ..self.render_parameters }; self.queue.write_buffer( &self.render_parameters_buffer, 0, bytemuck::cast_slice(slice::from_ref(&self.render_parameters)), ); self.fft_vec.copy_from_slice(fft_as_pod(spectrum)); self.queue .write_buffer(&self.fft_vec_buffer, 0, bytemuck::cast_slice(&self.fft_vec)); } pub fn render(&mut self) { let frame = self .swap_chain .get_current_frame() .expect("Timeout getting texture") .output; let mut encoder = self .device .create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Render Encoder"), }); { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: &frame.view, resolve_target: None, ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.0, g: 0.0, b: 0.0, a: 1.0, }), store: true, }, }], depth_stencil_attachment: None, }); render_pass.set_pipeline(&self.render_pipeline); // 2. render_pass.set_bind_group(0, &self.bind_group, &[]); render_pass.draw(0..6, 0..1); // 3. } // submit will accept anything that implements IntoIter self.queue.submit(std::iter::once(encoder.finish())); } }
use std::fmt; use lazy_static::lazy_static; use rand::Rng; use rand::XorShiftRng; use crate::args; use crate::pos::Pos; const NUM_SHAPES: usize = 7; const NUM_ROTATIONS: i8 = 4; /// A bag of shapes that is used to produce a random sequence of shapes in the game. /// /// The random sequence is designed to behave like a bag containing all seven shapes. Shapes are /// pulled from the bag one by one until the bag is empty, then all seven shapes are returned /// to the bag. /// /// The result is a random sequence that feels "natural", with an even distribution of pieces over /// time. #[derive(Clone)] pub struct Bag { shapes: [Shape; NUM_SHAPES], index: usize, rng: XorShiftRng, } impl fmt::Debug for Bag { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { f.debug_struct("Bag") .field("tetrominoes", &self.shapes) .field("index", &self.index) .field("rng", &"<rng>") .finish() } } impl Bag { /// Create a new bag with the given random number generator pub fn new(mut rng: XorShiftRng) -> Bag { Bag { shapes: Bag::random_sequence(&mut rng), index: 0, rng, } } /// Peek at the next shape without removing it. pub fn peek(&self) -> Shape { self.shapes[self.index] } /// Remove and return the next shape. pub fn pop(&mut self) -> Shape { let next = self.shapes[self.index]; self.index += 1; if self.index >= NUM_SHAPES { self.shapes = Bag::random_sequence(&mut self.rng); self.index = 0; } next } fn random_sequence<R: Rng>(rng: &mut R) -> [Shape; NUM_SHAPES] { let mut sequence = *SHAPES; // This is inlined from `Rng::shuffle`. // We do this so we can cast `i` into a `u8`, meaning the shuffle is reliable regardless // of differences in `usize`. // This allows us to replay a game on a different machine and get the same result. // This cast is safe because the sequence of shapes will definitely fit in a u8. let mut i = sequence.len() as u8; while i >= 2 { // invariant: elements with index >= i have been locked in place. i -= 1; // lock element i in place. sequence.swap(i as usize, rng.gen_range(0, i + 1) as usize); } sequence } } /// The 90-degree rotation of a shape, so can be one of four values. #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct Rotation(i8); impl Rotation { /// Rotate clockwise 90 degrees. pub fn clockwise(self) -> Rotation { Rotation(modulo(self.0 + 1, NUM_ROTATIONS)) } /// Rotate anti-clockwise 90 degrees. pub fn anticlockwise(self) -> Rotation { Rotation(modulo(self.0 - 1, NUM_ROTATIONS)) } } /// Calculates modulo. This is distinct from `%`, which calculates the remainder. fn modulo(x: i8, y: i8) -> i8 { ((x % y) + y) % y } /// The different tetromino colors, classified by shape. #[derive(PartialEq, Clone, Debug, Copy)] pub enum ShapeColor { /// The 'O' or 'square' shape. O, /// The 'I' shape. I, /// The 'J' shape. J, /// The 'L' shape. L, /// The 'S' shape. S, /// The 'T' shape. T, /// The 'Z' shape. Z, } /// A tetromino shape, described by its appearance at all rotations, plus its colour. #[derive(Debug, Copy, Clone, PartialEq)] pub struct Shape { /// The shape's appearance across all four rotations, stored in a u16. This is a compact /// binary 'bitfield' representation like so: /// ``` /// // _ _ _ _ /// // _ X _ _ /// // _ X _ _ /// // _ X X _ /// let l_shape = 0b_0000_0100_0100_0110; /// ``` rotations: [u16; 4], /// The colour of the shape. pub color: ShapeColor, } impl Shape { /// The maximum width of a shape. pub const WIDTH: u8 = 4; /// The maximum height of a shape. pub const HEIGHT: u8 = 4; /// Get all the blocks that comprise this shape with the given rotation. pub fn blocks(&self, rot: Rotation) -> Vec<Pos> { let mut blocks = Vec::new(); for index in 0..Shape::WIDTH * Shape::HEIGHT { // Look up `index` in `rotations` bit array if self.rotations[rot.0 as usize] & (1 << index) != 0 { let x = index % Shape::WIDTH; let y = index / Shape::WIDTH; blocks.push(Pos::new(i16::from(x), i16::from(y))); } } blocks } } /// Create a tetromino shape as a compact `u16` bit array. /// /// e.g. /// ``` /// tet!(_ _ _ _ /// _ X _ _ /// _ X _ _ /// _ X X _), /// ``` /// macro_rules! tet { (@b X) => { 1 }; (@b _) => { 0 }; ($_0:tt $_1:tt $_2:tt $_3:tt $_4:tt $_5:tt $_6:tt $_7:tt $_8:tt $_9:tt $_a:tt $_b:tt $_c:tt $_d:tt $_e:tt $_f:tt) => { tet!(@b $_0) << 0x0 | tet!(@b $_1) << 0x1 | tet!(@b $_2) << 0x2 | tet!(@b $_3) << 0x3 | tet!(@b $_4) << 0x4 | tet!(@b $_5) << 0x5 | tet!(@b $_6) << 0x6 | tet!(@b $_7) << 0x7 | tet!(@b $_8) << 0x8 | tet!(@b $_9) << 0x9 | tet!(@b $_a) << 0xa | tet!(@b $_b) << 0xb | tet!(@b $_c) << 0xc | tet!(@b $_d) << 0xd | tet!(@b $_e) << 0xe | tet!(@b $_f) << 0xf }; } lazy_static! { static ref SHAPES: [Shape; NUM_SHAPES] = { if args::evil_mode() { // MWAHAHAAAAAA let decoy_shape = Shape { rotations: [ tet!(_ _ _ _ X X X X _ _ _ _ _ _ _ _), tet!(_ _ X _ _ _ X _ _ _ X _ _ X X _), tet!(_ _ _ _ _ _ _ _ X X X X _ _ _ _), tet!(_ X _ _ _ X _ _ _ X _ _ _ X X _), ], color: ShapeColor::I, }; [S_SHAPE, S_SHAPE, S_SHAPE, Z_SHAPE, Z_SHAPE, Z_SHAPE, decoy_shape] } else { [O_SHAPE, I_SHAPE, J_SHAPE, L_SHAPE, S_SHAPE, T_SHAPE, Z_SHAPE] } }; } static O_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ _ X X _ _ X X _ _ _ _ _), tet!(_ _ _ _ _ X X _ _ X X _ _ _ _ _), tet!(_ _ _ _ _ X X _ _ X X _ _ _ _ _), tet!(_ _ _ _ _ X X _ _ X X _ _ _ _ _), ], color: ShapeColor::O, }; static I_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ X X X X _ _ _ _ _ _ _ _), tet!(_ _ X _ _ _ X _ _ _ X _ _ _ X _), tet!(_ _ _ _ _ _ _ _ X X X X _ _ _ _), tet!(_ X _ _ _ X _ _ _ X _ _ _ X _ _), ], color: ShapeColor::I, }; static J_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ X _ _ _ X X X _ _ _ _ _), tet!(_ _ _ _ _ X X _ _ X _ _ _ X _ _), tet!(_ _ _ _ _ _ _ _ X X X _ _ _ X _), tet!(_ _ _ _ _ X _ _ _ X _ _ X X _ _), ], color: ShapeColor::J, }; static L_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ _ _ X _ X X X _ _ _ _ _), tet!(_ _ _ _ _ X _ _ _ X _ _ _ X X _), tet!(_ _ _ _ _ _ _ _ X X X _ X _ _ _), tet!(_ _ _ _ X X _ _ _ X _ _ _ X _ _), ], color: ShapeColor::L, }; static S_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ _ X X _ X X _ _ _ _ _ _), tet!(_ X _ _ _ X X _ _ _ X _ _ _ _ _), tet!(_ X X _ X X _ _ _ _ _ _ _ _ _ _), tet!(_ X _ _ _ X X _ _ _ X _ _ _ _ _), ], color: ShapeColor::S, }; static T_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ _ X _ _ X X X _ _ _ _ _), tet!(_ _ _ _ _ X _ _ _ X X _ _ X _ _), tet!(_ _ _ _ _ _ _ _ X X X _ _ X _ _), tet!(_ _ _ _ _ X _ _ X X _ _ _ X _ _), ], color: ShapeColor::T, }; static Z_SHAPE: Shape = Shape { rotations: [ tet!(_ _ _ _ X X _ _ _ X X _ _ _ _ _), tet!(_ X _ _ X X _ _ X _ _ _ _ _ _ _), tet!(X X _ _ _ X X _ _ _ _ _ _ _ _ _), tet!(_ _ X _ _ X X _ _ X _ _ _ _ _ _), ], color: ShapeColor::Z, }; #[cfg(test)] mod tests { use quickcheck::{quickcheck, Arbitrary, Gen}; use super::*; impl Arbitrary for Bag { fn arbitrary<G: Gen>(g: &mut G) -> Bag { let size = g.size() as u32; let mut bag = Bag::new(rand::random()); for _ in 0..size { bag.pop(); } bag } } impl Arbitrary for Rotation { fn arbitrary<G: Gen>(g: &mut G) -> Rotation { if g.gen() { Rotation::default() } else if g.gen() { Rotation::arbitrary(g).clockwise() } else { Rotation::arbitrary(g).anticlockwise() } } } impl Arbitrary for &'static Shape { fn arbitrary<G: Gen>(g: &mut G) -> &'static Shape { g.choose(&*SHAPES).unwrap() } } impl Arbitrary for ShapeColor { fn arbitrary<G: Gen>(g: &mut G) -> ShapeColor { *g.choose(&[ ShapeColor::O, ShapeColor::I, ShapeColor::J, ShapeColor::L, ShapeColor::S, ShapeColor::T, ShapeColor::Z, ]) .unwrap() } } #[test] fn bag_always_returns_exact_result_for_same_seed() { let rng = XorShiftRng::new_unseeded(); let mut bag = Bag::new(rng); let mut vec = Vec::new(); for _ in 0..10 { vec.push(bag.pop().color); } assert_eq!( vec![ ShapeColor::J, ShapeColor::L, ShapeColor::S, ShapeColor::T, ShapeColor::Z, ShapeColor::O, ShapeColor::I, ShapeColor::Z, ShapeColor::L, ShapeColor::J, ], vec ); } quickcheck! { fn bag_always_returns_a_valid_shape(bag: Bag) -> bool { let mut bag = bag; let shape = bag.pop(); SHAPES.iter().any(|t| *t == shape) } fn bag_never_returns_same_shape_three_times(bag: Bag) -> bool { let mut bag = bag; let first = bag.pop(); let second = bag.pop(); let third = bag.pop(); !(first == second && second == third) } fn bag_always_returns_same_shape_within_thirteen_times(bag: Bag) -> bool { let mut bag = bag; let initial = bag.pop(); for _ in 0..13 { if bag.pop() == initial { return true; } } false } fn bag_always_gives_same_pieces_with_the_same_seed(x: u32, y: u32, z: u32, w: u32) -> bool { use rand::SeedableRng; let seed = [x, y, z, w]; let rng1 = XorShiftRng::from_seed(seed); let mut bag1 = Bag::new(rng1); let rng2 = XorShiftRng::from_seed(seed); let mut bag2 = Bag::new(rng2); for _ in 0..100 { if bag1.pop() != bag2.pop() { return false; } } return true; } fn peek_has_same_result_as_pop(bag: Bag) -> bool { let mut bag = bag; bag.peek() == bag.pop() } fn clockwise_rotation_once_is_different(rot: Rotation) -> bool { rot != rot.clockwise() } fn clockwise_rotation_twice_is_different(rot: Rotation) -> bool { rot != rot.clockwise().clockwise() } fn clockwise_rotation_thrice_is_different(rot: Rotation) -> bool { rot != rot.clockwise().clockwise().clockwise() } fn clockwise_rotation_four_times_is_identity(rot: Rotation) -> bool { rot == rot.clockwise().clockwise().clockwise().clockwise() } fn anticlockwise_rotation_four_times_is_identity(rot: Rotation) -> bool { rot == rot.anticlockwise().anticlockwise().anticlockwise().anticlockwise() } fn anticlockwise_is_inverse_of_clockwise(rot: Rotation) -> bool { rot.clockwise().anticlockwise() == rot } fn clockwise_is_inverse_of_anticlockwise(rot: Rotation) -> bool { rot.anticlockwise().clockwise() == rot } } }
use crate::config::Config; use crate::response_helpers; use crate::tweet::Tweet; use anyhow::{Context, Result}; use futures::stream::StreamExt; use itertools::Itertools; use reqwest::{header::*, Client, ClientBuilder}; use std::ffi::OsStr; use std::fs::File; use std::io::{prelude::*, BufReader}; use std::path::Path; use tokio::time::{sleep, Duration}; #[derive(Debug)] struct TwitterError { text: String, } impl std::fmt::Display for TwitterError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.text) } } impl std::error::Error for TwitterError {} impl TwitterError { fn new(text: &str) -> Self { Self { text: text.to_string(), } } } pub struct TwitterClient<'a> { client: Client, config: &'a Config, } impl<'a> TwitterClient<'a> { pub fn new(config: &'a Config) -> TwitterClient { let mut headers = HeaderMap::new(); headers.insert( AUTHORIZATION, format!("Bearer {}", &config.bearer).parse().unwrap(), ); let client = ClientBuilder::new() .default_headers(headers) .timeout(Duration::from_secs(30)) .build() .unwrap(); TwitterClient { client, config } } pub async fn process_ids_file( &self, path: impl AsRef<Path> + AsRef<OsStr>, ) -> Result<Vec<Tweet>> { let file = File::open(&path)?; let reader = BufReader::new(file); let ids: Vec<_> = reader .lines() .filter_map(|l| Some(l.ok()?.trim().to_string())) .collect(); self.process_ids(ids.iter().map(|s| s.as_ref())).await } pub async fn process_ids(&self, ids: impl Iterator<Item = &str>) -> Result<Vec<Tweet>> { let tweets = self.lookup(ids).await?; Ok(tweets) } async fn lookup(&self, tweet_ids: impl Iterator<Item = &str>) -> Result<Vec<Tweet>> { let chunks = tweet_ids.chunks(100); let mut all_tweets = vec![]; println!("Querying tweets..."); for chunk in chunks.into_iter() { let id: String = chunk.intersperse(",").collect(); let params = [ ("id", id.as_str()), ("include_entities", "true"), ("trim_user", "false"), ("tweet_mode", "extended"), ]; let resp = self .client .post("https://api.twitter.com/1.1/statuses/lookup.json") .form(&params) .send() .await?; if let Some(duration) = response_helpers::check_rate_limit(&resp) { eprintln!("Rate limit hit, sleeping for {:?}", duration); sleep(duration).await; continue; } let tweets: Vec<Tweet> = resp .json() .await .context("Failed to parse lookup endpoint JSON")?; all_tweets.extend(tweets); } Ok(all_tweets .into_iter() .unique_by(|t| t.id) .filter(|t| !t.retweeted_status) .collect()) } pub async fn process_users(&self, users: impl Iterator<Item = &str>) -> Result<Vec<Tweet>> { let results = futures::stream::iter(users.map(|u| self.process_user(u))) .buffer_unordered(20) .collect::<Vec<_>>() .await; let (ok, err): (Vec<_>, Vec<_>) = results.into_iter().partition(|r| r.is_ok()); if !err.is_empty() { for e in err { eprintln!("{:?}", e); } Err(TwitterError::new("Error processing users"))? } let tweets = ok.into_iter().flatten().flatten().collect(); Ok(tweets) } pub async fn process_user(&self, user: &str) -> Result<Vec<Tweet>> { let path = Path::new(&self.config.directory).join(user); let start = match std::fs::read_dir(path) { Err(_) => None, Ok(i) => i .filter_map(|n| { let max_id = n .ok()? .file_name() .to_str()? .to_string() .split('_') .skip(1) .next()? .parse::<u64>() .ok()?; Some(max_id) }) .max(), }; let tweets = self.user_timeline(user, start).await?; Ok(tweets) } pub async fn user_timeline( &self, screen_name: &str, since_id: Option<u64>, ) -> Result<Vec<Tweet>> { let mut params_base = vec![ ("screen_name", screen_name.to_owned()), ("count", "200".to_string()), ("include_rts", "true".to_string()), ("exclude_replies", "false".to_string()), ("include_entities", "true".to_string()), ("trim_user", "false".to_string()), ("tweet_mode", "extended".to_string()), ]; if let Some(id) = since_id { params_base.push(("since_id", id.to_string())); } let mut all_tweets = vec![]; let mut max_id: Option<u64> = None; println!("Retrieving {}...", &screen_name); loop { // Query Twitter API let mut params = params_base.clone(); if let Some(id) = max_id { params.push(("max_id", id.to_string())); } let resp = self .client .get("https://api.twitter.com/1.1/statuses/user_timeline.json") .form(&params) .send() .await?; if let Some(duration) = response_helpers::check_rate_limit(&resp) { eprintln!("Rate limit hit, sleeping for {:?}", duration); sleep(duration).await; continue; } // Exit loop if no more tweets let tweets: Vec<Tweet> = resp .json() .await .context("Failed to parse user_timeline endpoint JSON")?; if tweets.is_empty() { break; } // Update max_id for next iteration let min_id = tweets.iter().min().unwrap().id; if let Some(max_id) = max_id { if min_id == max_id { break; } } if let Some(since_id) = since_id { if since_id >= min_id { break; } } max_id = Some(min_id - 1); // Append new tweets all_tweets.extend(tweets); } Ok(all_tweets .into_iter() .unique_by(|t| t.id) .filter(|t| t.user.screen_name.to_lowercase() == screen_name.to_lowercase()) .filter(|t| !t.retweeted_status) .collect()) } }
//! # Simple "config" example //! //! This example will create a default config if none is found (in `test_config` directory), //! or read existing one and will print it out as a JSON //! extern crate serde_fs; #[macro_use] extern crate serde_derive; extern crate serde_bytes; extern crate serde_json; #[derive(Serialize, Deserialize, Default)] struct Config { name: String, values: Vec<u8>, #[serde(with = "serde_bytes")] file: Vec<u8>, } fn main() { use std::env; let config_dir = env::current_dir().unwrap().join("test_config"); let maybe_cfg: Option<Config> = serde_fs::from_fs(&config_dir).unwrap(); if maybe_cfg.is_none() { eprintln!("Config not found, creating one. You can edit it and re-run the example"); serde_fs::to_fs(&config_dir, &Config::default()).unwrap(); } let cfg: Config = serde_fs::from_fs(&config_dir).unwrap(); println!("{}", serde_json::to_string_pretty(&cfg).unwrap()); }
use std::{env, fs}; type Input = Vec<Vec<char>>; fn main() { let args: Vec<String> = env::args().collect(); if args.get(1).is_none() { panic!("Supply a file to run against"); } let content = fs::read_to_string(args.get(1).unwrap()).expect("Reading file went wrong"); let lines: Vec<&str> = content.lines().collect(); let chars = lines .iter() .map(|line| line.chars().collect::<Vec<char>>()) .collect(); part1(&chars); part2(&chars); } fn look_for_chars(chars: &Vec<char>, amount: usize) -> usize { for i in amount..chars.len() { let mut found = true; let slice = &chars[i - amount..i]; for char in slice.iter() { if slice.iter().filter(|c| c == &char).count() > 1 { found = false; break; } } if found { return i; } } 0 } fn part1(n: &Input) { for line in n { println!("Part 1: {}", look_for_chars(line, 4)); } } fn part2(n: &Input) { for line in n { println!("Part 2: {}", look_for_chars(line, 14)); } }
use crate::{ codegen::{builder::core, AatbeModule, ValueTypePair}, ty::{Aggregate, LLVMTyInCtx, TypeError, TypeResult}, }; use llvm_sys_wrapper::{LLVMTypeRef, LLVMValueRef}; use parser::ast::PrimitiveType; use std::{collections::HashMap, fmt}; pub struct VariantType { pub type_name: String, pub variants: HashMap<String, Variant>, pub discriminant_type: PrimitiveType, pub ty: LLVMTypeRef, } impl VariantType { pub fn push_variant(&mut self, name: &String, variant: Variant) { self.variants.insert(name.clone(), variant); } } impl LLVMTyInCtx for VariantType { fn llvm_ty_in_ctx(&self, _: &AatbeModule) -> LLVMTypeRef { self.ty } } #[derive(Debug)] pub struct Variant { pub parent_name: String, pub name: String, pub types: Option<Vec<PrimitiveType>>, pub ty: LLVMTypeRef, pub discriminant: u32, } impl LLVMTyInCtx for Variant { fn llvm_ty_in_ctx(&self, _: &AatbeModule) -> LLVMTypeRef { self.ty } } impl VariantType { pub fn get_variant(&self, name: &String) -> Option<&Variant> { self.variants.get(name) } pub fn has_variant(&self, name: &String) -> bool { self.variants.contains_key(name) } } impl Aggregate for Variant { fn gep_indexed_field( &self, module: &AatbeModule, index: u32, aggregate_ref: LLVMValueRef, ) -> TypeResult<ValueTypePair> { match &self.types { None => Err(TypeError::VariantOOB(self.name.clone(), index)), Some(types) if types.len() < index as usize => { Err(TypeError::VariantOOB(self.name.clone(), index)) } Some(types) => Ok(( core::struct_gep(module, aggregate_ref, index + 1), types[index as usize].clone(), ) .into()), } } fn gep_named_field( &self, _module: &AatbeModule, name: &String, _aggregate_ref: LLVMValueRef, ) -> TypeResult<ValueTypePair> { Err(TypeError::NamedOnVariant(self.name.clone(), name.clone())) } } impl fmt::Debug for VariantType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "VariantType {{ type_name: {:?}, variants: {}, ty: {:?} }}", self.type_name, format!( "{{ {} }}", self.variants .iter() .map(|(k, v)| format!("{}: {:?}", k, v)) .collect::<Vec<_>>() .join(", ") ), self.ty ) } }
use std::path::PathBuf; use serde::{Deserialize, Serialize}; use structopt::StructOpt; use tokio::fs; use persist_core::error::Error; use persist_core::protocol::{ProcessSpec, RestoreRequest}; use crate::daemon; use crate::format; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, StructOpt)] pub struct Opts { /// The path of the file to restore processes from #[structopt(short, long, default_value = "persist-dump.json")] pub from: PathBuf, /// Restore all processes #[structopt(long)] pub all: bool, /// The names of the processes to restore #[structopt(name = "process-name")] pub processes: Vec<String>, } pub async fn handle(opts: Opts) -> Result<(), Error> { let filters = match (opts.all, opts.processes) { (false, processes) if processes.is_empty() => { return Err(Error::from(String::from( "you must specify at least one process name or --all", ))); } (false, processes) => Some(processes), (true, _) => None, }; let contents = fs::read(opts.from).await?; let specs: Vec<ProcessSpec> = json::from_slice(contents.as_slice())?; let specs = if let Some(filters) = filters { specs .into_iter() .filter(|spec| filters.contains(&spec.name)) .collect() } else { specs }; let request = RestoreRequest { specs }; let mut daemon = daemon::connect().await?; let responses = daemon.restore(request).await?; for response in responses { if let Some(error) = response.error { let msg = format!( "process '{}' could not be restored: {}", response.name, error ); format::error(msg); } else { let msg = format!("process '{}' successfully restored.", response.name); format::success(msg); } } Ok(()) }
#[doc = "Register `COMP_CFGR1` reader"] pub type R = crate::R<COMP_CFGR1_SPEC>; #[doc = "Register `COMP_CFGR1` writer"] pub type W = crate::W<COMP_CFGR1_SPEC>; #[doc = "Field `EN` reader - COMP Channel1 enable This bit is set and cleared by software (only if LOCK not set). It enables the COMP�Channel1."] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - COMP Channel1 enable This bit is set and cleared by software (only if LOCK not set). It enables the COMP�Channel1."] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BRGEN` reader - Scaler bridge enable This bit is set and cleared by software (only if LOCK not set). This bit enables the bridge of the scaler. If SCALEN is set and BRGEN is reset, all four scaler outputs provide the same level V&lt;sub>REF_COMP&lt;/sub> (similar to V&lt;sub>REFINT&lt;/sub>). If SCALEN and BRGEN are set, the four scaler outputs provide V&lt;sub>REF_COMP&lt;/sub>, 3/4�V&lt;sub>REF_COMP&lt;/sub>, 1/2�V&lt;sub>REF_COMP&lt;/sub> and 1/4�V&lt;sub>REF_COMP&lt;/sub> levels, respectively."] pub type BRGEN_R = crate::BitReader; #[doc = "Field `BRGEN` writer - Scaler bridge enable This bit is set and cleared by software (only if LOCK not set). This bit enables the bridge of the scaler. If SCALEN is set and BRGEN is reset, all four scaler outputs provide the same level V&lt;sub>REF_COMP&lt;/sub> (similar to V&lt;sub>REFINT&lt;/sub>). If SCALEN and BRGEN are set, the four scaler outputs provide V&lt;sub>REF_COMP&lt;/sub>, 3/4�V&lt;sub>REF_COMP&lt;/sub>, 1/2�V&lt;sub>REF_COMP&lt;/sub> and 1/4�V&lt;sub>REF_COMP&lt;/sub> levels, respectively."] pub type BRGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SCALEN` reader - Voltage scaler enable This bit is set and cleared by software (only if LOCK not set). This bit enables the V&lt;sub>REFINT&lt;/sub> scaler for the COMP channels."] pub type SCALEN_R = crate::BitReader; #[doc = "Field `SCALEN` writer - Voltage scaler enable This bit is set and cleared by software (only if LOCK not set). This bit enables the V&lt;sub>REFINT&lt;/sub> scaler for the COMP channels."] pub type SCALEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `POLARITY` reader - COMP channel1 polarity selection This bit is set and cleared by software (only if LOCK not set). It inverts COMP channel1 polarity."] pub type POLARITY_R = crate::BitReader; #[doc = "Field `POLARITY` writer - COMP channel1 polarity selection This bit is set and cleared by software (only if LOCK not set). It inverts COMP channel1 polarity."] pub type POLARITY_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITEN` reader - COMP channel1 interrupt enable This bit is set and cleared by software (only if LOCK not set). This bit enable the interrupt generation of the COMP channel1."] pub type ITEN_R = crate::BitReader; #[doc = "Field `ITEN` writer - COMP channel1 interrupt enable This bit is set and cleared by software (only if LOCK not set). This bit enable the interrupt generation of the COMP channel1."] pub type ITEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HYST` reader - COMP channel1 hysteresis selection These bits are set and cleared by software (only if LOCK not set). They select the hysteresis voltage of the COMP channel1."] pub type HYST_R = crate::FieldReader; #[doc = "Field `HYST` writer - COMP channel1 hysteresis selection These bits are set and cleared by software (only if LOCK not set). They select the hysteresis voltage of the COMP channel1."] pub type HYST_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PWRMODE` reader - Power mode of the COMP channel1 These bits are set and cleared by software (only if LOCK not set). They control the power/speed of the COMP channel1."] pub type PWRMODE_R = crate::FieldReader; #[doc = "Field `PWRMODE` writer - Power mode of the COMP channel1 These bits are set and cleared by software (only if LOCK not set). They control the power/speed of the COMP channel1."] pub type PWRMODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `INMSEL` reader - COMP channel1 inverting input selection These bits are set and cleared by software (only if LOCK not set). They select which input is connected to the input minus of the COMP channel. Note: See Table�146: COMP1 inverting input assignment for more details."] pub type INMSEL_R = crate::FieldReader; #[doc = "Field `INMSEL` writer - COMP channel1 inverting input selection These bits are set and cleared by software (only if LOCK not set). They select which input is connected to the input minus of the COMP channel. Note: See Table�146: COMP1 inverting input assignment for more details."] pub type INMSEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `INPSEL1` reader - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of COMP channel. Note: See Table�145: COMP1 noninverting input assignment for more details."] pub type INPSEL1_R = crate::BitReader; #[doc = "Field `INPSEL1` writer - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of COMP channel. Note: See Table�145: COMP1 noninverting input assignment for more details."] pub type INPSEL1_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `INPSEL2` reader - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of the COMP channel. See Table�145: COMP1 noninverting input assignment for more details."] pub type INPSEL2_R = crate::BitReader; #[doc = "Field `INPSEL2` writer - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of the COMP channel. See Table�145: COMP1 noninverting input assignment for more details."] pub type INPSEL2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BLANKING` reader - COMP Channel1 blanking source selection Bits of this field are set and cleared by software (only if LOCK not set). The field selects the input source for COMP Channel1 output blanking: All other values: reserved"] pub type BLANKING_R = crate::FieldReader; #[doc = "Field `BLANKING` writer - COMP Channel1 blanking source selection Bits of this field are set and cleared by software (only if LOCK not set). The field selects the input source for COMP Channel1 output blanking: All other values: reserved"] pub type BLANKING_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `LOCK` reader - Lock This bit is set by software and cleared by a hardware system reset. It locks the whole content of the COMP Channel1 configuration register COMP_CFGR1\\[31:0\\]"] pub type LOCK_R = crate::BitReader; #[doc = "Field `LOCK` writer - Lock This bit is set by software and cleared by a hardware system reset. It locks the whole content of the COMP Channel1 configuration register COMP_CFGR1\\[31:0\\]"] pub type LOCK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - COMP Channel1 enable This bit is set and cleared by software (only if LOCK not set). It enables the COMP�Channel1."] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Scaler bridge enable This bit is set and cleared by software (only if LOCK not set). This bit enables the bridge of the scaler. If SCALEN is set and BRGEN is reset, all four scaler outputs provide the same level V&lt;sub>REF_COMP&lt;/sub> (similar to V&lt;sub>REFINT&lt;/sub>). If SCALEN and BRGEN are set, the four scaler outputs provide V&lt;sub>REF_COMP&lt;/sub>, 3/4�V&lt;sub>REF_COMP&lt;/sub>, 1/2�V&lt;sub>REF_COMP&lt;/sub> and 1/4�V&lt;sub>REF_COMP&lt;/sub> levels, respectively."] #[inline(always)] pub fn brgen(&self) -> BRGEN_R { BRGEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Voltage scaler enable This bit is set and cleared by software (only if LOCK not set). This bit enables the V&lt;sub>REFINT&lt;/sub> scaler for the COMP channels."] #[inline(always)] pub fn scalen(&self) -> SCALEN_R { SCALEN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - COMP channel1 polarity selection This bit is set and cleared by software (only if LOCK not set). It inverts COMP channel1 polarity."] #[inline(always)] pub fn polarity(&self) -> POLARITY_R { POLARITY_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 6 - COMP channel1 interrupt enable This bit is set and cleared by software (only if LOCK not set). This bit enable the interrupt generation of the COMP channel1."] #[inline(always)] pub fn iten(&self) -> ITEN_R { ITEN_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bits 8:9 - COMP channel1 hysteresis selection These bits are set and cleared by software (only if LOCK not set). They select the hysteresis voltage of the COMP channel1."] #[inline(always)] pub fn hyst(&self) -> HYST_R { HYST_R::new(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 12:13 - Power mode of the COMP channel1 These bits are set and cleared by software (only if LOCK not set). They control the power/speed of the COMP channel1."] #[inline(always)] pub fn pwrmode(&self) -> PWRMODE_R { PWRMODE_R::new(((self.bits >> 12) & 3) as u8) } #[doc = "Bits 16:19 - COMP channel1 inverting input selection These bits are set and cleared by software (only if LOCK not set). They select which input is connected to the input minus of the COMP channel. Note: See Table�146: COMP1 inverting input assignment for more details."] #[inline(always)] pub fn inmsel(&self) -> INMSEL_R { INMSEL_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bit 20 - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of COMP channel. Note: See Table�145: COMP1 noninverting input assignment for more details."] #[inline(always)] pub fn inpsel1(&self) -> INPSEL1_R { INPSEL1_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 22 - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of the COMP channel. See Table�145: COMP1 noninverting input assignment for more details."] #[inline(always)] pub fn inpsel2(&self) -> INPSEL2_R { INPSEL2_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bits 24:27 - COMP Channel1 blanking source selection Bits of this field are set and cleared by software (only if LOCK not set). The field selects the input source for COMP Channel1 output blanking: All other values: reserved"] #[inline(always)] pub fn blanking(&self) -> BLANKING_R { BLANKING_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bit 31 - Lock This bit is set by software and cleared by a hardware system reset. It locks the whole content of the COMP Channel1 configuration register COMP_CFGR1\\[31:0\\]"] #[inline(always)] pub fn lock(&self) -> LOCK_R { LOCK_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bit 0 - COMP Channel1 enable This bit is set and cleared by software (only if LOCK not set). It enables the COMP�Channel1."] #[inline(always)] #[must_use] pub fn en(&mut self) -> EN_W<COMP_CFGR1_SPEC, 0> { EN_W::new(self) } #[doc = "Bit 1 - Scaler bridge enable This bit is set and cleared by software (only if LOCK not set). This bit enables the bridge of the scaler. If SCALEN is set and BRGEN is reset, all four scaler outputs provide the same level V&lt;sub>REF_COMP&lt;/sub> (similar to V&lt;sub>REFINT&lt;/sub>). If SCALEN and BRGEN are set, the four scaler outputs provide V&lt;sub>REF_COMP&lt;/sub>, 3/4�V&lt;sub>REF_COMP&lt;/sub>, 1/2�V&lt;sub>REF_COMP&lt;/sub> and 1/4�V&lt;sub>REF_COMP&lt;/sub> levels, respectively."] #[inline(always)] #[must_use] pub fn brgen(&mut self) -> BRGEN_W<COMP_CFGR1_SPEC, 1> { BRGEN_W::new(self) } #[doc = "Bit 2 - Voltage scaler enable This bit is set and cleared by software (only if LOCK not set). This bit enables the V&lt;sub>REFINT&lt;/sub> scaler for the COMP channels."] #[inline(always)] #[must_use] pub fn scalen(&mut self) -> SCALEN_W<COMP_CFGR1_SPEC, 2> { SCALEN_W::new(self) } #[doc = "Bit 3 - COMP channel1 polarity selection This bit is set and cleared by software (only if LOCK not set). It inverts COMP channel1 polarity."] #[inline(always)] #[must_use] pub fn polarity(&mut self) -> POLARITY_W<COMP_CFGR1_SPEC, 3> { POLARITY_W::new(self) } #[doc = "Bit 6 - COMP channel1 interrupt enable This bit is set and cleared by software (only if LOCK not set). This bit enable the interrupt generation of the COMP channel1."] #[inline(always)] #[must_use] pub fn iten(&mut self) -> ITEN_W<COMP_CFGR1_SPEC, 6> { ITEN_W::new(self) } #[doc = "Bits 8:9 - COMP channel1 hysteresis selection These bits are set and cleared by software (only if LOCK not set). They select the hysteresis voltage of the COMP channel1."] #[inline(always)] #[must_use] pub fn hyst(&mut self) -> HYST_W<COMP_CFGR1_SPEC, 8> { HYST_W::new(self) } #[doc = "Bits 12:13 - Power mode of the COMP channel1 These bits are set and cleared by software (only if LOCK not set). They control the power/speed of the COMP channel1."] #[inline(always)] #[must_use] pub fn pwrmode(&mut self) -> PWRMODE_W<COMP_CFGR1_SPEC, 12> { PWRMODE_W::new(self) } #[doc = "Bits 16:19 - COMP channel1 inverting input selection These bits are set and cleared by software (only if LOCK not set). They select which input is connected to the input minus of the COMP channel. Note: See Table�146: COMP1 inverting input assignment for more details."] #[inline(always)] #[must_use] pub fn inmsel(&mut self) -> INMSEL_W<COMP_CFGR1_SPEC, 16> { INMSEL_W::new(self) } #[doc = "Bit 20 - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of COMP channel. Note: See Table�145: COMP1 noninverting input assignment for more details."] #[inline(always)] #[must_use] pub fn inpsel1(&mut self) -> INPSEL1_W<COMP_CFGR1_SPEC, 20> { INPSEL1_W::new(self) } #[doc = "Bit 22 - COMP noninverting input selection This bit is set and cleared by software (only if LOCK not set). They select which input is connected to the positive input of the COMP channel. See Table�145: COMP1 noninverting input assignment for more details."] #[inline(always)] #[must_use] pub fn inpsel2(&mut self) -> INPSEL2_W<COMP_CFGR1_SPEC, 22> { INPSEL2_W::new(self) } #[doc = "Bits 24:27 - COMP Channel1 blanking source selection Bits of this field are set and cleared by software (only if LOCK not set). The field selects the input source for COMP Channel1 output blanking: All other values: reserved"] #[inline(always)] #[must_use] pub fn blanking(&mut self) -> BLANKING_W<COMP_CFGR1_SPEC, 24> { BLANKING_W::new(self) } #[doc = "Bit 31 - Lock This bit is set by software and cleared by a hardware system reset. It locks the whole content of the COMP Channel1 configuration register COMP_CFGR1\\[31:0\\]"] #[inline(always)] #[must_use] pub fn lock(&mut self) -> LOCK_W<COMP_CFGR1_SPEC, 31> { LOCK_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 = "Comparator configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`comp_cfgr1::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 [`comp_cfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct COMP_CFGR1_SPEC; impl crate::RegisterSpec for COMP_CFGR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`comp_cfgr1::R`](R) reader structure"] impl crate::Readable for COMP_CFGR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`comp_cfgr1::W`](W) writer structure"] impl crate::Writable for COMP_CFGR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets COMP_CFGR1 to value 0"] impl crate::Resettable for COMP_CFGR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `CCMR2_Input` reader"] pub type R = crate::R<CCMR2_INPUT_SPEC>; #[doc = "Register `CCMR2_Input` writer"] pub type W = crate::W<CCMR2_INPUT_SPEC>; #[doc = "Field `CC3S` reader - Capture/compare 3 selection"] pub type CC3S_R = crate::FieldReader<CC3S_A>; #[doc = "Capture/compare 3 selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum CC3S_A { #[doc = "1: CC3 channel is configured as input, IC3 is mapped on TI3"] Ti3 = 1, #[doc = "2: CC3 channel is configured as input, IC3 is mapped on TI4"] Ti4 = 2, #[doc = "3: CC3 channel is configured as input, IC3 is mapped on TRC"] Trc = 3, } impl From<CC3S_A> for u8 { #[inline(always)] fn from(variant: CC3S_A) -> Self { variant as _ } } impl crate::FieldSpec for CC3S_A { type Ux = u8; } impl CC3S_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<CC3S_A> { match self.bits { 1 => Some(CC3S_A::Ti3), 2 => Some(CC3S_A::Ti4), 3 => Some(CC3S_A::Trc), _ => None, } } #[doc = "CC3 channel is configured as input, IC3 is mapped on TI3"] #[inline(always)] pub fn is_ti3(&self) -> bool { *self == CC3S_A::Ti3 } #[doc = "CC3 channel is configured as input, IC3 is mapped on TI4"] #[inline(always)] pub fn is_ti4(&self) -> bool { *self == CC3S_A::Ti4 } #[doc = "CC3 channel is configured as input, IC3 is mapped on TRC"] #[inline(always)] pub fn is_trc(&self) -> bool { *self == CC3S_A::Trc } } #[doc = "Field `CC3S` writer - Capture/compare 3 selection"] pub type CC3S_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, CC3S_A>; impl<'a, REG, const O: u8> CC3S_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "CC3 channel is configured as input, IC3 is mapped on TI3"] #[inline(always)] pub fn ti3(self) -> &'a mut crate::W<REG> { self.variant(CC3S_A::Ti3) } #[doc = "CC3 channel is configured as input, IC3 is mapped on TI4"] #[inline(always)] pub fn ti4(self) -> &'a mut crate::W<REG> { self.variant(CC3S_A::Ti4) } #[doc = "CC3 channel is configured as input, IC3 is mapped on TRC"] #[inline(always)] pub fn trc(self) -> &'a mut crate::W<REG> { self.variant(CC3S_A::Trc) } } #[doc = "Field `IC3PSC` reader - Input capture 3 prescaler"] pub type IC3PSC_R = crate::FieldReader; #[doc = "Field `IC3PSC` writer - Input capture 3 prescaler"] pub type IC3PSC_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O>; #[doc = "Field `IC3F` reader - Input capture 3 filter"] pub type IC3F_R = crate::FieldReader; #[doc = "Field `IC3F` writer - Input capture 3 filter"] pub type IC3F_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>; #[doc = "Field `CC4S` reader - Capture/Compare 4 selection"] pub type CC4S_R = crate::FieldReader<CC4S_A>; #[doc = "Capture/Compare 4 selection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum CC4S_A { #[doc = "1: CC4 channel is configured as input, IC4 is mapped on TI4"] Ti4 = 1, #[doc = "2: CC4 channel is configured as input, IC4 is mapped on TI3"] Ti3 = 2, #[doc = "3: CC4 channel is configured as input, IC4 is mapped on TRC"] Trc = 3, } impl From<CC4S_A> for u8 { #[inline(always)] fn from(variant: CC4S_A) -> Self { variant as _ } } impl crate::FieldSpec for CC4S_A { type Ux = u8; } impl CC4S_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<CC4S_A> { match self.bits { 1 => Some(CC4S_A::Ti4), 2 => Some(CC4S_A::Ti3), 3 => Some(CC4S_A::Trc), _ => None, } } #[doc = "CC4 channel is configured as input, IC4 is mapped on TI4"] #[inline(always)] pub fn is_ti4(&self) -> bool { *self == CC4S_A::Ti4 } #[doc = "CC4 channel is configured as input, IC4 is mapped on TI3"] #[inline(always)] pub fn is_ti3(&self) -> bool { *self == CC4S_A::Ti3 } #[doc = "CC4 channel is configured as input, IC4 is mapped on TRC"] #[inline(always)] pub fn is_trc(&self) -> bool { *self == CC4S_A::Trc } } #[doc = "Field `CC4S` writer - Capture/Compare 4 selection"] pub type CC4S_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, CC4S_A>; impl<'a, REG, const O: u8> CC4S_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "CC4 channel is configured as input, IC4 is mapped on TI4"] #[inline(always)] pub fn ti4(self) -> &'a mut crate::W<REG> { self.variant(CC4S_A::Ti4) } #[doc = "CC4 channel is configured as input, IC4 is mapped on TI3"] #[inline(always)] pub fn ti3(self) -> &'a mut crate::W<REG> { self.variant(CC4S_A::Ti3) } #[doc = "CC4 channel is configured as input, IC4 is mapped on TRC"] #[inline(always)] pub fn trc(self) -> &'a mut crate::W<REG> { self.variant(CC4S_A::Trc) } } #[doc = "Field `IC4PSC` reader - Input capture 4 prescaler"] pub type IC4PSC_R = crate::FieldReader; #[doc = "Field `IC4PSC` writer - Input capture 4 prescaler"] pub type IC4PSC_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 2, O>; #[doc = "Field `IC4F` reader - Input capture 4 filter"] pub type IC4F_R = crate::FieldReader; #[doc = "Field `IC4F` writer - Input capture 4 filter"] pub type IC4F_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>; impl R { #[doc = "Bits 0:1 - Capture/compare 3 selection"] #[inline(always)] pub fn cc3s(&self) -> CC3S_R { CC3S_R::new((self.bits & 3) as u8) } #[doc = "Bits 2:3 - Input capture 3 prescaler"] #[inline(always)] pub fn ic3psc(&self) -> IC3PSC_R { IC3PSC_R::new(((self.bits >> 2) & 3) as u8) } #[doc = "Bits 4:7 - Input capture 3 filter"] #[inline(always)] pub fn ic3f(&self) -> IC3F_R { IC3F_R::new(((self.bits >> 4) & 0x0f) as u8) } #[doc = "Bits 8:9 - Capture/Compare 4 selection"] #[inline(always)] pub fn cc4s(&self) -> CC4S_R { CC4S_R::new(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 10:11 - Input capture 4 prescaler"] #[inline(always)] pub fn ic4psc(&self) -> IC4PSC_R { IC4PSC_R::new(((self.bits >> 10) & 3) as u8) } #[doc = "Bits 12:15 - Input capture 4 filter"] #[inline(always)] pub fn ic4f(&self) -> IC4F_R { IC4F_R::new(((self.bits >> 12) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:1 - Capture/compare 3 selection"] #[inline(always)] #[must_use] pub fn cc3s(&mut self) -> CC3S_W<CCMR2_INPUT_SPEC, 0> { CC3S_W::new(self) } #[doc = "Bits 2:3 - Input capture 3 prescaler"] #[inline(always)] #[must_use] pub fn ic3psc(&mut self) -> IC3PSC_W<CCMR2_INPUT_SPEC, 2> { IC3PSC_W::new(self) } #[doc = "Bits 4:7 - Input capture 3 filter"] #[inline(always)] #[must_use] pub fn ic3f(&mut self) -> IC3F_W<CCMR2_INPUT_SPEC, 4> { IC3F_W::new(self) } #[doc = "Bits 8:9 - Capture/Compare 4 selection"] #[inline(always)] #[must_use] pub fn cc4s(&mut self) -> CC4S_W<CCMR2_INPUT_SPEC, 8> { CC4S_W::new(self) } #[doc = "Bits 10:11 - Input capture 4 prescaler"] #[inline(always)] #[must_use] pub fn ic4psc(&mut self) -> IC4PSC_W<CCMR2_INPUT_SPEC, 10> { IC4PSC_W::new(self) } #[doc = "Bits 12:15 - Input capture 4 filter"] #[inline(always)] #[must_use] pub fn ic4f(&mut self) -> IC4F_W<CCMR2_INPUT_SPEC, 12> { IC4F_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 = "capture/compare mode register 2 (input mode)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccmr2_input::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 [`ccmr2_input::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CCMR2_INPUT_SPEC; impl crate::RegisterSpec for CCMR2_INPUT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ccmr2_input::R`](R) reader structure"] impl crate::Readable for CCMR2_INPUT_SPEC {} #[doc = "`write(|w| ..)` method takes [`ccmr2_input::W`](W) writer structure"] impl crate::Writable for CCMR2_INPUT_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CCMR2_Input to value 0"] impl crate::Resettable for CCMR2_INPUT_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::fs::File; use std::fs::OpenOptions; use std::io::Write; use clap::{ArgMatches, value_t}; use itertools::Itertools; use rand_distr::uniform::Uniform; use scoped_threadpool::Pool; use super::{ Agent, BinomialBandit, EpsilonGreedyAgent, Game, GreedyAgent, HarmonicStepper, multiple_runs, OptimisticAgent, random_init, }; fn make_file_name(arg: &ArgMatches) -> String { if arg.is_present("pair_greedy") { String::from("results2/pair/greedy.csv") } else if arg.is_present("pair_epsilon") { let epsilon = value_t!(arg.value_of("pair_epsilon"), f64).unwrap_or_else(|e| e.exit()); format!("results2/pair/epsilon_e{}.csv", epsilon) } else if arg.is_present("pair_optimistic") { let c = value_t!(arg.value_of("pair_optimistic"), f64).unwrap_or_else(|e| e.exit()); format!("results2/pair/optimistic_c{}.csv", c) } else { String::from("bad_file.csv") } } pub fn pool_bernoulli(runs: u32, iterations: u32, agent_start: &[f64], arg: &ArgMatches) { let file_name = make_file_name(arg); let mut file = File::create(&file_name).unwrap(); let first_line = "left,right,start,iteration,wins,rewards"; file.write_all(first_line.as_bytes()).unwrap(); let reward_vec: Vec<f64> = (1..=99).map(|x| f64::from(x) / 100.0).collect(); //let rand_start = Uniform::new(agent_start - 1e-7, agent_start + 1e-7); let pair_vec = reward_vec .iter() .cartesian_product(&reward_vec) .filter(|(&x, &y)| x < y) .map(|(&x, &y)| (x, y)) .collect::<Vec<(f64, f64)>>(); let agent_vec = pair_vec .iter() .cartesian_product(agent_start) .map(|(&(x, y), &s)| (x, y, s)) .collect::<Vec<(f64, f64, f64)>>(); let mut pool = Pool::new(12); pool.scoped(|scope| { agent_vec.iter().for_each(|(left, right, start)| { scope.execute(move || { pair_bernoulli(runs, iterations, left, right, start, arg); }) }) }) } fn pair_bernoulli( runs: u32, iterations: u32, left: &f64, right: &f64, start: &f64, arg: &ArgMatches, ) { let rand_start = Uniform::new(start - 1e-7, start + 1e-7); let q_init = random_init(&rand_start, 2); let mut stepper = HarmonicStepper::new(1, 2); let ones = vec![1; 2]; let pair = vec![*left, *right]; let bandit = BinomialBandit::new(&ones, &pair); let mut agent: Box<dyn Agent<u32>> = if arg.is_present("pair_greedy") { Box::new(GreedyAgent::new(q_init, &mut stepper)) } else if arg.is_present("pair_epsilon") { let epsilon = value_t!(arg.value_of("pair_epsilon"), f64).unwrap_or_else(|e| e.exit()); Box::new(EpsilonGreedyAgent::new(q_init, &mut stepper, epsilon)) } else if arg.is_present("pair_optimistic") { let c = value_t!(arg.value_of("pair_optimistic"), f64).unwrap_or_else(|e| e.exit()); Box::new(OptimisticAgent::new(q_init, c, &mut stepper)) } else { Box::new(GreedyAgent::new(q_init, &mut stepper)) }; let mut game = Game::new(&mut *agent, &bandit); let file_name = make_file_name(arg); let mut file = OpenOptions::new().append(true).open(file_name).unwrap(); multiple_runs( &mut game, &pair, start, runs, iterations, &rand_start, &mut file, ) }
use clap::Clap; use crate::gpu::utils::get_system_gpus; #[derive(Clap)] #[clap(version = "1.0", author = "José M. Sarasola <alosarjos@gmail.com>")] pub struct Config { /// GPU card ID from /sys/class/drm/ #[clap(short, long, default_value = " ")] pub gpu_card_sys_path: String, /// Listening port for the API Rest server #[clap(short, long, default_value = "8080")] pub server_port: u16, } pub fn get_run_config() -> Config { let mut config: Config = Config::parse(); if config.gpu_card_sys_path.trim().is_empty() { println!("No GPU path was provided, attempting to find GPU..."); if let Some(system_gpus) = get_system_gpus() { let first_detected_gpu = system_gpus.first().unwrap(); println!( "Found GPU: {} at {}", first_detected_gpu.name, first_detected_gpu.file_path.to_str().unwrap() ); config.gpu_card_sys_path = first_detected_gpu.file_path.to_str().unwrap().to_string(); } else { panic!("No GPU was found on the system"); } } config }
/*! This crate is where extra tests which don't belong in examples go. */ use version_compatibility_interface::{RootMod,RootModVal}; use abi_stable::{ export_root_module, prefix_type::PrefixTypeTrait, sabi_types::VersionStrings, }; use std::marker::PhantomData; /////////////////////////////////////////////////////////////////////////////////// #[export_root_module] pub fn get_library() -> &'static RootMod { RootModVal{ _marker:PhantomData, abi_stable_version:abi_stable::ABI_STABLE_VERSION, }.leak_into_prefix() }
use crate::error::*; use crate::scope::Scope; use crate::value::Value; pub fn scope(call_scope: Scope, _: Value) -> ScriptResult<Value> { Ok(Value::Object( call_scope .values_recurse() .map(|(key, value)| (key.to_string(), value.clone())) .collect(), )) } pub fn local_scope(call_scope: Scope, _: Value) -> ScriptResult<Value> { Ok(Value::Object( call_scope .values() .map(|(key, value)| (key.to_string(), value.clone())) .collect(), )) } pub fn pipe(call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { rhs.invoke(call_scope, lhs) } pub fn add(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Ok(match (&lhs, &rhs) { (Value::Number(x), Value::Number(y)) => Value::Number(x + y), _ => { return Err(script_error!( "cannot add values of types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } }) } pub fn sub(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Ok(match (&lhs, &rhs) { (Value::Number(x), Value::Number(y)) => Value::Number(x - y), // TODO: checked _ => { return Err(script_error!( "cannot subtract values of types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } }) } pub fn mul(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Ok(match (&lhs, &rhs) { (Value::Number(x), Value::Number(y)) => Value::Number(x * y), // TODO: checked _ => { return Err(script_error!( "cannot multiply values of types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } }) } pub fn div(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Ok(match (&lhs, &rhs) { (Value::Number(x), Value::Number(y)) => Value::Number(x / y), // TODO: checked _ => { return Err(script_error!( "cannot divide values of types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } }) } pub fn eq(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } pub fn ne(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } pub fn ge(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } pub fn le(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } pub fn gt(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) } pub fn lt(_call_scope: Scope, lhs: Value, rhs: Value) -> ScriptResult<Value> { Err(script_error!( "comparison not implement for types: {:?}, {:?}", lhs.value_type(), rhs.value_type() )) }
use mlua::MetaMethod; use pulldown_cmark::Event; use crate::lua_tag::LuaTag; #[derive(Debug, Clone, PartialEq)] pub enum LuaEventKind { Markdown(Event<'static>), ContentStart, ContentEnd, } /// Wrapper around [`pulldown_cmark::Event`] implementing [`mlua::UserData`] #[derive(Debug, Clone, PartialEq)] pub struct LuaEvent(pub LuaEventKind); impl<'a> From<Event<'a>> for LuaEvent { fn from(ev: Event<'a>) -> Self { Self(LuaEventKind::Markdown(match ev { Event::Start(tag) => Event::Start(LuaTag::from(tag).into()), Event::End(tag) => Event::End(LuaTag::from(tag).into()), Event::Text(text) => Event::Text(text.to_string().into()), Event::Code(code) => Event::Code(code.to_string().into()), Event::Html(html) => Event::Html(html.to_string().into()), Event::FootnoteReference(fref) => Event::FootnoteReference(fref.to_string().into()), Event::SoftBreak => Event::SoftBreak, Event::HardBreak => Event::HardBreak, Event::Rule => Event::Rule, Event::TaskListMarker(set) => Event::TaskListMarker(set), })) } } impl From<LuaEvent> for Option<Event<'static>> { fn from(this: LuaEvent) -> Self { match this.0 { LuaEventKind::Markdown(event) => Some(event), LuaEventKind::ContentStart | LuaEventKind::ContentEnd => None, } } } impl mlua::UserData for LuaEvent { fn add_methods<'lua, M: mlua::UserDataMethods<'lua, Self>>(methods: &mut M) { methods.add_meta_method(MetaMethod::Eq, |_, this, other: LuaEvent| -> mlua::Result<bool> { Ok(this == &other) }); impl_lua_is!(methods => { is_start_tag: LuaEventKind::Markdown(Event::Start(_)), is_end_tag: LuaEventKind::Markdown(Event::End(_)), is_text: LuaEventKind::Markdown(Event::Text(_)), is_code: LuaEventKind::Markdown(Event::Code(_)), is_html: LuaEventKind::Markdown(Event::Html(_)), is_footnote_reference: LuaEventKind::Markdown(Event::FootnoteReference(_)), is_soft_break: LuaEventKind::Markdown(Event::SoftBreak), is_hard_break: LuaEventKind::Markdown(Event::HardBreak), is_rule: LuaEventKind::Markdown(Event::Rule), is_task_list_marker: LuaEventKind::Markdown(Event::TaskListMarker(_)), is_content_start: LuaEventKind::ContentStart, is_content_end: LuaEventKind::ContentEnd, }); impl_lua_unwrap_str!(methods => { as_text: inner = Event::Text | LuaEvent(LuaEventKind::Markdown(inner)), as_code: inner = Event::Code | LuaEvent(LuaEventKind::Markdown(inner)), as_html: inner = Event::Html | LuaEvent(LuaEventKind::Markdown(inner)), as_footnote_reference: inner = Event::FootnoteReference | LuaEvent(LuaEventKind::Markdown(inner)), }); methods.add_method("as_task_list_marker", |_, this, ()| -> mlua::Result<Option<bool>> { if let LuaEventKind::Markdown(Event::TaskListMarker(checked)) = &this.0 { Ok(Some(*checked)) } else { Ok(None) } }); methods.add_method("as_start_tag", |_, this, ()| -> mlua::Result<Option<LuaTag>> { if let LuaEventKind::Markdown(Event::Start(tag)) = &this.0 { Ok(Some(tag.clone().into())) } else { Ok(None) } }); methods.add_method("as_end_tag", |_, this, ()| -> mlua::Result<Option<LuaTag>> { if let LuaEventKind::Markdown(Event::End(tag)) = &this.0 { Ok(Some(tag.clone().into())) } else { Ok(None) } }); } }
use crate::bin_u64; #[cfg(target_arch = "x86")] use ::core::arch::x86::*; #[cfg(target_arch = "x86_64")] use ::core::arch::x86_64::*; /// Bitmask selecting bits on even positions when indexing from zero. pub(crate) const ODD: u64 = 0b0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_0101_u64; /// Bitmask selecting bits on odd positions when indexing from zero. pub(crate) const EVEN: u64 = 0b1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_1010_u64; #[target_feature(enable = "sse2")] unsafe fn all_ones128() -> __m128i { _mm_set1_epi8(0xFF_u8 as i8) } pub(crate) struct BlockClassifier64Bit { /// Compressed information about the state from the previous block. /// The first bit is lit iff the previous block ended with an unescaped escape character. /// The second bit is lit iff the previous block ended with a starting quote, /// meaning that it was not escaped, nor was it the closing quote of a quoted sequence. prev_block_mask: u8, } impl BlockClassifier64Bit { pub(crate) fn new() -> Self { Self { prev_block_mask: 0 } } /// Set the inter-block state based on slash overflow and the quotes mask. fn update_prev_block_mask(&mut self, set_slash_mask: bool, quotes: u64) { let slash_mask = u8::from(set_slash_mask); let quote_mask = (((quotes & (1 << 63)) >> 62) as u8) & 0x02; self.prev_block_mask = slash_mask | quote_mask; } /// Flip the inter-block state bit representing the quote state. pub(crate) fn flip_prev_quote_mask(&mut self) { self.prev_block_mask ^= 0x02; } /// Returns 0x01 if the last character of the previous block was an unescaped escape character, /// zero otherwise. fn get_prev_slash_mask(&self) -> u64 { u64::from(self.prev_block_mask & 0x01) } /// Returns 0x01 if the last character of the previous block was an unescaped quote, zero otherwise. fn get_prev_quote_mask(&self) -> u64 { u64::from((self.prev_block_mask & 0x02) >> 1) } #[target_feature(enable = "sse2")] #[target_feature(enable = "pclmulqdq")] pub(crate) unsafe fn classify(&mut self, slashes: u64, quotes: u64) -> u64 { let (escaped, set_prev_slash_mask) = if slashes == 0 { (self.get_prev_slash_mask(), false) } else { let slashes_excluding_escaped_first = slashes & !self.get_prev_slash_mask(); let starts = slashes_excluding_escaped_first & !(slashes_excluding_escaped_first << 1); let odd_starts = ODD & starts; let even_starts = EVEN & starts; let odd_starts_carry = odd_starts.wrapping_add(slashes); let (even_starts_carry, set_prev_slash_mask) = even_starts.overflowing_add(slashes); let ends_of_odd_starts = odd_starts_carry & !slashes; let ends_of_even_starts = even_starts_carry & !slashes; let escaped = (ends_of_odd_starts & EVEN) | (ends_of_even_starts & ODD) | self.get_prev_slash_mask(); (escaped, set_prev_slash_mask) }; let nonescaped_quotes = (quotes & !escaped) ^ self.get_prev_quote_mask(); let nonescaped_quotes_vector = _mm_set_epi64x(0, nonescaped_quotes as i64); let cumulative_xor = _mm_clmulepi64_si128::<0>(nonescaped_quotes_vector, all_ones128()); let within_quotes = _mm_cvtsi128_si64(cumulative_xor) as u64; self.update_prev_block_mask(set_prev_slash_mask, within_quotes); bin_u64!("slashes", slashes); bin_u64!("quotes", quotes); bin_u64!("prev_slash_bit", self.get_prev_slash_mask()); bin_u64!("prev_quote_bit", self.get_prev_quote_mask()); bin_u64!("escaped", escaped); bin_u64!("quotes & !escaped", quotes & !escaped); bin_u64!("nonescaped_quotes", nonescaped_quotes); bin_u64!("within_quotes", within_quotes); within_quotes } }
mod alternative; mod argument; mod arithmetic_operation; mod arithmetic_operator; mod calling_convention; mod case; mod comparison_operation; mod comparison_operator; mod declaration; mod definition; mod expression; mod foreign_declaration; mod foreign_definition; mod function_application; mod if_; mod let_; mod let_recursive; mod module; mod primitive; mod record; mod record_element; mod string; mod type_definition; mod variable; mod variant; pub use alternative::*; pub use argument::*; pub use arithmetic_operation::*; pub use arithmetic_operator::*; pub use calling_convention::*; pub use case::*; pub use comparison_operation::*; pub use comparison_operator::*; pub use declaration::*; pub use definition::*; pub use expression::*; pub use foreign_declaration::*; pub use foreign_definition::*; pub use function_application::*; pub use if_::*; pub use let_::*; pub use let_recursive::*; pub use module::*; pub use primitive::*; pub use record::*; pub use record_element::*; pub use string::*; pub use type_definition::*; pub use variable::*; pub use variant::*;
//! //! # String helpers //! /// Convert string in UpperCammelCase to senteces pub fn upper_cammel_case_to_sentence(src: String, remove_first: bool) -> String { // convert "ThisIsATest" to "this is a test" let mut letters: Vec<_> = vec![]; for c in src.chars() { if c.is_uppercase() { if !letters.is_empty() { letters.push(' '); } if let Some(lowercase) = c.to_lowercase().to_string().chars().next() { letters.push(lowercase); } } else { letters.push(c); } } let sentence: String = letters.into_iter().collect(); // remove first word "this is a test" to "is a test" if remove_first { let mut words: Vec<_> = sentence.split_whitespace().collect(); words.drain(0..1); words.join(" ") } else { sentence } } // // Unit Tests // #[cfg(test)] pub mod test { use super::*; #[test] fn test_upper_cammel_case_to_sentence() { assert_eq!( upper_cammel_case_to_sentence("ThisIsATest".to_owned(), false), "this is a test" ); assert_eq!( upper_cammel_case_to_sentence("ThisIsATest".to_owned(), true), "is a test" ); assert_eq!( upper_cammel_case_to_sentence("TopicAlreadyExists".to_owned(), true), "already exists" ); assert_eq!( upper_cammel_case_to_sentence("UnknownTopicOrPartition".to_owned(), false), "unknown topic or partition" ); } }
// BSD 2-Clause License // Copyright (c) 2019, Dimitris Spyropoulos // All rights reserved. // 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. // 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. extern crate time; use mylib::MyBloomFilter; use std::time::Instant; use std::fs::File; use std::io::{BufRead, BufReader, Result}; // Main function as a proof of concept. // The file bloom_input_10m.txt contains 10 million different numbers to be inserted in the bloom filter. // The file bloom_test_10m.txt contains again 10 million different numbers (inside the set and compared to first file). Existence of // those numbers is checked in the bloom filter. // The program prints the time taken to insert 10 million numbers to the bloom filter and the number of errors while checking the bloom filter. // In order to increase the speed, iterators were used over the file Buffers fn main() -> Result<()> { let now = Instant::now(); let mut bloom = MyBloomFilter::create(10000000 as u64,0.00001 as f64); let file = File::open("./input/bloom_input_10m.txt").expect("error in opening bloom_input file"); let mut hash: u64 = 0 as u64; BufReader::new(file).lines().for_each(|line| { match line{ Err(why) => panic!("{:?}", why), Ok(string) => hash = string.parse::<u64>().unwrap() } bloom.insert_bloom(hash); }); println!("{} milliseconds took to insert 10 000 000 hashes to bloom filters.",now.elapsed().as_millis()); let mut counter = 0; //counts the errcors let file2 = File::open("./input/bloom_test_10m.txt").expect("error in opening bloom test file"); BufReader::new(file2).lines().for_each(|line| { match line{ Err(why) => panic!("{:?}", why), Ok(string) => { hash = string.parse::<u64>().unwrap(); match bloom.check_bloom(hash as u64){ true => counter = counter + 1 , false => () } } } }); println!("Errors are {}",counter); Ok(()) }
use crossbeam_channel::{select, Receiver}; use death_rs::death::{Death, Life}; use error::Error; use log::error; use log::info; use rand::Rng; use signal_hook::{SIGINT, SIGTERM}; use simple_logger::SimpleLogger; use std::thread::sleep; use std::time::Duration; use std::{error, process::exit}; fn main() { SimpleLogger::new().init().unwrap(); let mut d: Death = match Death::new( // pass the signals to death you want to catch &[SIGINT, SIGTERM], // pass the timeout to wait for the workers to gracefully stop Duration::from_millis(800), ) { Ok(d) => d, Err(e) => panic!("Error creating death: {}", e), }; // Create n workers and register them with death. // This will spin them up in their own threads. for i in 0..10 { let worker = Worker::new(i); d.give_life(worker); } // block the main thread waiting for a signal. // wait_for_death will return a list of all the errors // propagated back from the children (and a timeout if they didn't close // fast enough). let errors = d.wait_for_death(); errors.iter().for_each(|e| error!("{}", e)); if errors.len() as i32 > 0 { exit(1) } } #[derive(thiserror::Error, Debug)] enum MyError { #[error("my error")] Err, } #[derive(Debug)] struct Worker { id: i32, } impl Worker { fn new(i: i32) -> Worker { Worker { id: i } } } impl Life for Worker { fn run(&mut self, done: Receiver<()>) -> Result<(), Box<dyn Error + Send + Sync>> { info!("Running {}", self.id); loop { select! { recv(done) -> _ => { let mut rng = rand::thread_rng(); let timeout = rng.gen_range(0, 1000); sleep(Duration::from_millis(timeout)); info!("shut down {} with {} delay", self.id, timeout); return Err(MyError::Err.into()); } } } } }
#[macro_use] extern crate vst; extern crate vst_gui; use crate::vst::host::Host; use vst::buffer::AudioBuffer; use vst::editor::Editor; use vst::plugin::HostCallback; use vst::plugin::{Category, Info, Plugin, PluginParameters}; use vst::util::ParameterTransfer; use std::sync::Arc; fn inline_script(s: &str) -> String { format!(r#"<script type="text/javascript">{}</script>"#, s) } fn inline_style(s: &str) -> String { format!(r#"<style type="text/css">{}</style>"#, s) } fn get_html() -> String { format!( r#" <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <style> @import url('https://fonts.googleapis.com/css2?family=Baloo+Tammudu+2:wght@500&display=swap'); </style> </head> <body scroll="no"> <div id="app"></div> <!--[if lt IE 9]> <div class="ie-upgrade-container"> <p class="ie-upgrade-message">Please, upgrade Internet Explorer to continue using this software.</p> <a class="ie-upgrade-link" target="_blank" href="https://www.microsoft.com/en-us/download/internet-explorer.aspx">Upgrade</a> </div> <![endif]--> <!--[if gte IE 9 | !IE ]> <!--> {scripts} <![endif]--> {style} </body> </html> "#, style = inline_style(include_str!("style.css")), scripts = inline_script(include_str!("bundle.js")) ) } #[derive(Default)] struct SimpleGain { params: Arc<SimpleGainParameter>, gui: SimpleGainGUI, } #[derive(Default)] struct SimpleGainParameter { transfer: ParameterTransfer, } #[derive(Default)] struct SimpleGainGUI { params: Arc<SimpleGainParameter>, #[allow(dead_code)] host: HostCallback, } impl SimpleGainGUI { fn new(params: Arc<SimpleGainParameter>, host: HostCallback) -> Self { Self { params: params, host: host, } } fn javascript_callback(&self) -> vst_gui::JavascriptCallback { let params = Arc::clone(&self.params); let host = self.host; Box::new(move |message: String| { let mut tokens = message.split_whitespace(); let command = tokens.next().unwrap_or(""); let argument = tokens.next().unwrap_or("").parse::<f32>(); match command { "getGain" => { return params.get_parameter_text(0); } "setGain" => { params.set_parameter(0, argument.unwrap()); host.automate(0, params.get_parameter(0)); } "mouseOverGain" => { host.begin_edit(0); } "releaseGain" => { host.end_edit(0); } _ => {} } String::new() }) } } impl PluginParameters for SimpleGainParameter { fn get_parameter_label(&self, index: i32) -> String { match index { 0 => "[-]".to_string(), _ => "".to_string(), } } fn get_parameter_name(&self, index: i32) -> String { match index { 0 => "gain".to_string(), _ => "".to_string(), } } fn get_parameter_text(&self, index: i32) -> String { match index { 0 => format!("{:.3}", self.transfer.get_parameter(index as usize)), _ => format!(""), } } fn get_parameter(&self, index: i32) -> f32 { self.transfer.get_parameter(index as usize) } fn set_parameter(&self, index: i32, value: f32) { self.transfer.set_parameter(index as usize, value); } fn can_be_automated(&self, index: i32) -> bool { match index { 0 => true, _ => false, } } } impl Plugin for SimpleGain { fn new(host: HostCallback) -> Self { let params = Arc::new(SimpleGainParameter { transfer: ParameterTransfer::new(1), }); let gui = SimpleGainGUI::new(params.clone(), host); Self { params: params, gui: gui, } } fn get_info(&self) -> Info { Info { name: "Simple Gain".to_string(), vendor: "Psykhedelic Mandala".to_string(), unique_id: 1337, category: Category::Effect, inputs: 2, outputs: 2, parameters: 1, ..Info::default() } } fn get_parameter_object(&mut self) -> Arc<dyn PluginParameters> { Arc::clone(&self.params) as Arc<dyn PluginParameters> } fn process(&mut self, buffer: &mut AudioBuffer<f32>) { let gain = self.params.get_parameter(0); let (inputs, outputs) = buffer.split(); let (l, r) = inputs.split_at(1); let stereo_in = l[0].iter().zip(r[0].iter()); let (mut l, mut r) = outputs.split_at_mut(1); let stereo_out = l[0].iter_mut().zip(r[0].iter_mut()); for ((left_in, right_in), (left_out, right_out)) in stereo_in.zip(stereo_out) { *left_out = *left_in * gain; *right_out = *right_in * gain; } } fn get_editor(&mut self) -> Option<Box<dyn Editor>> { let gui = vst_gui::new_plugin_gui( String::from(get_html()), self.gui.javascript_callback(), Some((500, 500)), ); Some(Box::new(gui)) } } plugin_main!(SimpleGain);
extern crate controller_rs; extern crate num_complex; extern crate pnet; extern crate serde_yaml; use pnet::datalink::interfaces; use pnet::datalink::{channel, Channel, ChannelType, Config}; use num_complex::Complex; use serde_yaml::{from_str, Value}; use std::env; use std::fs::File; use std::io::Read; use std::str; use controller_rs::board_cfg::BoardCfg; fn main() { let dev_name = env::args().nth(1).expect("Dev name not given"); let dev = interfaces() .into_iter() .filter(|x| x.name == dev_name) .nth(0) .expect("Cannot find dev"); let net_cfg = Config { write_buffer_size: 65536, read_buffer_size: 65536, read_timeout: None, write_timeout: None, channel_type: ChannelType::Layer2, bpf_fd_attempts: 1000, linux_fanout: None, }; let (mut tx, _) = if let Channel::Ethernet(tx, rx) = channel(&dev, net_cfg).expect("canot open channel") { (tx, rx) } else { panic!(); }; let mut phase_file = File::open(env::args().nth(3).expect("phase file not given")) .expect("phase file open failed"); let mut fparam = File::open(env::args().nth(2).unwrap()).unwrap(); let mut bytes = Vec::new(); fparam.read_to_end(&mut bytes).expect("Cannot read file"); let msg_str = str::from_utf8(&bytes).unwrap().to_string(); let param = from_str::<Value>(&msg_str).expect("Unable to read param"); let bc = BoardCfg::from_yaml(&param); let mut pf = vec![vec![vec![Complex::<i16>::new(0, 0); 2048]; 8]; 16]; for bid in 0..16 { for pid in 0..8 { let raw = unsafe { std::slice::from_raw_parts_mut(pf[bid][pid].as_mut_ptr() as *mut u8, 2048 * 4) }; match phase_file.read(raw) { Ok(s) if s == 2048 * 4 => {} _ => panic!("Error in read phase file"), } } } //pf[bid][pid] = vec![Complex::<i16>::new(16384, 0); 2048]; bc.update_phase_factor(&mut *tx, pf); //bc.send_internal_trig(&mut *tx); }
#![feature(format_args_capture)] use clap::{App, AppSettings, Arg}; use codespan_reporting::{ files::SimpleFile, term::{emit, termcolor::ColorChoice, Config}, }; use std::{error::Error, process::Command}; mod diagnostics; fn main() { match do_it() { Ok(()) => (), Err(err) => { eprintln!("{}", err); std::process::exit(1); } } } #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum Stage { Check, Build, Run, } fn do_it() -> Result<(), Box<dyn Error>> { let root = crate_root::root().unwrap(); let root = root.to_str().unwrap(); let builtins_path = format!("{root}/walrus_builtins.c"); let args = &[ Arg::new("FILE").required(true), Arg::new("color") .long("color") .value_name("COLOR") .takes_value(true) .possible_values(&["always", "never"]) .about("Emit colored diagnostics"), Arg::new("opt") .short('O') .long("opt") .value_name("OPT") .takes_value(true) .possible_values(&["0", "1", "2", "3"]) .default_value("0") .about("Optimization level"), Arg::new("verbose") .short('v') .long("verbose") .about("Use verbose output"), Arg::new("debug") .short('d') .long("debug") .about("Dump debug information after each pass"), ]; let matches = App::new("walrus") .setting(AppSettings::DeriveDisplayOrder) .setting(AppSettings::SubcommandRequiredElseHelp) .version("1.0") .author("Karl Meakin") .about("Compile Walrus programs") .subcommand( App::new("check") .about("Check the program for errors, but do not compile it") .args(args), ) .subcommand( App::new("build") .about("Compile the program into an executable, but do not run it") .args(args), ) .subcommand( App::new("run") .about("Compile and run the program") .args(args), ) .get_matches(); let (stage, matches) = match matches.subcommand() { Some(("check", matches)) => (Stage::Check, matches), Some(("build", matches)) => (Stage::Build, matches), Some(("run", matches)) => (Stage::Run, matches), _ => unreachable!(), }; let file = &matches.value_of("FILE").unwrap(); if !file.ends_with(".walrus") { return Err("Input filename should have `.walrus` extension".into()); } let file = std::fs::canonicalize(file)?; let file = file.to_str().unwrap(); let is_verbose = matches.is_present("verbose"); let is_debug = matches.is_present("debug"); let is_color = !matches!(matches.value_of("color"), Some("never")); let opt_level = matches.value_of("opt").unwrap(); let src = std::fs::read_to_string(file)?; let n_lines = src.lines().count(); let start_time = std::time::Instant::now(); let file_db = SimpleFile::new(file, &src); let syntax = walrus_parser::parse(&src); if is_debug { dbg!(&syntax); } let mut hir = walrus_semantics::hir::lower(&syntax); if is_debug { dbg!(&hir); } let mut scopes = walrus_semantics::scopes::scopes(&hir); if is_debug { dbg!(&scopes); } let mut types = walrus_semantics::ty::infer(hir.clone(), scopes.clone()); if is_debug { dbg!(&types); } let mut diagnostics = Vec::new(); diagnostics.extend(std::mem::take(&mut hir.diagnostics)); diagnostics.extend(std::mem::take(&mut scopes.diagnostics)); diagnostics.extend(std::mem::take(&mut types.diagnostics)); let mut writer = termcolor::StandardStream::stderr(if is_color { ColorChoice::Always } else { ColorChoice::Never }); let config = Config::default(); for diag in &diagnostics { let diag = diagnostics::render_diagnostic(&hir, diag); emit(&mut writer, &config, &file_db, &diag).expect("Could not emit diagnostic"); } let n_errors = diagnostics.iter().filter(|diag| diag.is_error()).count(); if n_errors > 0 { return Err(format!("Aborting compilation due to {n_errors} fatal errors").into()); } if is_verbose { let end_time = std::time::Instant::now(); let time = end_time.duration_since(start_time); println!("Checked {n_lines} lines in {time:?}"); } if stage < Stage::Build { return Ok(()); } let program_name = file.strip_suffix(".walrus").unwrap(); let llvm_ir_path = format!("{program_name}.ll"); let llvm_ir = walrus_codegen::codegen(program_name, hir.hir, scopes, types); std::fs::write(&llvm_ir_path, llvm_ir)?; let mut command = Command::new("clang"); if is_color { command.arg("-fcolor-diagnostics"); } command.args(&[ &format!("-O{opt_level}"), &builtins_path, &llvm_ir_path, "-o", program_name, ]); let output = command.output()?; if is_verbose { eprintln!("Running command: {:?}", command); } if !output.status.success() { eprintln!("Failed running command: {:?}", command); eprintln!("{}", String::from_utf8(output.stderr).unwrap()); } if is_verbose { let end_time = std::time::Instant::now(); let time = end_time.duration_since(start_time); println!("Compiled {n_lines} lines in {time:?}"); } if stage < Stage::Run { return Ok(()); } let mut program = Command::new(&program_name); if is_verbose { eprintln!("Running program: {:?}", program) } program.status()?; Ok(()) }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] CasesAggregations_Get(#[from] cases_aggregations::get::Error), #[error(transparent)] Operations_List(#[from] operations::list::Error), #[error(transparent)] AlertRules_List(#[from] alert_rules::list::Error), #[error(transparent)] AlertRules_Get(#[from] alert_rules::get::Error), #[error(transparent)] AlertRules_CreateOrUpdate(#[from] alert_rules::create_or_update::Error), #[error(transparent)] AlertRules_Delete(#[from] alert_rules::delete::Error), #[error(transparent)] Actions_ListByAlertRule(#[from] actions::list_by_alert_rule::Error), #[error(transparent)] Actions_Get(#[from] actions::get::Error), #[error(transparent)] Actions_CreateOrUpdate(#[from] actions::create_or_update::Error), #[error(transparent)] Actions_Delete(#[from] actions::delete::Error), #[error(transparent)] AlertRuleTemplates_List(#[from] alert_rule_templates::list::Error), #[error(transparent)] AlertRuleTemplates_Get(#[from] alert_rule_templates::get::Error), #[error(transparent)] DataConnectors_List(#[from] data_connectors::list::Error), #[error(transparent)] DataConnectors_Get(#[from] data_connectors::get::Error), #[error(transparent)] DataConnectors_CreateOrUpdate(#[from] data_connectors::create_or_update::Error), #[error(transparent)] DataConnectors_Delete(#[from] data_connectors::delete::Error), #[error(transparent)] ProductSettings_GetAll(#[from] product_settings::get_all::Error), #[error(transparent)] ProductSettings_Get(#[from] product_settings::get::Error), #[error(transparent)] ProductSettings_Update(#[from] product_settings::update::Error), #[error(transparent)] ProductSettings_Delete(#[from] product_settings::delete::Error), #[error(transparent)] EntityQueries_List(#[from] entity_queries::list::Error), #[error(transparent)] EntityQueries_Get(#[from] entity_queries::get::Error), #[error(transparent)] Incidents_List(#[from] incidents::list::Error), #[error(transparent)] Incidents_Get(#[from] incidents::get::Error), #[error(transparent)] Incidents_CreateOrUpdate(#[from] incidents::create_or_update::Error), #[error(transparent)] Incidents_Delete(#[from] incidents::delete::Error), #[error(transparent)] Incidents_ListOfAlerts(#[from] incidents::list_of_alerts::Error), #[error(transparent)] Incidents_ListOfBookmarks(#[from] incidents::list_of_bookmarks::Error), #[error(transparent)] IncidentComments_ListByIncident(#[from] incident_comments::list_by_incident::Error), #[error(transparent)] IncidentComments_GetComment(#[from] incident_comments::get_comment::Error), #[error(transparent)] IncidentComments_CreateComment(#[from] incident_comments::create_comment::Error), #[error(transparent)] IncidentComments_DeleteComment(#[from] incident_comments::delete_comment::Error), #[error(transparent)] Incidents_ListOfEntities(#[from] incidents::list_of_entities::Error), #[error(transparent)] IncidentRelations_List(#[from] incident_relations::list::Error), #[error(transparent)] IncidentRelations_GetRelation(#[from] incident_relations::get_relation::Error), #[error(transparent)] IncidentRelations_CreateOrUpdateRelation(#[from] incident_relations::create_or_update_relation::Error), #[error(transparent)] IncidentRelations_DeleteRelation(#[from] incident_relations::delete_relation::Error), #[error(transparent)] Watchlists_List(#[from] watchlists::list::Error), #[error(transparent)] Watchlists_Get(#[from] watchlists::get::Error), #[error(transparent)] Watchlists_Create(#[from] watchlists::create::Error), #[error(transparent)] Watchlists_Delete(#[from] watchlists::delete::Error), #[error(transparent)] WatchlistItems_List(#[from] watchlist_items::list::Error), #[error(transparent)] WatchlistItems_Get(#[from] watchlist_items::get::Error), #[error(transparent)] WatchlistItems_CreateOrUpdate(#[from] watchlist_items::create_or_update::Error), #[error(transparent)] WatchlistItems_Delete(#[from] watchlist_items::delete::Error), #[error(transparent)] AutomationRules_List(#[from] automation_rules::list::Error), #[error(transparent)] AutomationRules_Get(#[from] automation_rules::get::Error), #[error(transparent)] AutomationRules_CreateOrUpdate(#[from] automation_rules::create_or_update::Error), #[error(transparent)] AutomationRules_Delete(#[from] automation_rules::delete::Error), #[error(transparent)] Bookmarks_List(#[from] bookmarks::list::Error), #[error(transparent)] Bookmarks_Get(#[from] bookmarks::get::Error), #[error(transparent)] Bookmarks_CreateOrUpdate(#[from] bookmarks::create_or_update::Error), #[error(transparent)] Bookmarks_Delete(#[from] bookmarks::delete::Error), #[error(transparent)] BookmarkRelations_List(#[from] bookmark_relations::list::Error), #[error(transparent)] Bookmark_Expand(#[from] bookmark::expand::Error), #[error(transparent)] BookmarkRelations_GetRelation(#[from] bookmark_relations::get_relation::Error), #[error(transparent)] BookmarkRelations_CreateOrUpdateRelation(#[from] bookmark_relations::create_or_update_relation::Error), #[error(transparent)] BookmarkRelations_DeleteRelation(#[from] bookmark_relations::delete_relation::Error), #[error(transparent)] Cases_List(#[from] cases::list::Error), #[error(transparent)] Cases_Get(#[from] cases::get::Error), #[error(transparent)] Cases_CreateOrUpdate(#[from] cases::create_or_update::Error), #[error(transparent)] Cases_Delete(#[from] cases::delete::Error), #[error(transparent)] Comments_ListByCase(#[from] comments::list_by_case::Error), #[error(transparent)] Cases_GetComment(#[from] cases::get_comment::Error), #[error(transparent)] CaseComments_CreateComment(#[from] case_comments::create_comment::Error), #[error(transparent)] CaseRelations_List(#[from] case_relations::list::Error), #[error(transparent)] CaseRelations_GetRelation(#[from] case_relations::get_relation::Error), #[error(transparent)] CaseRelations_CreateOrUpdateRelation(#[from] case_relations::create_or_update_relation::Error), #[error(transparent)] CaseRelations_DeleteRelation(#[from] case_relations::delete_relation::Error), #[error(transparent)] DataConnectorsCheckRequirements_Post(#[from] data_connectors_check_requirements::post::Error), #[error(transparent)] IpGeodata_Get(#[from] ip_geodata::get::Error), #[error(transparent)] DomainWhois_Get(#[from] domain_whois::get::Error), #[error(transparent)] Entities_List(#[from] entities::list::Error), #[error(transparent)] Entities_Get(#[from] entities::get::Error), #[error(transparent)] Entities_Expand(#[from] entities::expand::Error), #[error(transparent)] EntitiesGetTimeline_List(#[from] entities_get_timeline::list::Error), #[error(transparent)] Entities_Queries(#[from] entities::queries::Error), #[error(transparent)] Entities_GetInsights(#[from] entities::get_insights::Error), #[error(transparent)] EntitiesRelations_List(#[from] entities_relations::list::Error), #[error(transparent)] EntityRelations_GetRelation(#[from] entity_relations::get_relation::Error), #[error(transparent)] OfficeConsents_List(#[from] office_consents::list::Error), #[error(transparent)] OfficeConsents_Get(#[from] office_consents::get::Error), #[error(transparent)] OfficeConsents_Delete(#[from] office_consents::delete::Error), #[error(transparent)] ThreatIntelligenceIndicator_CreateIndicator(#[from] threat_intelligence_indicator::create_indicator::Error), #[error(transparent)] ThreatIntelligenceIndicators_List(#[from] threat_intelligence_indicators::list::Error), #[error(transparent)] ThreatIntelligenceIndicator_Get(#[from] threat_intelligence_indicator::get::Error), #[error(transparent)] ThreatIntelligenceIndicator_Create(#[from] threat_intelligence_indicator::create::Error), #[error(transparent)] ThreatIntelligenceIndicator_Delete(#[from] threat_intelligence_indicator::delete::Error), #[error(transparent)] ThreatIntelligenceIndicator_QueryIndicators(#[from] threat_intelligence_indicator::query_indicators::Error), #[error(transparent)] ThreatIntelligenceIndicatorMetrics_List(#[from] threat_intelligence_indicator_metrics::list::Error), #[error(transparent)] ThreatIntelligenceIndicator_AppendTags(#[from] threat_intelligence_indicator::append_tags::Error), #[error(transparent)] ThreatIntelligenceIndicator_ReplaceTags(#[from] threat_intelligence_indicator::replace_tags::Error), } pub mod cases_aggregations { use super::{models, API_VERSION}; pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, aggregations_name: &str, ) -> std::result::Result<models::Aggregations, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/aggregations/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, aggregations_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Aggregations = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod operations { use super::{models, API_VERSION}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<models::OperationsList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/providers/Microsoft.SecurityInsights/operations", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::OperationsList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); Err(list::Error::UnexpectedResponse { status_code, body: rsp_body.clone(), }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Unexpected HTTP status code {}", status_code)] UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod alert_rules { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::AlertRulesList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AlertRulesList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, ) -> std::result::Result<models::AlertRule, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, rule_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AlertRule = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, alert_rule: &models::AlertRule, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, rule_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(alert_rule).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AlertRule = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::AlertRule = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::AlertRule), Created201(models::AlertRule), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, rule_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod actions { use super::{models, API_VERSION}; pub async fn list_by_alert_rule( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, ) -> std::result::Result<models::ActionsList, list_by_alert_rule::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, rule_id ); let mut url = url::Url::parse(url_str).map_err(list_by_alert_rule::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_by_alert_rule::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_by_alert_rule::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_by_alert_rule::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ActionsList = serde_json::from_slice(rsp_body) .map_err(|source| list_by_alert_rule::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| list_by_alert_rule::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_by_alert_rule::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_by_alert_rule { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, action_id: &str, ) -> std::result::Result<models::ActionResponse, get::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ; let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ActionResponse = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, action_id: &str, action: &models::ActionRequest, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ; let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(action).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ActionResponse = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::ActionResponse = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::ActionResponse), Created201(models::ActionResponse), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, rule_id: &str, action_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRules/{}/actions/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , rule_id , action_id) ; let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod alert_rule_templates { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::AlertRuleTemplatesList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRuleTemplates", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AlertRuleTemplatesList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, alert_rule_template_id: &str, ) -> std::result::Result<models::AlertRuleTemplate, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/alertRuleTemplates/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, alert_rule_template_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AlertRuleTemplate = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod data_connectors { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::DataConnectorList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DataConnectorList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, data_connector_id: &str, ) -> std::result::Result<models::DataConnector, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, data_connector_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DataConnector = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, data_connector_id: &str, data_connector: &models::DataConnector, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, data_connector_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(data_connector).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DataConnector = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::DataConnector = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::DataConnector), Created201(models::DataConnector), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, data_connector_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectors/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, data_connector_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod product_settings { use super::{models, API_VERSION}; pub async fn get_all( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::SettingList, get_all::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(get_all::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_all::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_all::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_all::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::SettingList = serde_json::from_slice(rsp_body).map_err(|source| get_all::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_all::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_all::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_all { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, settings_name: &str, ) -> std::result::Result<models::Settings, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, settings_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Settings = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, settings_name: &str, settings: &models::Settings, ) -> std::result::Result<models::Settings, update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, settings_name ); let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(settings).map_err(update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Settings = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Err(update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, settings_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/settings/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, settings_name ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod entity_queries { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::EntityQueryList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entityQueries", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityQueryList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_query_id: &str, ) -> std::result::Result<models::EntityQuery, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entityQueries/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_query_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityQuery = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod incidents { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::IncidentList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, ) -> std::result::Result<models::Incident, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Incident = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, incident: &models::Incident, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(incident).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Incident = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Incident = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Incident), Created201(models::Incident), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_of_alerts( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, ) -> std::result::Result<models::IncidentAlertList, list_of_alerts::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/alerts", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(list_of_alerts::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_of_alerts::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_of_alerts::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_of_alerts::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentAlertList = serde_json::from_slice(rsp_body).map_err(|source| list_of_alerts::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list_of_alerts::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_of_alerts::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_of_alerts { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_of_bookmarks( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, ) -> std::result::Result<models::IncidentBookmarkList, list_of_bookmarks::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/bookmarks", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(list_of_bookmarks::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_of_bookmarks::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_of_bookmarks::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_of_bookmarks::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentBookmarkList = serde_json::from_slice(rsp_body) .map_err(|source| list_of_bookmarks::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| list_of_bookmarks::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_of_bookmarks::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_of_bookmarks { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_of_entities( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, ) -> std::result::Result<models::IncidentEntitiesResponse, list_of_entities::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/entities", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(list_of_entities::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_of_entities::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_of_entities::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_of_entities::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentEntitiesResponse = serde_json::from_slice(rsp_body) .map_err(|source| list_of_entities::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| list_of_entities::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_of_entities::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_of_entities { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod incident_comments { use super::{models, API_VERSION}; pub async fn list_by_incident( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::IncidentCommentList, list_by_incident::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(list_by_incident::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_by_incident::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_by_incident::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_by_incident::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentCommentList = serde_json::from_slice(rsp_body) .map_err(|source| list_by_incident::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| list_by_incident::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_by_incident::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_by_incident { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_comment( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, incident_comment_id: &str, ) -> std::result::Result<models::IncidentComment, get_comment::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ; let mut url = url::Url::parse(url_str).map_err(get_comment::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_comment::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_comment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_comment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentComment = serde_json::from_slice(rsp_body).map_err(|source| get_comment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_comment::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_comment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_comment { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_comment( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, incident_comment_id: &str, incident_comment: &models::IncidentComment, ) -> std::result::Result<create_comment::Response, create_comment::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ; let mut url = url::Url::parse(url_str).map_err(create_comment::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_comment::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(incident_comment).map_err(create_comment::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_comment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_comment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::IncidentComment = serde_json::from_slice(rsp_body).map_err(|source| create_comment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_comment::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::IncidentComment = serde_json::from_slice(rsp_body).map_err(|source| create_comment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_comment::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| create_comment::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_comment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_comment { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::IncidentComment), Created201(models::IncidentComment), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete_comment( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, incident_comment_id: &str, ) -> std::result::Result<delete_comment::Response, delete_comment::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/comments/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , incident_comment_id) ; let mut url = url::Url::parse(url_str).map_err(delete_comment::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete_comment::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete_comment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_comment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete_comment::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete_comment::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete_comment::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_comment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_comment { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod incident_relations { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::RelationList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, incident_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RelationList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, relation_name: &str, ) -> std::result::Result<models::Relation, get_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(get_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_relation { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, relation_name: &str, relation: &models::Relation, ) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(create_or_update_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(relation).map_err(create_or_update_relation::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_or_update_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Relation), Created201(models::Relation), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, incident_id: &str, relation_name: &str, ) -> std::result::Result<delete_relation::Response, delete_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/incidents/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , incident_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(delete_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete_relation::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| delete_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod watchlists { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::WatchlistList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::WatchlistList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, ) -> std::result::Result<models::Watchlist, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, watchlist_alias ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Watchlist = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, watchlist: &models::Watchlist, ) -> std::result::Result<create::Response, create::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, watchlist_alias ); let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(watchlist).map_err(create::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Watchlist = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Watchlist = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Err(create::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Watchlist), Created201(models::Watchlist), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, watchlist_alias ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod watchlist_items { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, ) -> std::result::Result<models::WatchlistItemList, list::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}/watchlistItems" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , watchlist_alias) ; let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::WatchlistItemList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, watchlist_item_id: &str, ) -> std::result::Result<models::WatchlistItem, get::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}/watchlistItems/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , watchlist_alias , watchlist_item_id) ; let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::WatchlistItem = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, watchlist_item_id: &str, watchlist_item: &models::WatchlistItem, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}/watchlistItems/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , watchlist_alias , watchlist_item_id) ; let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(watchlist_item).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::WatchlistItem = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::WatchlistItem = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::WatchlistItem), Created201(models::WatchlistItem), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, watchlist_alias: &str, watchlist_item_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/watchlists/{}/watchlistItems/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , watchlist_alias , watchlist_item_id) ; let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod automation_rules { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::AutomationRulesList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/automationRules", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AutomationRulesList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, automation_rule_id: &str, ) -> std::result::Result<models::AutomationRule, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/automationRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, automation_rule_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AutomationRule = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, automation_rule_id: &str, automation_rule: &models::AutomationRule, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/automationRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, automation_rule_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(automation_rule).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::AutomationRule = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::AutomationRule = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::AutomationRule), Created201(models::AutomationRule), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, automation_rule_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/automationRules/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, automation_rule_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod bookmarks { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::BookmarkList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BookmarkList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, ) -> std::result::Result<models::Bookmark, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, bookmark_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Bookmark = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, bookmark: &models::Bookmark, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, bookmark_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(bookmark).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Bookmark = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Bookmark = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Bookmark), Created201(models::Bookmark), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, bookmark_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod bookmark_relations { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::RelationList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, bookmark_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RelationList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, relation_name: &str, ) -> std::result::Result<models::Relation, get_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(get_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_relation { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, relation_name: &str, relation: &models::Relation, ) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(create_or_update_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(relation).map_err(create_or_update_relation::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_or_update_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Relation), Created201(models::Relation), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, relation_name: &str, ) -> std::result::Result<delete_relation::Response, delete_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , bookmark_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(delete_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete_relation::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| delete_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod bookmark { use super::{models, API_VERSION}; pub async fn expand( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, bookmark_id: &str, parameters: &models::BookmarkExpandParameters, ) -> std::result::Result<models::BookmarkExpandResponse, expand::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/bookmarks/{}/expand", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, bookmark_id ); let mut url = url::Url::parse(url_str).map_err(expand::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(expand::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(parameters).map_err(expand::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(expand::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(expand::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::BookmarkExpandResponse = serde_json::from_slice(rsp_body).map_err(|source| expand::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| expand::Error::DeserializeError(source, rsp_body.clone()))?; Err(expand::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod expand { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod cases { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::CaseList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, ) -> std::result::Result<models::Case, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Case = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, case: &models::Case, ) -> std::result::Result<create_or_update::Response, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(case).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Case = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::Case = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::Case), Created201(models::Case), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_comment( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, case_comment_id: &str, ) -> std::result::Result<models::CaseComment, get_comment::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id, case_comment_id ); let mut url = url::Url::parse(url_str).map_err(get_comment::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_comment::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_comment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_comment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseComment = serde_json::from_slice(rsp_body).map_err(|source| get_comment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_comment::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_comment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_comment { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod comments { use super::{models, API_VERSION}; pub async fn list_by_case( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::CaseCommentList, list_by_case::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id ); let mut url = url::Url::parse(url_str).map_err(list_by_case::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_by_case::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_by_case::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_by_case::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseCommentList = serde_json::from_slice(rsp_body).map_err(|source| list_by_case::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list_by_case::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_by_case::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_by_case { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod case_comments { use super::{models, API_VERSION}; pub async fn create_comment( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, case_comment_id: &str, case_comment: &models::CaseComment, ) -> std::result::Result<models::CaseComment, create_comment::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/comments/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id, case_comment_id ); let mut url = url::Url::parse(url_str).map_err(create_comment::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_comment::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(case_comment).map_err(create_comment::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_comment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_comment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::CaseComment = serde_json::from_slice(rsp_body).map_err(|source| create_comment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| create_comment::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_comment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_comment { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod case_relations { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::CaseRelationList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseRelationList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, relation_name: &str, ) -> std::result::Result<models::CaseRelation, get_relation::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id, relation_name ); let mut url = url::Url::parse(url_str).map_err(get_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseRelation = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_relation { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, relation_name: &str, relation_input_model: &models::RelationsModelInput, ) -> std::result::Result<create_or_update_relation::Response, create_or_update_relation::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id, relation_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(relation_input_model).map_err(create_or_update_relation::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_or_update_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CaseRelation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::CaseRelation = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_or_update_relation::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::CaseRelation), Created201(models::CaseRelation), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, case_id: &str, relation_name: &str, ) -> std::result::Result<delete_relation::Response, delete_relation::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/cases/{}/relations/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, case_id, relation_name ); let mut url = url::Url::parse(url_str).map_err(delete_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete_relation::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete_relation::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| delete_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_relation { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod data_connectors_check_requirements { use super::{models, API_VERSION}; pub async fn post( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, workspace_name: &str, operational_insights_resource_provider: &str, data_connectors_check_requirements: &models::DataConnectorsCheckRequirements, ) -> std::result::Result<models::DataConnectorRequirementsState, post::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/dataConnectorsCheckRequirements" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name) ; let mut url = url::Url::parse(url_str).map_err(post::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(post::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(data_connectors_check_requirements).map_err(post::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(post::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(post::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DataConnectorRequirementsState = serde_json::from_slice(rsp_body).map_err(|source| post::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| post::Error::DeserializeError(source, rsp_body.clone()))?; Err(post::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod post { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod ip_geodata { use super::{models, API_VERSION}; pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ip_address: &str, ) -> std::result::Result<models::EnrichmentIpGeodata, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.SecurityInsights/enrichment/ip/geodata/", operation_config.base_path(), subscription_id, resource_group_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); url.query_pairs_mut().append_pair("ipAddress", ip_address); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EnrichmentIpGeodata = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod domain_whois { use super::{models, API_VERSION}; pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, domain: &str, ) -> std::result::Result<models::EnrichmentDomainWhois, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.SecurityInsights/enrichment/domain/whois/", operation_config.base_path(), subscription_id, resource_group_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); url.query_pairs_mut().append_pair("domain", domain); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EnrichmentDomainWhois = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod entities { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::EntityList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, ) -> std::result::Result<models::Entity, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Entity = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn expand( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, parameters: &models::EntityExpandParameters, ) -> std::result::Result<models::EntityExpandResponse, expand::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/expand", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(expand::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(expand::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(parameters).map_err(expand::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(expand::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(expand::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityExpandResponse = serde_json::from_slice(rsp_body).map_err(|source| expand::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| expand::Error::DeserializeError(source, rsp_body.clone()))?; Err(expand::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod expand { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn queries( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, kind: &str, ) -> std::result::Result<models::GetQueriesResponse, queries::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/queries", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(queries::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(queries::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); url.query_pairs_mut().append_pair("kind", kind); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(queries::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(queries::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::GetQueriesResponse = serde_json::from_slice(rsp_body).map_err(|source| queries::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| queries::Error::DeserializeError(source, rsp_body.clone()))?; Err(queries::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod queries { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_insights( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, parameters: &models::EntityGetInsightsParameters, ) -> std::result::Result<models::EntityGetInsightsResponse, get_insights::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/getInsights", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(get_insights::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_insights::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(parameters).map_err(get_insights::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_insights::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_insights::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityGetInsightsResponse = serde_json::from_slice(rsp_body).map_err(|source| get_insights::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_insights::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_insights::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_insights { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod entities_get_timeline { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, parameters: &models::EntityTimelineParameters, ) -> std::result::Result<models::EntityTimelineResponse, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/getTimeline", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(parameters).map_err(list::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::EntityTimelineResponse = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod entities_relations { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::RelationList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/relations", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, entity_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RelationList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod entity_relations { use super::{models, API_VERSION}; pub async fn get_relation( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, entity_id: &str, relation_name: &str, ) -> std::result::Result<models::Relation, get_relation::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/entities/{}/relations/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , entity_id , relation_name) ; let mut url = url::Url::parse(url_str).map_err(get_relation::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_relation::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_relation::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_relation::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::Relation = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get_relation::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_relation::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_relation { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod office_consents { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::OfficeConsentList, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::OfficeConsentList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, consent_id: &str, ) -> std::result::Result<models::OfficeConsent, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, consent_id ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::OfficeConsent = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, consent_id: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/officeConsents/{}", operation_config.base_path(), subscription_id, resource_group_name, operational_insights_resource_provider, workspace_name, consent_id ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod threat_intelligence_indicator { use super::{models, API_VERSION}; pub async fn create_indicator( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, threat_intelligence_properties: &models::ThreatIntelligenceIndicatorModelForRequestBody, ) -> std::result::Result<create_indicator::Response, create_indicator::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/createIndicator" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name) ; let mut url = url::Url::parse(url_str).map_err(create_indicator::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_indicator::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(threat_intelligence_properties).map_err(create_indicator::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_indicator::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_indicator::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body) .map_err(|source| create_indicator::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_indicator::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body) .map_err(|source| create_indicator::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create_indicator::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| create_indicator::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_indicator::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_indicator { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::ThreatIntelligenceInformation), Created201(models::ThreatIntelligenceInformation), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, name: &str, ) -> std::result::Result<models::ThreatIntelligenceInformation, get::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , name) ; let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, name: &str, threat_intelligence_properties: &models::ThreatIntelligenceIndicatorModelForRequestBody, ) -> std::result::Result<create::Response, create::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , name) ; let mut url = url::Url::parse(url_str).map_err(create::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(threat_intelligence_properties).map_err(create::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(create::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Ok200(rsp_value)) } http::StatusCode::CREATED => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Ok(create::Response::Created201(rsp_value)) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| create::Error::DeserializeError(source, rsp_body.clone()))?; Err(create::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::ThreatIntelligenceInformation), Created201(models::ThreatIntelligenceInformation), } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , name) ; let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200, NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn query_indicators( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, threat_intelligence_filtering_criteria: &models::ThreatIntelligenceFilteringCriteria, ) -> std::result::Result<models::ThreatIntelligenceInformationList, query_indicators::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/queryIndicators" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name) ; let mut url = url::Url::parse(url_str).map_err(query_indicators::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(query_indicators::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(threat_intelligence_filtering_criteria).map_err(query_indicators::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(query_indicators::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(query_indicators::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformationList = serde_json::from_slice(rsp_body) .map_err(|source| query_indicators::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body) .map_err(|source| query_indicators::Error::DeserializeError(source, rsp_body.clone()))?; Err(query_indicators::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod query_indicators { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn append_tags( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, name: &str, threat_intelligence_append_tags: &models::ThreatIntelligenceAppendTags, ) -> std::result::Result<(), append_tags::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}/appendTags" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , name) ; let mut url = url::Url::parse(url_str).map_err(append_tags::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(append_tags::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(threat_intelligence_append_tags).map_err(append_tags::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(append_tags::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(append_tags::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(()), status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| append_tags::Error::DeserializeError(source, rsp_body.clone()))?; Err(append_tags::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod append_tags { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn replace_tags( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, name: &str, threat_intelligence_replace_tags: &models::ThreatIntelligenceIndicatorModelForRequestBody, ) -> std::result::Result<models::ThreatIntelligenceInformation, replace_tags::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators/{}/replaceTags" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name , name) ; let mut url = url::Url::parse(url_str).map_err(replace_tags::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(replace_tags::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(threat_intelligence_replace_tags).map_err(replace_tags::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(replace_tags::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(replace_tags::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformation = serde_json::from_slice(rsp_body).map_err(|source| replace_tags::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| replace_tags::Error::DeserializeError(source, rsp_body.clone()))?; Err(replace_tags::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod replace_tags { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod threat_intelligence_indicators { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, filter: Option<&str>, orderby: Option<&str>, top: Option<i32>, skip_token: Option<&str>, ) -> std::result::Result<models::ThreatIntelligenceInformationList, list::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/indicators" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name) ; let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); if let Some(filter) = filter { url.query_pairs_mut().append_pair("$filter", filter); } if let Some(orderby) = orderby { url.query_pairs_mut().append_pair("$orderby", orderby); } if let Some(top) = top { url.query_pairs_mut().append_pair("$top", top.to_string().as_str()); } if let Some(skip_token) = skip_token { url.query_pairs_mut().append_pair("$skipToken", skip_token); } let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceInformationList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod threat_intelligence_indicator_metrics { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, operational_insights_resource_provider: &str, workspace_name: &str, ) -> std::result::Result<models::ThreatIntelligenceMetricsList, list::Error> { let http_client = operation_config.http_client(); let url_str = & format ! ("{}/subscriptions/{}/resourceGroups/{}/providers/{}/workspaces/{}/providers/Microsoft.SecurityInsights/threatIntelligence/main/metrics" , operation_config . base_path () , subscription_id , resource_group_name , operational_insights_resource_provider , workspace_name) ; let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ThreatIntelligenceMetricsList = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::CloudError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::CloudError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - This register specifies the parameters used by channel y."] pub dfsdm_ch0cfgr1: DFSDM_CH0CFGR1, #[doc = "0x04 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch0cfgr2: DFSDM_CH0CFGR2, #[doc = "0x08 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch0awscdr: DFSDM_CH0AWSCDR, #[doc = "0x0c - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch0wdatr: DFSDM_CH0WDATR, #[doc = "0x10 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch0datinr: DFSDM_CH0DATINR, _reserved5: [u8; 12usize], #[doc = "0x20 - This register specifies the parameters used by channel y."] pub dfsdm_ch1cfgr1: DFSDM_CH1CFGR1, #[doc = "0x24 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch1cfgr2: DFSDM_CH1CFGR2, #[doc = "0x28 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch1awscdr: DFSDM_CH1AWSCDR, #[doc = "0x2c - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch1wdatr: DFSDM_CH1WDATR, #[doc = "0x30 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch1datinr: DFSDM_CH1DATINR, _reserved10: [u8; 12usize], #[doc = "0x40 - This register specifies the parameters used by channel y."] pub dfsdm_ch2cfgr1: DFSDM_CH2CFGR1, #[doc = "0x44 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch2cfgr2: DFSDM_CH2CFGR2, #[doc = "0x48 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch2awscdr: DFSDM_CH2AWSCDR, #[doc = "0x4c - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch2wdatr: DFSDM_CH2WDATR, #[doc = "0x50 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch2datinr: DFSDM_CH2DATINR, _reserved15: [u8; 12usize], #[doc = "0x60 - This register specifies the parameters used by channel y."] pub dfsdm_ch3cfgr1: DFSDM_CH3CFGR1, #[doc = "0x64 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch3cfgr2: DFSDM_CH3CFGR2, #[doc = "0x68 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch3awscdr: DFSDM_CH3AWSCDR, #[doc = "0x6c - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch3wdatr: DFSDM_CH3WDATR, #[doc = "0x70 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch3datinr: DFSDM_CH3DATINR, _reserved20: [u8; 12usize], #[doc = "0x80 - This register specifies the parameters used by channel y."] pub dfsdm_ch4cfgr1: DFSDM_CH4CFGR1, #[doc = "0x84 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch4cfgr2: DFSDM_CH4CFGR2, #[doc = "0x88 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch4awscdr: DFSDM_CH4AWSCDR, #[doc = "0x8c - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch4wdatr: DFSDM_CH4WDATR, #[doc = "0x90 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch4datinr: DFSDM_CH4DATINR, _reserved25: [u8; 12usize], #[doc = "0xa0 - This register specifies the parameters used by channel y."] pub dfsdm_ch5cfgr1: DFSDM_CH5CFGR1, #[doc = "0xa4 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch5cfgr2: DFSDM_CH5CFGR2, #[doc = "0xa8 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch5awscdr: DFSDM_CH5AWSCDR, #[doc = "0xac - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch5wdatr: DFSDM_CH5WDATR, #[doc = "0xb0 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch5datinr: DFSDM_CH5DATINR, _reserved30: [u8; 12usize], #[doc = "0xc0 - This register specifies the parameters used by channel y."] pub dfsdm_ch6cfgr1: DFSDM_CH6CFGR1, #[doc = "0xc4 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch6cfgr2: DFSDM_CH6CFGR2, #[doc = "0xc8 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch6awscdr: DFSDM_CH6AWSCDR, #[doc = "0xcc - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch6wdatr: DFSDM_CH6WDATR, #[doc = "0xd0 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch6datinr: DFSDM_CH6DATINR, _reserved35: [u8; 12usize], #[doc = "0xe0 - This register specifies the parameters used by channel y."] pub dfsdm_ch7cfgr1: DFSDM_CH7CFGR1, #[doc = "0xe4 - This register specifies the parameters used by channel y (y = 0..7)."] pub dfsdm_ch7cfgr2: DFSDM_CH7CFGR2, #[doc = "0xe8 - Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub dfsdm_ch7awscdr: DFSDM_CH7AWSCDR, #[doc = "0xec - This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub dfsdm_ch7wdatr: DFSDM_CH7WDATR, #[doc = "0xf0 - This register contains 16-bit input data to be processed by DFSDM filter module."] pub dfsdm_ch7datinr: DFSDM_CH7DATINR, _reserved40: [u8; 12usize], #[doc = "0x100 - DFSDM control register 1"] pub dfsdm_flt0cr1: DFSDM_FLT0CR1, #[doc = "0x104 - DFSDM control register 2"] pub dfsdm_flt0cr2: DFSDM_FLT0CR2, #[doc = "0x108 - DFSDM interrupt and status register"] pub dfsdm_flt0isr: DFSDM_FLT0ISR, #[doc = "0x10c - DFSDM interrupt flag clear register"] pub dfsdm_flt0icr: DFSDM_FLT0ICR, #[doc = "0x110 - DFSDM injected channel group selection register"] pub dfsdm_flt0jchgr: DFSDM_FLT0JCHGR, #[doc = "0x114 - DFSDM filter control register"] pub dfsdm_flt0fcr: DFSDM_FLT0FCR, #[doc = "0x118 - DFSDM data register for injected group"] pub dfsdm_flt0jdatar: DFSDM_FLT0JDATAR, #[doc = "0x11c - DFSDM data register for the regular channel"] pub dfsdm_flt0rdatar: DFSDM_FLT0RDATAR, #[doc = "0x120 - DFSDM analog watchdog high threshold register"] pub dfsdm_flt0awhtr: DFSDM_FLT0AWHTR, #[doc = "0x124 - DFSDM analog watchdog low threshold register"] pub dfsdm_flt0awltr: DFSDM_FLT0AWLTR, #[doc = "0x128 - DFSDM analog watchdog status register"] pub dfsdm_flt0awsr: DFSDM_FLT0AWSR, #[doc = "0x12c - DFSDM analog watchdog clear flag register"] pub dfsdm_flt0awcfr: DFSDM_FLT0AWCFR, #[doc = "0x130 - DFSDM Extremes detector maximum register"] pub dfsdm_flt0exmax: DFSDM_FLT0EXMAX, #[doc = "0x134 - DFSDM Extremes detector minimum register"] pub dfsdm_flt0exmin: DFSDM_FLT0EXMIN, #[doc = "0x138 - DFSDM conversion timer register"] pub dfsdm_flt0cnvtimr: DFSDM_FLT0CNVTIMR, _reserved55: [u8; 68usize], #[doc = "0x180 - DFSDM control register 1"] pub dfsdm_flt1cr1: DFSDM_FLT1CR1, #[doc = "0x184 - DFSDM control register 2"] pub dfsdm_flt1cr2: DFSDM_FLT1CR2, #[doc = "0x188 - DFSDM interrupt and status register"] pub dfsdm_flt1isr: DFSDM_FLT1ISR, #[doc = "0x18c - DFSDM interrupt flag clear register"] pub dfsdm_flt1icr: DFSDM_FLT1ICR, #[doc = "0x190 - DFSDM injected channel group selection register"] pub dfsdm_flt1jchgr: DFSDM_FLT1JCHGR, #[doc = "0x194 - DFSDM filter control register"] pub dfsdm_flt1fcr: DFSDM_FLT1FCR, #[doc = "0x198 - DFSDM data register for injected group"] pub dfsdm_flt1jdatar: DFSDM_FLT1JDATAR, #[doc = "0x19c - DFSDM data register for the regular channel"] pub dfsdm_flt1rdatar: DFSDM_FLT1RDATAR, #[doc = "0x1a0 - DFSDM analog watchdog high threshold register"] pub dfsdm_flt1awhtr: DFSDM_FLT1AWHTR, #[doc = "0x1a4 - DFSDM analog watchdog low threshold register"] pub dfsdm_flt1awltr: DFSDM_FLT1AWLTR, #[doc = "0x1a8 - DFSDM analog watchdog status register"] pub dfsdm_flt1awsr: DFSDM_FLT1AWSR, #[doc = "0x1ac - DFSDM analog watchdog clear flag register"] pub dfsdm_flt1awcfr: DFSDM_FLT1AWCFR, #[doc = "0x1b0 - DFSDM Extremes detector maximum register"] pub dfsdm_flt1exmax: DFSDM_FLT1EXMAX, #[doc = "0x1b4 - DFSDM Extremes detector minimum register"] pub dfsdm_flt1exmin: DFSDM_FLT1EXMIN, #[doc = "0x1b8 - DFSDM conversion timer register"] pub dfsdm_flt1cnvtimr: DFSDM_FLT1CNVTIMR, _reserved70: [u8; 68usize], #[doc = "0x200 - DFSDM control register 1"] pub dfsdm_flt2cr1: DFSDM_FLT2CR1, #[doc = "0x204 - DFSDM control register 2"] pub dfsdm_flt2cr2: DFSDM_FLT2CR2, #[doc = "0x208 - DFSDM interrupt and status register"] pub dfsdm_flt2isr: DFSDM_FLT2ISR, #[doc = "0x20c - DFSDM interrupt flag clear register"] pub dfsdm_flt2icr: DFSDM_FLT2ICR, #[doc = "0x210 - DFSDM injected channel group selection register"] pub dfsdm_flt2jchgr: DFSDM_FLT2JCHGR, #[doc = "0x214 - DFSDM filter control register"] pub dfsdm_flt2fcr: DFSDM_FLT2FCR, #[doc = "0x218 - DFSDM data register for injected group"] pub dfsdm_flt2jdatar: DFSDM_FLT2JDATAR, #[doc = "0x21c - DFSDM data register for the regular channel"] pub dfsdm_flt2rdatar: DFSDM_FLT2RDATAR, #[doc = "0x220 - DFSDM analog watchdog high threshold register"] pub dfsdm_flt2awhtr: DFSDM_FLT2AWHTR, #[doc = "0x224 - DFSDM analog watchdog low threshold register"] pub dfsdm_flt2awltr: DFSDM_FLT2AWLTR, #[doc = "0x228 - DFSDM analog watchdog status register"] pub dfsdm_flt2awsr: DFSDM_FLT2AWSR, #[doc = "0x22c - DFSDM analog watchdog clear flag register"] pub dfsdm_flt2awcfr: DFSDM_FLT2AWCFR, #[doc = "0x230 - DFSDM Extremes detector maximum register"] pub dfsdm_flt2exmax: DFSDM_FLT2EXMAX, #[doc = "0x234 - DFSDM Extremes detector minimum register"] pub dfsdm_flt2exmin: DFSDM_FLT2EXMIN, #[doc = "0x238 - DFSDM conversion timer register"] pub dfsdm_flt2cnvtimr: DFSDM_FLT2CNVTIMR, _reserved85: [u8; 68usize], #[doc = "0x280 - DFSDM control register 1"] pub dfsdm_flt3cr1: DFSDM_FLT3CR1, #[doc = "0x284 - DFSDM control register 2"] pub dfsdm_flt3cr2: DFSDM_FLT3CR2, #[doc = "0x288 - DFSDM interrupt and status register"] pub dfsdm_flt3isr: DFSDM_FLT3ISR, #[doc = "0x28c - DFSDM interrupt flag clear register"] pub dfsdm_flt3icr: DFSDM_FLT3ICR, #[doc = "0x290 - DFSDM injected channel group selection register"] pub dfsdm_flt3jchgr: DFSDM_FLT3JCHGR, #[doc = "0x294 - DFSDM filter control register"] pub dfsdm_flt3fcr: DFSDM_FLT3FCR, #[doc = "0x298 - DFSDM data register for injected group"] pub dfsdm_flt3jdatar: DFSDM_FLT3JDATAR, #[doc = "0x29c - DFSDM data register for the regular channel"] pub dfsdm_flt3rdatar: DFSDM_FLT3RDATAR, #[doc = "0x2a0 - DFSDM analog watchdog high threshold register"] pub dfsdm_flt3awhtr: DFSDM_FLT3AWHTR, #[doc = "0x2a4 - DFSDM analog watchdog low threshold register"] pub dfsdm_flt3awltr: DFSDM_FLT3AWLTR, #[doc = "0x2a8 - DFSDM analog watchdog status register"] pub dfsdm_flt3awsr: DFSDM_FLT3AWSR, #[doc = "0x2ac - DFSDM analog watchdog clear flag register"] pub dfsdm_flt3awcfr: DFSDM_FLT3AWCFR, #[doc = "0x2b0 - DFSDM Extremes detector maximum register"] pub dfsdm_flt3exmax: DFSDM_FLT3EXMAX, #[doc = "0x2b4 - DFSDM Extremes detector minimum register"] pub dfsdm_flt3exmin: DFSDM_FLT3EXMIN, #[doc = "0x2b8 - DFSDM conversion timer register"] pub dfsdm_flt3cnvtimr: DFSDM_FLT3CNVTIMR, } #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch0cfgr1](dfsdm_ch0cfgr1) module"] pub type DFSDM_CH0CFGR1 = crate::Reg<u32, _DFSDM_CH0CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH0CFGR1; #[doc = "`read()` method returns [dfsdm_ch0cfgr1::R](dfsdm_ch0cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH0CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch0cfgr1::W](dfsdm_ch0cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH0CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch0cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch0cfgr2](dfsdm_ch0cfgr2) module"] pub type DFSDM_CH0CFGR2 = crate::Reg<u32, _DFSDM_CH0CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH0CFGR2; #[doc = "`read()` method returns [dfsdm_ch0cfgr2::R](dfsdm_ch0cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH0CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch0cfgr2::W](dfsdm_ch0cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH0CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch0cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch0awscdr](dfsdm_ch0awscdr) module"] pub type DFSDM_CH0AWSCDR = crate::Reg<u32, _DFSDM_CH0AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH0AWSCDR; #[doc = "`read()` method returns [dfsdm_ch0awscdr::R](dfsdm_ch0awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH0AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch0awscdr::W](dfsdm_ch0awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH0AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch0awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch0wdatr](dfsdm_ch0wdatr) module"] pub type DFSDM_CH0WDATR = crate::Reg<u32, _DFSDM_CH0WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH0WDATR; #[doc = "`read()` method returns [dfsdm_ch0wdatr::R](dfsdm_ch0wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH0WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch0wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch0datinr](dfsdm_ch0datinr) module"] pub type DFSDM_CH0DATINR = crate::Reg<u32, _DFSDM_CH0DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH0DATINR; #[doc = "`read()` method returns [dfsdm_ch0datinr::R](dfsdm_ch0datinr::R) reader structure"] impl crate::Readable for DFSDM_CH0DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch0datinr::W](dfsdm_ch0datinr::W) writer structure"] impl crate::Writable for DFSDM_CH0DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch0datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch1cfgr1](dfsdm_ch1cfgr1) module"] pub type DFSDM_CH1CFGR1 = crate::Reg<u32, _DFSDM_CH1CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH1CFGR1; #[doc = "`read()` method returns [dfsdm_ch1cfgr1::R](dfsdm_ch1cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH1CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch1cfgr1::W](dfsdm_ch1cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH1CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch1cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch1cfgr2](dfsdm_ch1cfgr2) module"] pub type DFSDM_CH1CFGR2 = crate::Reg<u32, _DFSDM_CH1CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH1CFGR2; #[doc = "`read()` method returns [dfsdm_ch1cfgr2::R](dfsdm_ch1cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH1CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch1cfgr2::W](dfsdm_ch1cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH1CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch1cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch1awscdr](dfsdm_ch1awscdr) module"] pub type DFSDM_CH1AWSCDR = crate::Reg<u32, _DFSDM_CH1AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH1AWSCDR; #[doc = "`read()` method returns [dfsdm_ch1awscdr::R](dfsdm_ch1awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH1AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch1awscdr::W](dfsdm_ch1awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH1AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch1awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch1wdatr](dfsdm_ch1wdatr) module"] pub type DFSDM_CH1WDATR = crate::Reg<u32, _DFSDM_CH1WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH1WDATR; #[doc = "`read()` method returns [dfsdm_ch1wdatr::R](dfsdm_ch1wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH1WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch1wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch1datinr](dfsdm_ch1datinr) module"] pub type DFSDM_CH1DATINR = crate::Reg<u32, _DFSDM_CH1DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH1DATINR; #[doc = "`read()` method returns [dfsdm_ch1datinr::R](dfsdm_ch1datinr::R) reader structure"] impl crate::Readable for DFSDM_CH1DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch1datinr::W](dfsdm_ch1datinr::W) writer structure"] impl crate::Writable for DFSDM_CH1DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch1datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch2cfgr1](dfsdm_ch2cfgr1) module"] pub type DFSDM_CH2CFGR1 = crate::Reg<u32, _DFSDM_CH2CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH2CFGR1; #[doc = "`read()` method returns [dfsdm_ch2cfgr1::R](dfsdm_ch2cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH2CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch2cfgr1::W](dfsdm_ch2cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH2CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch2cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch2cfgr2](dfsdm_ch2cfgr2) module"] pub type DFSDM_CH2CFGR2 = crate::Reg<u32, _DFSDM_CH2CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH2CFGR2; #[doc = "`read()` method returns [dfsdm_ch2cfgr2::R](dfsdm_ch2cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH2CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch2cfgr2::W](dfsdm_ch2cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH2CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch2cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch2awscdr](dfsdm_ch2awscdr) module"] pub type DFSDM_CH2AWSCDR = crate::Reg<u32, _DFSDM_CH2AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH2AWSCDR; #[doc = "`read()` method returns [dfsdm_ch2awscdr::R](dfsdm_ch2awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH2AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch2awscdr::W](dfsdm_ch2awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH2AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch2awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch2wdatr](dfsdm_ch2wdatr) module"] pub type DFSDM_CH2WDATR = crate::Reg<u32, _DFSDM_CH2WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH2WDATR; #[doc = "`read()` method returns [dfsdm_ch2wdatr::R](dfsdm_ch2wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH2WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch2wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch2datinr](dfsdm_ch2datinr) module"] pub type DFSDM_CH2DATINR = crate::Reg<u32, _DFSDM_CH2DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH2DATINR; #[doc = "`read()` method returns [dfsdm_ch2datinr::R](dfsdm_ch2datinr::R) reader structure"] impl crate::Readable for DFSDM_CH2DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch2datinr::W](dfsdm_ch2datinr::W) writer structure"] impl crate::Writable for DFSDM_CH2DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch2datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch3cfgr1](dfsdm_ch3cfgr1) module"] pub type DFSDM_CH3CFGR1 = crate::Reg<u32, _DFSDM_CH3CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH3CFGR1; #[doc = "`read()` method returns [dfsdm_ch3cfgr1::R](dfsdm_ch3cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH3CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch3cfgr1::W](dfsdm_ch3cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH3CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch3cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch3cfgr2](dfsdm_ch3cfgr2) module"] pub type DFSDM_CH3CFGR2 = crate::Reg<u32, _DFSDM_CH3CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH3CFGR2; #[doc = "`read()` method returns [dfsdm_ch3cfgr2::R](dfsdm_ch3cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH3CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch3cfgr2::W](dfsdm_ch3cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH3CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch3cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch3awscdr](dfsdm_ch3awscdr) module"] pub type DFSDM_CH3AWSCDR = crate::Reg<u32, _DFSDM_CH3AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH3AWSCDR; #[doc = "`read()` method returns [dfsdm_ch3awscdr::R](dfsdm_ch3awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH3AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch3awscdr::W](dfsdm_ch3awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH3AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch3awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch3wdatr](dfsdm_ch3wdatr) module"] pub type DFSDM_CH3WDATR = crate::Reg<u32, _DFSDM_CH3WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH3WDATR; #[doc = "`read()` method returns [dfsdm_ch3wdatr::R](dfsdm_ch3wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH3WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch3wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch3datinr](dfsdm_ch3datinr) module"] pub type DFSDM_CH3DATINR = crate::Reg<u32, _DFSDM_CH3DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH3DATINR; #[doc = "`read()` method returns [dfsdm_ch3datinr::R](dfsdm_ch3datinr::R) reader structure"] impl crate::Readable for DFSDM_CH3DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch3datinr::W](dfsdm_ch3datinr::W) writer structure"] impl crate::Writable for DFSDM_CH3DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch3datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch4cfgr1](dfsdm_ch4cfgr1) module"] pub type DFSDM_CH4CFGR1 = crate::Reg<u32, _DFSDM_CH4CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH4CFGR1; #[doc = "`read()` method returns [dfsdm_ch4cfgr1::R](dfsdm_ch4cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH4CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch4cfgr1::W](dfsdm_ch4cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH4CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch4cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch4cfgr2](dfsdm_ch4cfgr2) module"] pub type DFSDM_CH4CFGR2 = crate::Reg<u32, _DFSDM_CH4CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH4CFGR2; #[doc = "`read()` method returns [dfsdm_ch4cfgr2::R](dfsdm_ch4cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH4CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch4cfgr2::W](dfsdm_ch4cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH4CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch4cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch4awscdr](dfsdm_ch4awscdr) module"] pub type DFSDM_CH4AWSCDR = crate::Reg<u32, _DFSDM_CH4AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH4AWSCDR; #[doc = "`read()` method returns [dfsdm_ch4awscdr::R](dfsdm_ch4awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH4AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch4awscdr::W](dfsdm_ch4awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH4AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch4awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch4wdatr](dfsdm_ch4wdatr) module"] pub type DFSDM_CH4WDATR = crate::Reg<u32, _DFSDM_CH4WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH4WDATR; #[doc = "`read()` method returns [dfsdm_ch4wdatr::R](dfsdm_ch4wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH4WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch4wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch4datinr](dfsdm_ch4datinr) module"] pub type DFSDM_CH4DATINR = crate::Reg<u32, _DFSDM_CH4DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH4DATINR; #[doc = "`read()` method returns [dfsdm_ch4datinr::R](dfsdm_ch4datinr::R) reader structure"] impl crate::Readable for DFSDM_CH4DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch4datinr::W](dfsdm_ch4datinr::W) writer structure"] impl crate::Writable for DFSDM_CH4DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch4datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch5cfgr1](dfsdm_ch5cfgr1) module"] pub type DFSDM_CH5CFGR1 = crate::Reg<u32, _DFSDM_CH5CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH5CFGR1; #[doc = "`read()` method returns [dfsdm_ch5cfgr1::R](dfsdm_ch5cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH5CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch5cfgr1::W](dfsdm_ch5cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH5CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch5cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch5cfgr2](dfsdm_ch5cfgr2) module"] pub type DFSDM_CH5CFGR2 = crate::Reg<u32, _DFSDM_CH5CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH5CFGR2; #[doc = "`read()` method returns [dfsdm_ch5cfgr2::R](dfsdm_ch5cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH5CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch5cfgr2::W](dfsdm_ch5cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH5CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch5cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch5awscdr](dfsdm_ch5awscdr) module"] pub type DFSDM_CH5AWSCDR = crate::Reg<u32, _DFSDM_CH5AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH5AWSCDR; #[doc = "`read()` method returns [dfsdm_ch5awscdr::R](dfsdm_ch5awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH5AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch5awscdr::W](dfsdm_ch5awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH5AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch5awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch5wdatr](dfsdm_ch5wdatr) module"] pub type DFSDM_CH5WDATR = crate::Reg<u32, _DFSDM_CH5WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH5WDATR; #[doc = "`read()` method returns [dfsdm_ch5wdatr::R](dfsdm_ch5wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH5WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch5wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch5datinr](dfsdm_ch5datinr) module"] pub type DFSDM_CH5DATINR = crate::Reg<u32, _DFSDM_CH5DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH5DATINR; #[doc = "`read()` method returns [dfsdm_ch5datinr::R](dfsdm_ch5datinr::R) reader structure"] impl crate::Readable for DFSDM_CH5DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch5datinr::W](dfsdm_ch5datinr::W) writer structure"] impl crate::Writable for DFSDM_CH5DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch5datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch6cfgr1](dfsdm_ch6cfgr1) module"] pub type DFSDM_CH6CFGR1 = crate::Reg<u32, _DFSDM_CH6CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH6CFGR1; #[doc = "`read()` method returns [dfsdm_ch6cfgr1::R](dfsdm_ch6cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH6CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch6cfgr1::W](dfsdm_ch6cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH6CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch6cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch6cfgr2](dfsdm_ch6cfgr2) module"] pub type DFSDM_CH6CFGR2 = crate::Reg<u32, _DFSDM_CH6CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH6CFGR2; #[doc = "`read()` method returns [dfsdm_ch6cfgr2::R](dfsdm_ch6cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH6CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch6cfgr2::W](dfsdm_ch6cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH6CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch6cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch6awscdr](dfsdm_ch6awscdr) module"] pub type DFSDM_CH6AWSCDR = crate::Reg<u32, _DFSDM_CH6AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH6AWSCDR; #[doc = "`read()` method returns [dfsdm_ch6awscdr::R](dfsdm_ch6awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH6AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch6awscdr::W](dfsdm_ch6awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH6AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch6awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch6wdatr](dfsdm_ch6wdatr) module"] pub type DFSDM_CH6WDATR = crate::Reg<u32, _DFSDM_CH6WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH6WDATR; #[doc = "`read()` method returns [dfsdm_ch6wdatr::R](dfsdm_ch6wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH6WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch6wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch6datinr](dfsdm_ch6datinr) module"] pub type DFSDM_CH6DATINR = crate::Reg<u32, _DFSDM_CH6DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH6DATINR; #[doc = "`read()` method returns [dfsdm_ch6datinr::R](dfsdm_ch6datinr::R) reader structure"] impl crate::Readable for DFSDM_CH6DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch6datinr::W](dfsdm_ch6datinr::W) writer structure"] impl crate::Writable for DFSDM_CH6DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch6datinr; #[doc = "This register specifies the parameters used by channel y.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch7cfgr1](dfsdm_ch7cfgr1) module"] pub type DFSDM_CH7CFGR1 = crate::Reg<u32, _DFSDM_CH7CFGR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH7CFGR1; #[doc = "`read()` method returns [dfsdm_ch7cfgr1::R](dfsdm_ch7cfgr1::R) reader structure"] impl crate::Readable for DFSDM_CH7CFGR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch7cfgr1::W](dfsdm_ch7cfgr1::W) writer structure"] impl crate::Writable for DFSDM_CH7CFGR1 {} #[doc = "This register specifies the parameters used by channel y."] pub mod dfsdm_ch7cfgr1; #[doc = "This register specifies the parameters used by channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch7cfgr2](dfsdm_ch7cfgr2) module"] pub type DFSDM_CH7CFGR2 = crate::Reg<u32, _DFSDM_CH7CFGR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH7CFGR2; #[doc = "`read()` method returns [dfsdm_ch7cfgr2::R](dfsdm_ch7cfgr2::R) reader structure"] impl crate::Readable for DFSDM_CH7CFGR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch7cfgr2::W](dfsdm_ch7cfgr2::W) writer structure"] impl crate::Writable for DFSDM_CH7CFGR2 {} #[doc = "This register specifies the parameters used by channel y (y = 0..7)."] pub mod dfsdm_ch7cfgr2; #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch7awscdr](dfsdm_ch7awscdr) module"] pub type DFSDM_CH7AWSCDR = crate::Reg<u32, _DFSDM_CH7AWSCDR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH7AWSCDR; #[doc = "`read()` method returns [dfsdm_ch7awscdr::R](dfsdm_ch7awscdr::R) reader structure"] impl crate::Readable for DFSDM_CH7AWSCDR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch7awscdr::W](dfsdm_ch7awscdr::W) writer structure"] impl crate::Writable for DFSDM_CH7AWSCDR {} #[doc = "Short-circuit detector and analog watchdog settings for channel y (y = 0..7)"] pub mod dfsdm_ch7awscdr; #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7).\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch7wdatr](dfsdm_ch7wdatr) module"] pub type DFSDM_CH7WDATR = crate::Reg<u32, _DFSDM_CH7WDATR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH7WDATR; #[doc = "`read()` method returns [dfsdm_ch7wdatr::R](dfsdm_ch7wdatr::R) reader structure"] impl crate::Readable for DFSDM_CH7WDATR {} #[doc = "This register contains the data resulting from the analog watchdog filter associated to the input channel y (y = 0..7)."] pub mod dfsdm_ch7wdatr; #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_ch7datinr](dfsdm_ch7datinr) module"] pub type DFSDM_CH7DATINR = crate::Reg<u32, _DFSDM_CH7DATINR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_CH7DATINR; #[doc = "`read()` method returns [dfsdm_ch7datinr::R](dfsdm_ch7datinr::R) reader structure"] impl crate::Readable for DFSDM_CH7DATINR {} #[doc = "`write(|w| ..)` method takes [dfsdm_ch7datinr::W](dfsdm_ch7datinr::W) writer structure"] impl crate::Writable for DFSDM_CH7DATINR {} #[doc = "This register contains 16-bit input data to be processed by DFSDM filter module."] pub mod dfsdm_ch7datinr; #[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0cr1](dfsdm_flt0cr1) module"] pub type DFSDM_FLT0CR1 = crate::Reg<u32, _DFSDM_FLT0CR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0CR1; #[doc = "`read()` method returns [dfsdm_flt0cr1::R](dfsdm_flt0cr1::R) reader structure"] impl crate::Readable for DFSDM_FLT0CR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0cr1::W](dfsdm_flt0cr1::W) writer structure"] impl crate::Writable for DFSDM_FLT0CR1 {} #[doc = "DFSDM control register 1"] pub mod dfsdm_flt0cr1; #[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0cr2](dfsdm_flt0cr2) module"] pub type DFSDM_FLT0CR2 = crate::Reg<u32, _DFSDM_FLT0CR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0CR2; #[doc = "`read()` method returns [dfsdm_flt0cr2::R](dfsdm_flt0cr2::R) reader structure"] impl crate::Readable for DFSDM_FLT0CR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0cr2::W](dfsdm_flt0cr2::W) writer structure"] impl crate::Writable for DFSDM_FLT0CR2 {} #[doc = "DFSDM control register 2"] pub mod dfsdm_flt0cr2; #[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0isr](dfsdm_flt0isr) module"] pub type DFSDM_FLT0ISR = crate::Reg<u32, _DFSDM_FLT0ISR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0ISR; #[doc = "`read()` method returns [dfsdm_flt0isr::R](dfsdm_flt0isr::R) reader structure"] impl crate::Readable for DFSDM_FLT0ISR {} #[doc = "DFSDM interrupt and status register"] pub mod dfsdm_flt0isr; #[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0icr](dfsdm_flt0icr) module"] pub type DFSDM_FLT0ICR = crate::Reg<u32, _DFSDM_FLT0ICR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0ICR; #[doc = "`read()` method returns [dfsdm_flt0icr::R](dfsdm_flt0icr::R) reader structure"] impl crate::Readable for DFSDM_FLT0ICR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0icr::W](dfsdm_flt0icr::W) writer structure"] impl crate::Writable for DFSDM_FLT0ICR {} #[doc = "DFSDM interrupt flag clear register"] pub mod dfsdm_flt0icr; #[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0jchgr](dfsdm_flt0jchgr) module"] pub type DFSDM_FLT0JCHGR = crate::Reg<u32, _DFSDM_FLT0JCHGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0JCHGR; #[doc = "`read()` method returns [dfsdm_flt0jchgr::R](dfsdm_flt0jchgr::R) reader structure"] impl crate::Readable for DFSDM_FLT0JCHGR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0jchgr::W](dfsdm_flt0jchgr::W) writer structure"] impl crate::Writable for DFSDM_FLT0JCHGR {} #[doc = "DFSDM injected channel group selection register"] pub mod dfsdm_flt0jchgr; #[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0fcr](dfsdm_flt0fcr) module"] pub type DFSDM_FLT0FCR = crate::Reg<u32, _DFSDM_FLT0FCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0FCR; #[doc = "`read()` method returns [dfsdm_flt0fcr::R](dfsdm_flt0fcr::R) reader structure"] impl crate::Readable for DFSDM_FLT0FCR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0fcr::W](dfsdm_flt0fcr::W) writer structure"] impl crate::Writable for DFSDM_FLT0FCR {} #[doc = "DFSDM filter control register"] pub mod dfsdm_flt0fcr; #[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0jdatar](dfsdm_flt0jdatar) module"] pub type DFSDM_FLT0JDATAR = crate::Reg<u32, _DFSDM_FLT0JDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0JDATAR; #[doc = "`read()` method returns [dfsdm_flt0jdatar::R](dfsdm_flt0jdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT0JDATAR {} #[doc = "DFSDM data register for injected group"] pub mod dfsdm_flt0jdatar; #[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0rdatar](dfsdm_flt0rdatar) module"] pub type DFSDM_FLT0RDATAR = crate::Reg<u32, _DFSDM_FLT0RDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0RDATAR; #[doc = "`read()` method returns [dfsdm_flt0rdatar::R](dfsdm_flt0rdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT0RDATAR {} #[doc = "DFSDM data register for the regular channel"] pub mod dfsdm_flt0rdatar; #[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0awhtr](dfsdm_flt0awhtr) module"] pub type DFSDM_FLT0AWHTR = crate::Reg<u32, _DFSDM_FLT0AWHTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0AWHTR; #[doc = "`read()` method returns [dfsdm_flt0awhtr::R](dfsdm_flt0awhtr::R) reader structure"] impl crate::Readable for DFSDM_FLT0AWHTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0awhtr::W](dfsdm_flt0awhtr::W) writer structure"] impl crate::Writable for DFSDM_FLT0AWHTR {} #[doc = "DFSDM analog watchdog high threshold register"] pub mod dfsdm_flt0awhtr; #[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0awltr](dfsdm_flt0awltr) module"] pub type DFSDM_FLT0AWLTR = crate::Reg<u32, _DFSDM_FLT0AWLTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0AWLTR; #[doc = "`read()` method returns [dfsdm_flt0awltr::R](dfsdm_flt0awltr::R) reader structure"] impl crate::Readable for DFSDM_FLT0AWLTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0awltr::W](dfsdm_flt0awltr::W) writer structure"] impl crate::Writable for DFSDM_FLT0AWLTR {} #[doc = "DFSDM analog watchdog low threshold register"] pub mod dfsdm_flt0awltr; #[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0awsr](dfsdm_flt0awsr) module"] pub type DFSDM_FLT0AWSR = crate::Reg<u32, _DFSDM_FLT0AWSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0AWSR; #[doc = "`read()` method returns [dfsdm_flt0awsr::R](dfsdm_flt0awsr::R) reader structure"] impl crate::Readable for DFSDM_FLT0AWSR {} #[doc = "DFSDM analog watchdog status register"] pub mod dfsdm_flt0awsr; #[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0awcfr](dfsdm_flt0awcfr) module"] pub type DFSDM_FLT0AWCFR = crate::Reg<u32, _DFSDM_FLT0AWCFR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0AWCFR; #[doc = "`read()` method returns [dfsdm_flt0awcfr::R](dfsdm_flt0awcfr::R) reader structure"] impl crate::Readable for DFSDM_FLT0AWCFR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt0awcfr::W](dfsdm_flt0awcfr::W) writer structure"] impl crate::Writable for DFSDM_FLT0AWCFR {} #[doc = "DFSDM analog watchdog clear flag register"] pub mod dfsdm_flt0awcfr; #[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0exmax](dfsdm_flt0exmax) module"] pub type DFSDM_FLT0EXMAX = crate::Reg<u32, _DFSDM_FLT0EXMAX>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0EXMAX; #[doc = "`read()` method returns [dfsdm_flt0exmax::R](dfsdm_flt0exmax::R) reader structure"] impl crate::Readable for DFSDM_FLT0EXMAX {} #[doc = "DFSDM Extremes detector maximum register"] pub mod dfsdm_flt0exmax; #[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0exmin](dfsdm_flt0exmin) module"] pub type DFSDM_FLT0EXMIN = crate::Reg<u32, _DFSDM_FLT0EXMIN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0EXMIN; #[doc = "`read()` method returns [dfsdm_flt0exmin::R](dfsdm_flt0exmin::R) reader structure"] impl crate::Readable for DFSDM_FLT0EXMIN {} #[doc = "DFSDM Extremes detector minimum register"] pub mod dfsdm_flt0exmin; #[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt0cnvtimr](dfsdm_flt0cnvtimr) module"] pub type DFSDM_FLT0CNVTIMR = crate::Reg<u32, _DFSDM_FLT0CNVTIMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT0CNVTIMR; #[doc = "`read()` method returns [dfsdm_flt0cnvtimr::R](dfsdm_flt0cnvtimr::R) reader structure"] impl crate::Readable for DFSDM_FLT0CNVTIMR {} #[doc = "DFSDM conversion timer register"] pub mod dfsdm_flt0cnvtimr; #[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1cr1](dfsdm_flt1cr1) module"] pub type DFSDM_FLT1CR1 = crate::Reg<u32, _DFSDM_FLT1CR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1CR1; #[doc = "`read()` method returns [dfsdm_flt1cr1::R](dfsdm_flt1cr1::R) reader structure"] impl crate::Readable for DFSDM_FLT1CR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1cr1::W](dfsdm_flt1cr1::W) writer structure"] impl crate::Writable for DFSDM_FLT1CR1 {} #[doc = "DFSDM control register 1"] pub mod dfsdm_flt1cr1; #[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1cr2](dfsdm_flt1cr2) module"] pub type DFSDM_FLT1CR2 = crate::Reg<u32, _DFSDM_FLT1CR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1CR2; #[doc = "`read()` method returns [dfsdm_flt1cr2::R](dfsdm_flt1cr2::R) reader structure"] impl crate::Readable for DFSDM_FLT1CR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1cr2::W](dfsdm_flt1cr2::W) writer structure"] impl crate::Writable for DFSDM_FLT1CR2 {} #[doc = "DFSDM control register 2"] pub mod dfsdm_flt1cr2; #[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1isr](dfsdm_flt1isr) module"] pub type DFSDM_FLT1ISR = crate::Reg<u32, _DFSDM_FLT1ISR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1ISR; #[doc = "`read()` method returns [dfsdm_flt1isr::R](dfsdm_flt1isr::R) reader structure"] impl crate::Readable for DFSDM_FLT1ISR {} #[doc = "DFSDM interrupt and status register"] pub mod dfsdm_flt1isr; #[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1icr](dfsdm_flt1icr) module"] pub type DFSDM_FLT1ICR = crate::Reg<u32, _DFSDM_FLT1ICR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1ICR; #[doc = "`read()` method returns [dfsdm_flt1icr::R](dfsdm_flt1icr::R) reader structure"] impl crate::Readable for DFSDM_FLT1ICR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1icr::W](dfsdm_flt1icr::W) writer structure"] impl crate::Writable for DFSDM_FLT1ICR {} #[doc = "DFSDM interrupt flag clear register"] pub mod dfsdm_flt1icr; #[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1jchgr](dfsdm_flt1jchgr) module"] pub type DFSDM_FLT1JCHGR = crate::Reg<u32, _DFSDM_FLT1JCHGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1JCHGR; #[doc = "`read()` method returns [dfsdm_flt1jchgr::R](dfsdm_flt1jchgr::R) reader structure"] impl crate::Readable for DFSDM_FLT1JCHGR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1jchgr::W](dfsdm_flt1jchgr::W) writer structure"] impl crate::Writable for DFSDM_FLT1JCHGR {} #[doc = "DFSDM injected channel group selection register"] pub mod dfsdm_flt1jchgr; #[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1fcr](dfsdm_flt1fcr) module"] pub type DFSDM_FLT1FCR = crate::Reg<u32, _DFSDM_FLT1FCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1FCR; #[doc = "`read()` method returns [dfsdm_flt1fcr::R](dfsdm_flt1fcr::R) reader structure"] impl crate::Readable for DFSDM_FLT1FCR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1fcr::W](dfsdm_flt1fcr::W) writer structure"] impl crate::Writable for DFSDM_FLT1FCR {} #[doc = "DFSDM filter control register"] pub mod dfsdm_flt1fcr; #[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1jdatar](dfsdm_flt1jdatar) module"] pub type DFSDM_FLT1JDATAR = crate::Reg<u32, _DFSDM_FLT1JDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1JDATAR; #[doc = "`read()` method returns [dfsdm_flt1jdatar::R](dfsdm_flt1jdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT1JDATAR {} #[doc = "DFSDM data register for injected group"] pub mod dfsdm_flt1jdatar; #[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1rdatar](dfsdm_flt1rdatar) module"] pub type DFSDM_FLT1RDATAR = crate::Reg<u32, _DFSDM_FLT1RDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1RDATAR; #[doc = "`read()` method returns [dfsdm_flt1rdatar::R](dfsdm_flt1rdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT1RDATAR {} #[doc = "DFSDM data register for the regular channel"] pub mod dfsdm_flt1rdatar; #[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1awhtr](dfsdm_flt1awhtr) module"] pub type DFSDM_FLT1AWHTR = crate::Reg<u32, _DFSDM_FLT1AWHTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1AWHTR; #[doc = "`read()` method returns [dfsdm_flt1awhtr::R](dfsdm_flt1awhtr::R) reader structure"] impl crate::Readable for DFSDM_FLT1AWHTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1awhtr::W](dfsdm_flt1awhtr::W) writer structure"] impl crate::Writable for DFSDM_FLT1AWHTR {} #[doc = "DFSDM analog watchdog high threshold register"] pub mod dfsdm_flt1awhtr; #[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1awltr](dfsdm_flt1awltr) module"] pub type DFSDM_FLT1AWLTR = crate::Reg<u32, _DFSDM_FLT1AWLTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1AWLTR; #[doc = "`read()` method returns [dfsdm_flt1awltr::R](dfsdm_flt1awltr::R) reader structure"] impl crate::Readable for DFSDM_FLT1AWLTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1awltr::W](dfsdm_flt1awltr::W) writer structure"] impl crate::Writable for DFSDM_FLT1AWLTR {} #[doc = "DFSDM analog watchdog low threshold register"] pub mod dfsdm_flt1awltr; #[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1awsr](dfsdm_flt1awsr) module"] pub type DFSDM_FLT1AWSR = crate::Reg<u32, _DFSDM_FLT1AWSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1AWSR; #[doc = "`read()` method returns [dfsdm_flt1awsr::R](dfsdm_flt1awsr::R) reader structure"] impl crate::Readable for DFSDM_FLT1AWSR {} #[doc = "DFSDM analog watchdog status register"] pub mod dfsdm_flt1awsr; #[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1awcfr](dfsdm_flt1awcfr) module"] pub type DFSDM_FLT1AWCFR = crate::Reg<u32, _DFSDM_FLT1AWCFR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1AWCFR; #[doc = "`read()` method returns [dfsdm_flt1awcfr::R](dfsdm_flt1awcfr::R) reader structure"] impl crate::Readable for DFSDM_FLT1AWCFR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt1awcfr::W](dfsdm_flt1awcfr::W) writer structure"] impl crate::Writable for DFSDM_FLT1AWCFR {} #[doc = "DFSDM analog watchdog clear flag register"] pub mod dfsdm_flt1awcfr; #[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1exmax](dfsdm_flt1exmax) module"] pub type DFSDM_FLT1EXMAX = crate::Reg<u32, _DFSDM_FLT1EXMAX>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1EXMAX; #[doc = "`read()` method returns [dfsdm_flt1exmax::R](dfsdm_flt1exmax::R) reader structure"] impl crate::Readable for DFSDM_FLT1EXMAX {} #[doc = "DFSDM Extremes detector maximum register"] pub mod dfsdm_flt1exmax; #[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1exmin](dfsdm_flt1exmin) module"] pub type DFSDM_FLT1EXMIN = crate::Reg<u32, _DFSDM_FLT1EXMIN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1EXMIN; #[doc = "`read()` method returns [dfsdm_flt1exmin::R](dfsdm_flt1exmin::R) reader structure"] impl crate::Readable for DFSDM_FLT1EXMIN {} #[doc = "DFSDM Extremes detector minimum register"] pub mod dfsdm_flt1exmin; #[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt1cnvtimr](dfsdm_flt1cnvtimr) module"] pub type DFSDM_FLT1CNVTIMR = crate::Reg<u32, _DFSDM_FLT1CNVTIMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT1CNVTIMR; #[doc = "`read()` method returns [dfsdm_flt1cnvtimr::R](dfsdm_flt1cnvtimr::R) reader structure"] impl crate::Readable for DFSDM_FLT1CNVTIMR {} #[doc = "DFSDM conversion timer register"] pub mod dfsdm_flt1cnvtimr; #[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2cr1](dfsdm_flt2cr1) module"] pub type DFSDM_FLT2CR1 = crate::Reg<u32, _DFSDM_FLT2CR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2CR1; #[doc = "`read()` method returns [dfsdm_flt2cr1::R](dfsdm_flt2cr1::R) reader structure"] impl crate::Readable for DFSDM_FLT2CR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2cr1::W](dfsdm_flt2cr1::W) writer structure"] impl crate::Writable for DFSDM_FLT2CR1 {} #[doc = "DFSDM control register 1"] pub mod dfsdm_flt2cr1; #[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2cr2](dfsdm_flt2cr2) module"] pub type DFSDM_FLT2CR2 = crate::Reg<u32, _DFSDM_FLT2CR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2CR2; #[doc = "`read()` method returns [dfsdm_flt2cr2::R](dfsdm_flt2cr2::R) reader structure"] impl crate::Readable for DFSDM_FLT2CR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2cr2::W](dfsdm_flt2cr2::W) writer structure"] impl crate::Writable for DFSDM_FLT2CR2 {} #[doc = "DFSDM control register 2"] pub mod dfsdm_flt2cr2; #[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2isr](dfsdm_flt2isr) module"] pub type DFSDM_FLT2ISR = crate::Reg<u32, _DFSDM_FLT2ISR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2ISR; #[doc = "`read()` method returns [dfsdm_flt2isr::R](dfsdm_flt2isr::R) reader structure"] impl crate::Readable for DFSDM_FLT2ISR {} #[doc = "DFSDM interrupt and status register"] pub mod dfsdm_flt2isr; #[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2icr](dfsdm_flt2icr) module"] pub type DFSDM_FLT2ICR = crate::Reg<u32, _DFSDM_FLT2ICR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2ICR; #[doc = "`read()` method returns [dfsdm_flt2icr::R](dfsdm_flt2icr::R) reader structure"] impl crate::Readable for DFSDM_FLT2ICR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2icr::W](dfsdm_flt2icr::W) writer structure"] impl crate::Writable for DFSDM_FLT2ICR {} #[doc = "DFSDM interrupt flag clear register"] pub mod dfsdm_flt2icr; #[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2jchgr](dfsdm_flt2jchgr) module"] pub type DFSDM_FLT2JCHGR = crate::Reg<u32, _DFSDM_FLT2JCHGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2JCHGR; #[doc = "`read()` method returns [dfsdm_flt2jchgr::R](dfsdm_flt2jchgr::R) reader structure"] impl crate::Readable for DFSDM_FLT2JCHGR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2jchgr::W](dfsdm_flt2jchgr::W) writer structure"] impl crate::Writable for DFSDM_FLT2JCHGR {} #[doc = "DFSDM injected channel group selection register"] pub mod dfsdm_flt2jchgr; #[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2fcr](dfsdm_flt2fcr) module"] pub type DFSDM_FLT2FCR = crate::Reg<u32, _DFSDM_FLT2FCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2FCR; #[doc = "`read()` method returns [dfsdm_flt2fcr::R](dfsdm_flt2fcr::R) reader structure"] impl crate::Readable for DFSDM_FLT2FCR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2fcr::W](dfsdm_flt2fcr::W) writer structure"] impl crate::Writable for DFSDM_FLT2FCR {} #[doc = "DFSDM filter control register"] pub mod dfsdm_flt2fcr; #[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2jdatar](dfsdm_flt2jdatar) module"] pub type DFSDM_FLT2JDATAR = crate::Reg<u32, _DFSDM_FLT2JDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2JDATAR; #[doc = "`read()` method returns [dfsdm_flt2jdatar::R](dfsdm_flt2jdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT2JDATAR {} #[doc = "DFSDM data register for injected group"] pub mod dfsdm_flt2jdatar; #[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2rdatar](dfsdm_flt2rdatar) module"] pub type DFSDM_FLT2RDATAR = crate::Reg<u32, _DFSDM_FLT2RDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2RDATAR; #[doc = "`read()` method returns [dfsdm_flt2rdatar::R](dfsdm_flt2rdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT2RDATAR {} #[doc = "DFSDM data register for the regular channel"] pub mod dfsdm_flt2rdatar; #[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2awhtr](dfsdm_flt2awhtr) module"] pub type DFSDM_FLT2AWHTR = crate::Reg<u32, _DFSDM_FLT2AWHTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2AWHTR; #[doc = "`read()` method returns [dfsdm_flt2awhtr::R](dfsdm_flt2awhtr::R) reader structure"] impl crate::Readable for DFSDM_FLT2AWHTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2awhtr::W](dfsdm_flt2awhtr::W) writer structure"] impl crate::Writable for DFSDM_FLT2AWHTR {} #[doc = "DFSDM analog watchdog high threshold register"] pub mod dfsdm_flt2awhtr; #[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2awltr](dfsdm_flt2awltr) module"] pub type DFSDM_FLT2AWLTR = crate::Reg<u32, _DFSDM_FLT2AWLTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2AWLTR; #[doc = "`read()` method returns [dfsdm_flt2awltr::R](dfsdm_flt2awltr::R) reader structure"] impl crate::Readable for DFSDM_FLT2AWLTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2awltr::W](dfsdm_flt2awltr::W) writer structure"] impl crate::Writable for DFSDM_FLT2AWLTR {} #[doc = "DFSDM analog watchdog low threshold register"] pub mod dfsdm_flt2awltr; #[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2awsr](dfsdm_flt2awsr) module"] pub type DFSDM_FLT2AWSR = crate::Reg<u32, _DFSDM_FLT2AWSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2AWSR; #[doc = "`read()` method returns [dfsdm_flt2awsr::R](dfsdm_flt2awsr::R) reader structure"] impl crate::Readable for DFSDM_FLT2AWSR {} #[doc = "DFSDM analog watchdog status register"] pub mod dfsdm_flt2awsr; #[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2awcfr](dfsdm_flt2awcfr) module"] pub type DFSDM_FLT2AWCFR = crate::Reg<u32, _DFSDM_FLT2AWCFR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2AWCFR; #[doc = "`read()` method returns [dfsdm_flt2awcfr::R](dfsdm_flt2awcfr::R) reader structure"] impl crate::Readable for DFSDM_FLT2AWCFR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt2awcfr::W](dfsdm_flt2awcfr::W) writer structure"] impl crate::Writable for DFSDM_FLT2AWCFR {} #[doc = "DFSDM analog watchdog clear flag register"] pub mod dfsdm_flt2awcfr; #[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2exmax](dfsdm_flt2exmax) module"] pub type DFSDM_FLT2EXMAX = crate::Reg<u32, _DFSDM_FLT2EXMAX>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2EXMAX; #[doc = "`read()` method returns [dfsdm_flt2exmax::R](dfsdm_flt2exmax::R) reader structure"] impl crate::Readable for DFSDM_FLT2EXMAX {} #[doc = "DFSDM Extremes detector maximum register"] pub mod dfsdm_flt2exmax; #[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2exmin](dfsdm_flt2exmin) module"] pub type DFSDM_FLT2EXMIN = crate::Reg<u32, _DFSDM_FLT2EXMIN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2EXMIN; #[doc = "`read()` method returns [dfsdm_flt2exmin::R](dfsdm_flt2exmin::R) reader structure"] impl crate::Readable for DFSDM_FLT2EXMIN {} #[doc = "DFSDM Extremes detector minimum register"] pub mod dfsdm_flt2exmin; #[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt2cnvtimr](dfsdm_flt2cnvtimr) module"] pub type DFSDM_FLT2CNVTIMR = crate::Reg<u32, _DFSDM_FLT2CNVTIMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT2CNVTIMR; #[doc = "`read()` method returns [dfsdm_flt2cnvtimr::R](dfsdm_flt2cnvtimr::R) reader structure"] impl crate::Readable for DFSDM_FLT2CNVTIMR {} #[doc = "DFSDM conversion timer register"] pub mod dfsdm_flt2cnvtimr; #[doc = "DFSDM control register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3cr1](dfsdm_flt3cr1) module"] pub type DFSDM_FLT3CR1 = crate::Reg<u32, _DFSDM_FLT3CR1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3CR1; #[doc = "`read()` method returns [dfsdm_flt3cr1::R](dfsdm_flt3cr1::R) reader structure"] impl crate::Readable for DFSDM_FLT3CR1 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3cr1::W](dfsdm_flt3cr1::W) writer structure"] impl crate::Writable for DFSDM_FLT3CR1 {} #[doc = "DFSDM control register 1"] pub mod dfsdm_flt3cr1; #[doc = "DFSDM control register 2\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3cr2](dfsdm_flt3cr2) module"] pub type DFSDM_FLT3CR2 = crate::Reg<u32, _DFSDM_FLT3CR2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3CR2; #[doc = "`read()` method returns [dfsdm_flt3cr2::R](dfsdm_flt3cr2::R) reader structure"] impl crate::Readable for DFSDM_FLT3CR2 {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3cr2::W](dfsdm_flt3cr2::W) writer structure"] impl crate::Writable for DFSDM_FLT3CR2 {} #[doc = "DFSDM control register 2"] pub mod dfsdm_flt3cr2; #[doc = "DFSDM interrupt and status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3isr](dfsdm_flt3isr) module"] pub type DFSDM_FLT3ISR = crate::Reg<u32, _DFSDM_FLT3ISR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3ISR; #[doc = "`read()` method returns [dfsdm_flt3isr::R](dfsdm_flt3isr::R) reader structure"] impl crate::Readable for DFSDM_FLT3ISR {} #[doc = "DFSDM interrupt and status register"] pub mod dfsdm_flt3isr; #[doc = "DFSDM interrupt flag clear register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3icr](dfsdm_flt3icr) module"] pub type DFSDM_FLT3ICR = crate::Reg<u32, _DFSDM_FLT3ICR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3ICR; #[doc = "`read()` method returns [dfsdm_flt3icr::R](dfsdm_flt3icr::R) reader structure"] impl crate::Readable for DFSDM_FLT3ICR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3icr::W](dfsdm_flt3icr::W) writer structure"] impl crate::Writable for DFSDM_FLT3ICR {} #[doc = "DFSDM interrupt flag clear register"] pub mod dfsdm_flt3icr; #[doc = "DFSDM injected channel group selection register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3jchgr](dfsdm_flt3jchgr) module"] pub type DFSDM_FLT3JCHGR = crate::Reg<u32, _DFSDM_FLT3JCHGR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3JCHGR; #[doc = "`read()` method returns [dfsdm_flt3jchgr::R](dfsdm_flt3jchgr::R) reader structure"] impl crate::Readable for DFSDM_FLT3JCHGR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3jchgr::W](dfsdm_flt3jchgr::W) writer structure"] impl crate::Writable for DFSDM_FLT3JCHGR {} #[doc = "DFSDM injected channel group selection register"] pub mod dfsdm_flt3jchgr; #[doc = "DFSDM filter control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3fcr](dfsdm_flt3fcr) module"] pub type DFSDM_FLT3FCR = crate::Reg<u32, _DFSDM_FLT3FCR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3FCR; #[doc = "`read()` method returns [dfsdm_flt3fcr::R](dfsdm_flt3fcr::R) reader structure"] impl crate::Readable for DFSDM_FLT3FCR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3fcr::W](dfsdm_flt3fcr::W) writer structure"] impl crate::Writable for DFSDM_FLT3FCR {} #[doc = "DFSDM filter control register"] pub mod dfsdm_flt3fcr; #[doc = "DFSDM data register for injected group\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3jdatar](dfsdm_flt3jdatar) module"] pub type DFSDM_FLT3JDATAR = crate::Reg<u32, _DFSDM_FLT3JDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3JDATAR; #[doc = "`read()` method returns [dfsdm_flt3jdatar::R](dfsdm_flt3jdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT3JDATAR {} #[doc = "DFSDM data register for injected group"] pub mod dfsdm_flt3jdatar; #[doc = "DFSDM data register for the regular channel\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3rdatar](dfsdm_flt3rdatar) module"] pub type DFSDM_FLT3RDATAR = crate::Reg<u32, _DFSDM_FLT3RDATAR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3RDATAR; #[doc = "`read()` method returns [dfsdm_flt3rdatar::R](dfsdm_flt3rdatar::R) reader structure"] impl crate::Readable for DFSDM_FLT3RDATAR {} #[doc = "DFSDM data register for the regular channel"] pub mod dfsdm_flt3rdatar; #[doc = "DFSDM analog watchdog high threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3awhtr](dfsdm_flt3awhtr) module"] pub type DFSDM_FLT3AWHTR = crate::Reg<u32, _DFSDM_FLT3AWHTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3AWHTR; #[doc = "`read()` method returns [dfsdm_flt3awhtr::R](dfsdm_flt3awhtr::R) reader structure"] impl crate::Readable for DFSDM_FLT3AWHTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3awhtr::W](dfsdm_flt3awhtr::W) writer structure"] impl crate::Writable for DFSDM_FLT3AWHTR {} #[doc = "DFSDM analog watchdog high threshold register"] pub mod dfsdm_flt3awhtr; #[doc = "DFSDM analog watchdog low threshold register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3awltr](dfsdm_flt3awltr) module"] pub type DFSDM_FLT3AWLTR = crate::Reg<u32, _DFSDM_FLT3AWLTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3AWLTR; #[doc = "`read()` method returns [dfsdm_flt3awltr::R](dfsdm_flt3awltr::R) reader structure"] impl crate::Readable for DFSDM_FLT3AWLTR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3awltr::W](dfsdm_flt3awltr::W) writer structure"] impl crate::Writable for DFSDM_FLT3AWLTR {} #[doc = "DFSDM analog watchdog low threshold register"] pub mod dfsdm_flt3awltr; #[doc = "DFSDM analog watchdog status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3awsr](dfsdm_flt3awsr) module"] pub type DFSDM_FLT3AWSR = crate::Reg<u32, _DFSDM_FLT3AWSR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3AWSR; #[doc = "`read()` method returns [dfsdm_flt3awsr::R](dfsdm_flt3awsr::R) reader structure"] impl crate::Readable for DFSDM_FLT3AWSR {} #[doc = "DFSDM analog watchdog status register"] pub mod dfsdm_flt3awsr; #[doc = "DFSDM analog watchdog clear flag register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3awcfr](dfsdm_flt3awcfr) module"] pub type DFSDM_FLT3AWCFR = crate::Reg<u32, _DFSDM_FLT3AWCFR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3AWCFR; #[doc = "`read()` method returns [dfsdm_flt3awcfr::R](dfsdm_flt3awcfr::R) reader structure"] impl crate::Readable for DFSDM_FLT3AWCFR {} #[doc = "`write(|w| ..)` method takes [dfsdm_flt3awcfr::W](dfsdm_flt3awcfr::W) writer structure"] impl crate::Writable for DFSDM_FLT3AWCFR {} #[doc = "DFSDM analog watchdog clear flag register"] pub mod dfsdm_flt3awcfr; #[doc = "DFSDM Extremes detector maximum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3exmax](dfsdm_flt3exmax) module"] pub type DFSDM_FLT3EXMAX = crate::Reg<u32, _DFSDM_FLT3EXMAX>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3EXMAX; #[doc = "`read()` method returns [dfsdm_flt3exmax::R](dfsdm_flt3exmax::R) reader structure"] impl crate::Readable for DFSDM_FLT3EXMAX {} #[doc = "DFSDM Extremes detector maximum register"] pub mod dfsdm_flt3exmax; #[doc = "DFSDM Extremes detector minimum register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3exmin](dfsdm_flt3exmin) module"] pub type DFSDM_FLT3EXMIN = crate::Reg<u32, _DFSDM_FLT3EXMIN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3EXMIN; #[doc = "`read()` method returns [dfsdm_flt3exmin::R](dfsdm_flt3exmin::R) reader structure"] impl crate::Readable for DFSDM_FLT3EXMIN {} #[doc = "DFSDM Extremes detector minimum register"] pub mod dfsdm_flt3exmin; #[doc = "DFSDM conversion timer register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dfsdm_flt3cnvtimr](dfsdm_flt3cnvtimr) module"] pub type DFSDM_FLT3CNVTIMR = crate::Reg<u32, _DFSDM_FLT3CNVTIMR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DFSDM_FLT3CNVTIMR; #[doc = "`read()` method returns [dfsdm_flt3cnvtimr::R](dfsdm_flt3cnvtimr::R) reader structure"] impl crate::Readable for DFSDM_FLT3CNVTIMR {} #[doc = "DFSDM conversion timer register"] pub mod dfsdm_flt3cnvtimr;
pub mod api_type;
use std::{ ops::{Mul,Neg}, mem, }; use crate::{ traits::*, vector::*, }; use serde::{Serialize, Deserialize}; pub use float_cmp::{Ulps,ApproxEq}; macro_rules! implement_one_to_one_assign_method { (fn $method_name:ident -> $type:ident { $($member:ident),* }) => { pub fn $method_name($($member: T),*) -> Self { $type { $($member: $member),* } } } } macro_rules! implement_matrix { ($matrix_type:ident { dim: $dim:expr, vector_type: $vector_type:ident, cols: { $($c_num:expr => $c:ident { $($ce_num:expr => $m_col_element:ident: $col_vec_member:ident),*}),* }, rows: { $($r_num:expr => $r:ident { $($re_num:expr => $m_row_element:ident: $row_vec_member:ident),* }),* } }) => { #[repr(C)] #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct $matrix_type<T: Base> { $($(pub $m_col_element: T),*),* } impl<T: Base> $matrix_type<T> { #[inline] pub fn dims() -> usize { ($({let $c = 1; $c} +)* 0) } implement_one_to_one_assign_method!( fn from_components_row_major -> $matrix_type { $($($m_row_element),*),* } ); implement_one_to_one_assign_method!( fn from_components_col_major -> $matrix_type { $($($m_col_element),*),* } ); pub fn from_cols($($c: $vector_type<T>),*) -> Self { $matrix_type::from_components_col_major($($($c.$col_vec_member),*),*) } pub fn from_rows($($r: $vector_type<T>),*) -> Self { $matrix_type::from_components_row_major($($($r.$row_vec_member),*),*) } pub fn transpose(&self) -> Self { $matrix_type::from_components_row_major($($(self.$m_col_element),*),*) } pub fn col(&self, index: usize) -> $vector_type<T> { match index { $($c_num => $vector_type::new( $(self.$m_col_element),* ),)* _ => panic!("index out of range"), } } pub fn row(&self, index: usize) -> $vector_type<T> { match index { $($r_num => $vector_type::new( $(self.$m_row_element),* ),)* _ => panic!("index out of range") } } pub fn set_col_elem(&mut self, col_index: usize, elem_index: usize, value: T) { self.as_array()[col_index*$dim + elem_index] = value; } pub fn identity() -> Self { $matrix_type::from_diagonal($vector_type::one()) } fn from_value(value: T) -> Self { $matrix_type::from_components_col_major($($({ let $m_col_element = value; $m_col_element}),*),*) } pub fn zero() -> Self { $matrix_type::from_value(T::zero()) } pub fn one() -> Self { $matrix_type::from_value(T::one()) } #[inline] pub fn to_array(&self) -> [T; $dim*$dim] { unsafe { mem::transmute_copy(self) } } } // m * m implement_binary_operator!(Mul<$matrix_type<T>> for $matrix_type<T>, fn mul(lhs, rhs) -> $matrix_type<T> { unsafe { let mut res: $matrix_type<T> = mem::uninitialized(); for r in 0..$dim { for c in 0..$dim { let col = rhs.col(c); let row = lhs.row(r); res.set_col_elem(c, r, col.dot(row)); } } res } } ); // m * v implement_binary_operator!(Mul<$vector_type<T>> for $matrix_type<T>, fn mul(lhs, rhs) -> $vector_type<T> { $vector_type::new( $(lhs.row($r_num).dot(rhs)),* ) } ); impl<'a, T: Base> AsArray for &'a $matrix_type<T> { type Output = &'a [T; $dim*$dim]; #[inline] fn as_array(self) -> Self::Output { unsafe { mem::transmute(self) } } } impl<'a, T: Base> AsArray for &'a mut $matrix_type<T> { type Output = &'a mut [T; $dim*$dim]; #[inline] fn as_array(self) -> Self::Output { unsafe { mem::transmute(self) } } } impl<'a, T: Base> AsArrays for &'a $matrix_type<T> { type Output = &'a [[T; $dim]; $dim]; #[inline] fn as_arrays(self) -> Self::Output { unsafe { mem::transmute(self) } } } impl<'a, T: Base> AsArrays for &'a mut $matrix_type<T> { type Output = &'a mut [[T; $dim]; $dim]; #[inline] fn as_arrays(self) -> Self::Output { unsafe { mem::transmute(self) } } } impl<T: Base> MatrixAccess for $matrix_type<T> { type Output = T; #[inline] fn col_elem(self, col_index: usize, elem_index: usize) -> Self::Output { self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem(self, row_index: usize, elem_index: usize) -> Self::Output { self.as_array()[elem_index*$dim + row_index] } } impl<'a, T: Base> MatrixAccess for &'a $matrix_type<T> { type Output = T; #[inline] fn col_elem(self, col_index: usize, elem_index: usize) -> Self::Output { self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem(self, row_index: usize, elem_index: usize) -> Self::Output { self.as_array()[elem_index*$dim + row_index] } } impl<'a, T: Base> MatrixAccess for &'a mut $matrix_type<T> { type Output = T; #[inline] fn col_elem(self, col_index: usize, elem_index: usize) -> Self::Output { self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem(self, row_index: usize, elem_index: usize) -> Self::Output { self.as_array()[elem_index*$dim + row_index] } } impl<'a, T: Base> MatrixAccessRef<'a> for &'a $matrix_type<T> { type Output = T; #[inline] fn col_elem_ref(self, col_index: usize, elem_index: usize) -> &'a Self::Output { &self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem_ref(self, row_index: usize, elem_index: usize) -> &'a Self::Output { &self.as_array()[elem_index*$dim + row_index] } } impl<'a, T: Base> MatrixAccessRef<'a> for &'a mut $matrix_type<T> { type Output = T; #[inline] fn col_elem_ref(self, col_index: usize, elem_index: usize) -> &'a Self::Output { &self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem_ref(self, row_index: usize, elem_index: usize) -> &'a Self::Output { &self.as_array()[elem_index*$dim + row_index] } } impl<'a, T: Base> MatrixAccessMut<'a> for &'a mut $matrix_type<T> { type Output = T; #[inline] fn col_elem_mut(self, col_index: usize, elem_index: usize) -> &'a mut Self::Output { &mut self.as_array()[col_index*$dim + elem_index] } #[inline] fn row_elem_mut(self, row_index: usize, elem_index: usize) -> &'a mut Self::Output { &mut self.as_array()[elem_index*$dim + row_index] } } impl<T: BaseFloat> ApproxEq for $matrix_type<T> where T: ApproxEq<Flt=T> { type Flt = T; #[inline] fn approx_eq(&self, other: &Self, epsilon: T, ulps: <T as Ulps>::U) -> bool { //$($(self.$m_col_element.approx_eq(&other.$m_col_element, epsilon, ulps))&&*)&&* for i in 0..$dim*$dim { if !self.as_array()[i].approx_eq(&other.as_array()[i], epsilon, ulps) { return false; } } return true; } } } } implement_matrix!( Matrix2 { dim: 2, vector_type: Vector2, cols: { 0 => c0 { 0 => m00: x, 1 => m10: y }, 1 => c1 { 0 => m01: x, 1 => m11: y } }, rows: { 0 => r0 { 0 => m00: x, 1 => m01: y }, 1 => r1 { 0 => m10: x, 1 => m11: y } } } ); implement_matrix!( Matrix3 { dim: 3, vector_type: Vector3, cols: { 0 => c0 { 0 => m00: x, 1 => m10: y, 2 => m20: z }, 1 => c1 { 0 => m01: x, 1 => m11: y, 2 => m21: z }, 2 => c2 { 0 => m02: x, 1 => m12: y, 2 => m22: z } }, rows: { 0 => r0 { 0 => m00: x, 1 => m01: y, 2 => m02: z }, 1 => r1 { 0 => m10: x, 1 => m11: y, 2 => m12: z }, 2 => r2 { 0 => m20: x, 1 => m21: y, 2 => m22: z } } } ); implement_matrix!( Matrix4 { dim: 4, vector_type: Vector4, cols: { 0 => c0 { 0 => m00: x, 1 => m10: y, 2 => m20: z, 3 => m30: w }, 1 => c1 { 0 => m01: x, 1 => m11: y, 2 => m21: z, 3 => m31: w }, 2 => c2 { 0 => m02: x, 1 => m12: y, 2 => m22: z, 3 => m32: w }, 3 => c3 { 0 => m03: x, 1 => m13: y, 2 => m23: z, 3 => m33: w } }, rows: { 0 => r0 { 0 => m00: x, 1 => m01: y, 2 => m02: z, 3 => m03: w }, 1 => r1 { 0 => m10: x, 1 => m11: y, 2 => m12: z, 3 => m13: w }, 2 => r2 { 0 => m20: x, 1 => m21: y, 2 => m22: z, 3 => m23: w }, 3 => r3 { 0 => m30: x, 1 => m31: y, 2 => m32: z, 3 => m33: w } } } ); impl<T: Base> Matrix2<T> { pub fn from_diagonal(d: Vector2<T>) -> Self { Matrix2::from_components_row_major( d.x, T::zero(), T::zero(), d.y , ) } } impl<T: Base> Matrix3<T> { pub fn from_diagonal(d: Vector3<T>) -> Self { Matrix3::from_components_row_major( d.x, T::zero(), T::zero(), T::zero(), d.y , T::zero(), T::zero(), T::zero(), d.z , ) } } impl<T: Base> Matrix4<T> { pub fn from_diagonal(d: Vector4<T>) -> Self { Matrix4::from_components_row_major( d.x, T::zero(), T::zero(), T::zero(), T::zero(), d.y , T::zero(), T::zero(), T::zero(), T::zero(), d.z , T::zero(), T::zero(), T::zero(), T::zero(), d.w , ) } } impl<T: Base + Neg<Output=T>> Matrix3<T> { pub fn det(&self) -> T { let m = |r,c| self.row_elem(r, c); m(0, 0) * m(1, 1) * m(2, 2) + m(0, 1) * m(1, 2) * m(2, 0) + m(0, 2) * m(1, 0) * m(2, 1) - m(2, 0) * m(1, 1) * m(0, 2) - m(2, 1) * m(1, 2) * m(0, 0) - m(2, 2) * m(1, 0) * m(0, 1) } pub fn inverse(&self) -> Option<Self> { let det = self.det(); if det == T::zero() { // TODO(henk): How to compare? None } else { let d = T::one() / det; let m = |r,c| self.row_elem(r, c); Some(Matrix3::from_components_row_major( d*(m(1, 1) * m(2, 2) - m(1, 2) * m(2, 1)), d*(m(0, 2) * m(2, 1) - m(0, 1) * m(2, 2)), d*(m(0, 1) * m(1, 2) - m(0, 2) * m(1, 1)), d*(m(1, 2) * m(2, 0) - m(1, 0) * m(2, 2)), d*(m(0, 0) * m(2, 2) - m(0, 2) * m(2, 0)), d*(m(0, 2) * m(1, 0) - m(0, 0) * m(1, 2)), d*(m(1, 0) * m(2, 1) - m(1, 1) * m(2, 0)), d*(m(0, 1) * m(2, 0) - m(0, 0) * m(2, 1)), d*(m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0)) )) } } } impl<T: BaseFloat + ApproxEq<Flt=T>> Matrix4<T> { pub fn inverse(&self) -> Option<Self> { let (m00, m01, m02, m03) = (self.row_elem(0, 0), self.row_elem(0, 1), self.row_elem(0, 2), self.row_elem(0, 3)); let (m10, m11, m12, m13) = (self.row_elem(1, 0), self.row_elem(1, 1), self.row_elem(1, 2), self.row_elem(1, 3)); let (m20, m21, m22, m23) = (self.row_elem(2, 0), self.row_elem(2, 1), self.row_elem(2, 2), self.row_elem(2, 3)); let (m30, m31, m32, m33) = (self.row_elem(3, 0), self.row_elem(3, 1), self.row_elem(3, 2), self.row_elem(3, 3)); let d = T::one() / self.det(); // TODO: Test for zero! Some(Self::from_components_row_major( d*(m11*m22*m33 + m12*m23*m31 + m13*m21*m32 - m11*m23*m32 - m12*m21*m33 - m13*m22*m31), d*(m01*m23*m32 + m02*m21*m33 + m03*m22*m31 - m01*m22*m33 - m02*m23*m31 - m03*m21*m32), d*(m01*m12*m33 + m02*m13*m31 + m03*m11*m32 - m01*m13*m32 - m02*m11*m33 - m03*m12*m31), d*(m01*m13*m22 + m02*m11*m23 + m03*m12*m21 - m01*m12*m23 - m02*m13*m21 - m03*m11*m22), d*(m10*m23*m32 + m12*m20*m33 + m13*m22*m30 - m10*m22*m33 - m12*m23*m30 - m13*m20*m32), d*(m00*m22*m33 + m02*m23*m30 + m03*m20*m32 - m00*m23*m32 - m02*m20*m33 - m03*m22*m30), d*(m00*m13*m32 + m02*m10*m33 + m03*m12*m30 - m00*m12*m33 - m02*m13*m30 - m03*m10*m32), d*(m00*m12*m23 + m02*m13*m20 + m03*m10*m22 - m00*m13*m22 - m02*m10*m23 - m03*m12*m20), d*(m10*m21*m33 + m11*m23*m30 + m13*m20*m31 - m10*m23*m31 - m11*m20*m33 - m13*m21*m30), d*(m00*m23*m31 + m01*m20*m33 + m03*m21*m30 - m00*m21*m33 - m01*m23*m30 - m03*m20*m31), d*(m00*m11*m33 + m01*m13*m30 + m03*m10*m31 - m00*m13*m31 - m01*m10*m33 - m03*m11*m30), d*(m00*m13*m21 + m01*m10*m23 + m03*m11*m20 - m00*m11*m23 - m01*m13*m20 - m03*m10*m21), d*(m10*m22*m31 + m11*m20*m32 + m12*m21*m30 - m10*m21*m32 - m11*m22*m30 - m12*m20*m31), d*(m00*m21*m32 + m01*m22*m30 + m02*m20*m31 - m00*m22*m31 - m01*m20*m32 - m02*m21*m30), d*(m00*m12*m31 + m01*m10*m32 + m02*m11*m30 - m00*m11*m32 - m01*m12*m30 - m02*m10*m31), d*(m00*m11*m22 + m01*m12*m20 + m02*m10*m21 - m00*m12*m21 - m01*m10*m22 - m02*m11*m20) )) } } impl<T: Base + Neg<Output=T>> Matrix4<T> { pub fn det(&self) -> T { let (m00, m01, m02, m03) = (self.row_elem(0, 0), self.row_elem(0, 1), self.row_elem(0, 2), self.row_elem(0, 3)); let (m10, m11, m12, m13) = (self.row_elem(1, 0), self.row_elem(1, 1), self.row_elem(1, 2), self.row_elem(1, 3)); let (m20, m21, m22, m23) = (self.row_elem(2, 0), self.row_elem(2, 1), self.row_elem(2, 2), self.row_elem(2, 3)); let (m30, m31, m32, m33) = (self.row_elem(3, 0), self.row_elem(3, 1), self.row_elem(3, 2), self.row_elem(3, 3)); m00*m11*m22*m33 + m00*m12*m23*m31 + m00*m13*m21*m32 + m01*m10*m23*m32 + m01*m12*m20*m33 + m01*m13*m22*m30 + m02*m10*m21*m33 + m02*m11*m23*m30 + m02*m13*m20*m31 + m03*m10*m22*m31 + m03*m11*m20*m32 + m03*m12*m21*m30 - m00*m11*m23*m32 - m00*m12*m21*m33 - m00*m13*m22*m31 - m01*m10*m22*m33 - m01*m12*m23*m30 - m01*m13*m20*m32 - m02*m10*m23*m31 - m02*m11*m20*m33 - m02*m13*m21*m30 - m03*m10*m21*m32 - m03*m11*m22*m30 - m03*m12*m20*m31 } pub fn inverse1(&self) -> Option<Self> { let det = self.det(); if det == T::zero() { // TODO(henk): How to compare None } else { let d = T::one() / det; let m = |r,c| self.row_elem(r, c); Some(Matrix4::from_components_row_major( d*(m(1, 1) * m(2, 2) * m(3, 3) + m(2, 1) * m(3, 2) * m(1, 3) + m(3, 1) * m(1, 2) * m(2, 3) - m(1, 1) * m(3, 2) * m(2, 3) - m(2, 1) * m(1, 2) * m(3, 3) - m(3, 1) * m(2, 2) * m(1, 3)), d*(m(1, 0) * m(3, 2) * m(2, 3) + m(2, 0) * m(1, 2) * m(3, 3) + m(3, 0) * m(2, 2) * m(1, 3) - m(1, 0) * m(2, 2) * m(3, 3) - m(2, 0) * m(3, 2) * m(1, 3) - m(3, 0) * m(1, 2) * m(2, 3)), d*(m(1, 0) * m(2, 1) * m(3, 3) + m(2, 0) * m(3, 1) * m(1, 3) + m(3, 0) * m(1, 1) * m(2, 3) - m(1, 0) * m(3, 1) * m(2, 3) - m(2, 0) * m(1, 1) * m(3, 3) - m(3, 0) * m(2, 1) * m(1, 3)), d*(m(1, 0) * m(3, 1) * m(2, 2) + m(2, 0) * m(1, 1) * m(3, 2) + m(3, 0) * m(2, 1) * m(1, 2) - m(1, 0) * m(2, 1) * m(3, 2) - m(2, 0) * m(3, 1) * m(1, 2) - m(3, 0) * m(1, 1) * m(2, 2)), d*(m(0, 1) * m(3, 2) * m(2, 3) + m(2, 1) * m(0, 2) * m(3, 3) + m(3, 1) * m(2, 2) * m(0, 3) - m(0, 1) * m(2, 2) * m(3, 3) - m(2, 1) * m(3, 2) * m(0, 3) - m(3, 1) * m(0, 2) * m(2, 3)), d*(m(0, 0) * m(2, 2) * m(3, 3) + m(2, 0) * m(3, 2) * m(0, 3) + m(3, 0) * m(0, 2) * m(2, 3) - m(0, 0) * m(3, 2) * m(2, 3) - m(2, 0) * m(0, 2) * m(3, 3) - m(3, 0) * m(2, 2) * m(0, 3)), d*(m(0, 0) * m(3, 1) * m(2, 3) + m(2, 0) * m(0, 1) * m(3, 3) + m(3, 0) * m(2, 1) * m(0, 3) - m(0, 0) * m(2, 1) * m(3, 3) - m(2, 0) * m(3, 1) * m(0, 3) - m(3, 0) * m(0, 1) * m(2, 3)), d*(m(0, 0) * m(2, 1) * m(3, 2) + m(2, 0) * m(3, 1) * m(0, 2) + m(3, 0) * m(0, 1) * m(2, 2) - m(0, 0) * m(3, 1) * m(2, 2) - m(2, 0) * m(0, 1) * m(3, 2) - m(3, 0) * m(2, 1) * m(0, 2)), d*(m(0, 1) * m(1, 2) * m(3, 3) + m(1, 1) * m(3, 2) * m(0, 3) + m(3, 1) * m(0, 2) * m(1, 3) - m(0, 1) * m(3, 2) * m(1, 3) - m(1, 1) * m(0, 2) * m(3, 3) - m(3, 1) * m(1, 2) * m(0, 3)), d*(m(0, 0) * m(3, 2) * m(1, 3) + m(1, 0) * m(0, 2) * m(3, 3) + m(3, 0) * m(1, 2) * m(0, 3) - m(0, 0) * m(1, 2) * m(3, 3) - m(1, 0) * m(3, 2) * m(0, 3) - m(3, 0) * m(0, 2) * m(1, 3)), d*(m(0, 0) * m(1, 1) * m(3, 3) + m(1, 0) * m(3, 1) * m(0, 3) + m(3, 0) * m(0, 1) * m(1, 3) - m(0, 0) * m(3, 1) * m(1, 3) - m(1, 0) * m(0, 1) * m(3, 3) - m(3, 0) * m(1, 1) * m(0, 3)), d*(m(0, 0) * m(3, 1) * m(1, 2) + m(1, 0) * m(0, 1) * m(3, 2) + m(3, 0) * m(1, 1) * m(0, 2) - m(0, 0) * m(1, 1) * m(3, 2) - m(1, 0) * m(3, 1) * m(0, 2) - m(3, 0) * m(0, 1) * m(1, 2)), d*(m(0, 1) * m(2, 2) * m(1, 3) + m(1, 1) * m(0, 2) * m(2, 3) + m(2, 1) * m(1, 2) * m(0, 3) - m(0, 1) * m(1, 2) * m(2, 3) - m(1, 1) * m(2, 2) * m(0, 3) - m(2, 1) * m(0, 2) * m(1, 3)), d*(m(0, 0) * m(1, 2) * m(2, 3) + m(1, 0) * m(2, 2) * m(0, 3) + m(2, 0) * m(0, 2) * m(1, 3) - m(0, 0) * m(2, 2) * m(1, 3) - m(1, 0) * m(0, 2) * m(2, 3) - m(2, 0) * m(1, 2) * m(0, 3)), d*(m(0, 0) * m(2, 1) * m(1, 3) + m(1, 0) * m(0, 1) * m(2, 3) + m(2, 0) * m(1, 1) * m(0, 3) - m(0, 0) * m(1, 1) * m(2, 3) - m(1, 0) * m(2, 1) * m(0, 3) - m(2, 0) * m(0, 1) * m(1, 3)), d*(m(0, 0) * m(1, 1) * m(2, 2) + m(1, 0) * m(2, 1) * m(0, 2) + m(2, 0) * m(0, 1) * m(1, 2) - m(0, 0) * m(2, 1) * m(1, 2) - m(1, 0) * m(0, 1) * m(2, 2) - m(2, 0) * m(1, 1) * m(0, 2)) )) } } } impl<T: BaseFloat> Matrix3<T> { pub fn new_normal_matrix(model_matrix: &Matrix3<T>) -> Option<Self> { if let Some(inv) = model_matrix.inverse() { Some(Matrix3::from(inv.transpose())) } else { None } } } impl<T: BaseFloat> From<Matrix4<T>> for Matrix3<T> { fn from(m: Matrix4<T>) -> Self { Matrix3::from_components_row_major( m.m00, m.m01, m.m02, m.m10, m.m11, m.m12, m.m20, m.m21, m.m22 ) } } impl<T: BaseFloat> Matrix4<T> { pub fn new_translation(x: T, y: T, z: T) -> Self { Matrix4::from_components_row_major( T::one() , T::zero(), T::zero(), x, T::zero(), T::one() , T::zero(), y, T::zero(), T::zero(), T::one() , z, T::zero(), T::zero(), T::zero(), T::one() ) } pub fn new_translation_from_vector(v: Vector3<T>) -> Self { Self::new_translation(v.x, v.y, v.z) } pub fn new_scale(x: T, y: T, z: T) -> Self { Matrix4::from_components_row_major( x , T::zero(), T::zero(), T::zero(), T::zero(), y , T::zero(), T::zero(), T::zero(), T::zero(), z , T::zero(), T::zero(), T::zero(), T::zero(), T::one(), ) } pub fn new_scale_from_vector(v: Vector3<T>) -> Self { Self::new_scale(v.x, v.y, v.z) } pub fn new_scale_uniform(s: T) -> Self { Self::new_scale(s, s, s) } pub fn new_rotation(axis: Vector3<T>, angle: T) -> Self { let cos_a = T::cos(angle); let sin_a = T::sin(angle); let k = T::one() - cos_a; Matrix4::from_components_row_major( axis.x * axis.x * k + cos_a , axis.x * axis.y * k - axis.z * sin_a, axis.x * axis.z * k + axis.y * sin_a, T::zero(), axis.y * axis.x * k + axis.z * sin_a, axis.y * axis.y * k + cos_a , axis.y * axis.z * k - axis.x * sin_a, T::zero(), axis.z * axis.x * k - axis.y * sin_a, axis.z * axis.y * k + axis.x * sin_a, axis.z * axis.z * k + cos_a , T::zero(), T::zero() , T::zero() , T::zero() , T::one() ) } pub fn new_rotation_x(angle: T) -> Self { Matrix4::from_components_row_major( T::one() , T::zero() , T::zero() , T::zero(), T::zero(), T::cos(angle), -T::sin(angle), T::zero(), T::zero(), T::sin(angle), T::cos(angle), T::zero(), T::zero(), T::zero() , T::zero() , T::one() ) } pub fn new_rotation_y(angle: T) -> Self { Matrix4::from_components_row_major( T::cos(angle), T::zero(), T::sin(angle), T::zero(), T::zero() , T::one() , T::zero() , T::zero(), -T::sin(angle), T::zero(), T::cos(angle), T::zero(), T::zero() , T::zero(), T::zero() , T::one() ) } pub fn new_rotation_z(angle: T) -> Self { Matrix4::from_components_row_major( T::cos(angle), -T::sin(angle), T::zero(), T::zero(), T::sin(angle), T::cos(angle), T::zero(), T::zero(), T::zero() , T::zero() , T::one() , T::zero(), T::zero() , T::zero() , T::zero(), T::one() ) } pub fn new_perspective_from_bounds(left: T, right: T, bottom: T, top: T, z_near: T, z_far: T) -> Self { let two = T::one() + T::one(); let w = right - left; let h = top - bottom; let d = z_far - z_near; Matrix4::from_components_row_major( two * z_near / w, T::zero() , (right + left) / w , T::zero(), T::zero() , two * z_near / h, (top + bottom) / h , T::zero(), T::zero() , T::zero() , -(z_far + z_near) / d, -two * z_far*z_near / d, T::zero() , T::zero() , -T::one() , T::zero() ) } pub fn new_perspective_from_fov(fov: T, aspect: T, z_near: T, z_far: T) -> Self { let pi = T::from(::std::f32::consts::PI).unwrap(); let circ = T::from(360.0).unwrap(); let right = z_near * T::tan(fov * pi / circ); let left = -right; let top = right / aspect; let bottom = -top; Self::new_perspective_from_bounds(left, right, bottom, top, z_near, z_far) } pub fn new_orthographic_from_bounds(left: T, right: T, bottom: T, top: T, z_near: T, z_far: T) -> Self { let two = T::one() + T::one(); let w = right - left; let h = top - bottom; let d = z_far - z_near; Matrix4::from_components_row_major( two / w , T::zero(), T::zero(), -(right + left) / w, T::zero(), two / h , T::zero(), -(top + bottom) / h, T::zero(), T::zero(), -two / d , -(z_far + z_near) / d, T::zero(), T::zero(), T::zero(), T::one() ) } pub fn new_orthographic_from_dimensions(width: T, height: T, z_near: T, z_far: T) -> Self { let two = T::one() + T::one(); let d = z_far - z_near; Matrix4::from_components_row_major( two / width, T::zero() , T::zero(), T::zero(), T::zero() , two / height, T::zero(), T::zero(), T::zero() , T::zero() , -two / d , -(z_far + z_near) / d, T::zero() , T::zero() , T::zero(), T::one() ) } pub fn new_look_at(eye: Vector3<T>, target: Vector3<T>, up: Vector3<T>) -> Self { let f = (target - eye).normalize(); let s = f.cross(up).normalize(); let u = s.cross(f).normalize(); Matrix4::from_components_row_major( s.x , s.y , s.z , -(s.x * eye.x + s.y * eye.y + s.z * eye.z), u.x , u.y , u.z , -(u.x * eye.x + u.y * eye.y + u.z * eye.z), -f.x , -f.y , -f.z , f.x * eye.x + f.y * eye.y + f.z * eye.z , T::zero(), T::zero(), T::zero(), T::one() ) } }
use crate::domain::entities::{Pokemon, PokemonName, PokemonNumber, PokemonTypes}; pub enum Insert { Ok(PokemonNumber), Conflict, Error, } pub trait Repository { fn insert(&mut self, number: PokemonNumber, name: PokemonName, types: PokemonTypes) -> Insert; } pub struct InMemoryRepository { error: bool, pokemons: Vec<Pokemon>, } impl InMemoryRepository { pub fn new() -> Self { let pokemons: Vec<Pokemon> = vec![]; Self { error: false, pokemons, } } pub fn with_error(self) -> Self { Self { error: true, ..self } } } impl Repository for InMemoryRepository { fn insert(&mut self, number: PokemonNumber, name: PokemonName, types: PokemonTypes) -> Insert { if self.error { return Insert::Error; } if self.pokemons.iter().any(|pokemon| pokemon.number == number) { return Insert::Conflict; } self.pokemons.push(Pokemon::new(number, name, types)); Insert::Ok(number) } }
#[macro_use] pub extern crate serde_derive; pub extern crate serde; pub extern crate serde_json; mod complex; mod complexop; mod entity; mod entityop; pub mod enumtypes; pub mod entitytypes { pub use crate::entity::*; pub use crate::entityop::*; } pub mod complextypes { pub use crate::complex::*; pub use crate::complexop::*; }
mod document; mod filler; use actix_web::dev::BodyEncoding; use actix_web::http::{header::ACCEPT, ContentEncoding}; use actix_web::{web, HttpResponse}; use serde::Serialize; use crate::services::filler::compiler; #[derive(Serialize)] struct WsMessage { message: String, } #[derive(Serialize)] struct WsError { error: String, } pub fn config(cfg: &mut web::ServiceConfig) { document::config(cfg); filler::config(cfg); } pub fn get_accepted_header(request: &web::HttpRequest) -> Option<String> { if let Some(accept) = request.headers().get(ACCEPT) { let accept = accept.to_str().unwrap_or("").to_lowercase(); if accept.as_str() == mime::APPLICATION_PDF || accept.as_str() == mime::APPLICATION_OCTET_STREAM { Some(accept) } else { None } } else { None } } pub fn export_content<S: AsRef<str>>( accept: S, export_result: compiler::ExportCompilerResult<Vec<u8>>, ) -> HttpResponse { match export_result { Ok(bytes) => HttpResponse::Ok() .encoding(ContentEncoding::Identity) .content_type(accept.as_ref()) .append_header(("accept-ranges", "bytes")) .append_header(( "content-disposition", format!( "attachment; filename=\"pdf.{}\"", if accept.as_ref() != mime::APPLICATION_PDF { "zip" } else { "pdf" } ), )) .body(bytes), Err(compiler::ExportCompilerError::GenericError(message)) => { HttpResponse::InternalServerError().json(WsError { error: message }) } } }
#[doc = "Register `CFGR1` reader"] pub type R = crate::R<CFGR1_SPEC>; #[doc = "Register `CFGR1` writer"] pub type W = crate::W<CFGR1_SPEC>; #[doc = "Field `TS1_EN` reader - Temperature sensor 1 enable bit This bit is set and cleared by software. Note: Once enabled, the temperature sensor is active after a specific delay time. The TS1_RDY flag will be set when the sensor is ready."] pub type TS1_EN_R = crate::BitReader; #[doc = "Field `TS1_EN` writer - Temperature sensor 1 enable bit This bit is set and cleared by software. Note: Once enabled, the temperature sensor is active after a specific delay time. The TS1_RDY flag will be set when the sensor is ready."] pub type TS1_EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TS1_START` reader - Start frequency measurement on temperature sensor 1 This bit is set and cleared by software."] pub type TS1_START_R = crate::BitReader; #[doc = "Field `TS1_START` writer - Start frequency measurement on temperature sensor 1 This bit is set and cleared by software."] pub type TS1_START_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TS1_INTRIG_SEL` reader - Input trigger selection bit for temperature sensor 1 These bits are set and cleared by software. They select which input triggers a temperature measurement. Refer to Section 19.3.10: Trigger input."] pub type TS1_INTRIG_SEL_R = crate::FieldReader; #[doc = "Field `TS1_INTRIG_SEL` writer - Input trigger selection bit for temperature sensor 1 These bits are set and cleared by software. They select which input triggers a temperature measurement. Refer to Section 19.3.10: Trigger input."] pub type TS1_INTRIG_SEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `TS1_SMP_TIME` reader - Sampling time for temperature sensor 1 These bits allow increasing the sampling time to improve measurement precision. When the PCLK clock is selected as reference clock (REFCLK_SEL = 0), the measurement will be performed at TS1_SMP_TIME period of CLK_PTAT. When the LSE is selected as reference clock (REFCLK_SEL =1), the measurement will be performed at TS1_SMP_TIME period of LSE."] pub type TS1_SMP_TIME_R = crate::FieldReader; #[doc = "Field `TS1_SMP_TIME` writer - Sampling time for temperature sensor 1 These bits allow increasing the sampling time to improve measurement precision. When the PCLK clock is selected as reference clock (REFCLK_SEL = 0), the measurement will be performed at TS1_SMP_TIME period of CLK_PTAT. When the LSE is selected as reference clock (REFCLK_SEL =1), the measurement will be performed at TS1_SMP_TIME period of LSE."] pub type TS1_SMP_TIME_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `REFCLK_SEL` reader - Reference clock selection bit This bit is set and cleared by software. It indicates whether the reference clock is the high speed clock (PCLK) or the low speed clock (LSE)."] pub type REFCLK_SEL_R = crate::BitReader; #[doc = "Field `REFCLK_SEL` writer - Reference clock selection bit This bit is set and cleared by software. It indicates whether the reference clock is the high speed clock (PCLK) or the low speed clock (LSE)."] pub type REFCLK_SEL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `Q_MEAS_OPT` reader - Quick measurement option bit This bit is set and cleared by software. It is used to increase the measurement speed by suppressing the calibration step. It is effective only when the LSE clock is used as reference clock (REFCLK_SEL=1)."] pub type Q_MEAS_OPT_R = crate::BitReader; #[doc = "Field `Q_MEAS_OPT` writer - Quick measurement option bit This bit is set and cleared by software. It is used to increase the measurement speed by suppressing the calibration step. It is effective only when the LSE clock is used as reference clock (REFCLK_SEL=1)."] pub type Q_MEAS_OPT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `HSREF_CLK_DIV` reader - High speed clock division ratio These bits are set and cleared by software. They can be used to define the division ratio for the main clock in order to obtain the internal frequency lower than 1 MHz required for the calibration. They are applicable only for calibration when PCLK is selected as reference clock (REFCLK_SEL=0). ..."] pub type HSREF_CLK_DIV_R = crate::FieldReader; #[doc = "Field `HSREF_CLK_DIV` writer - High speed clock division ratio These bits are set and cleared by software. They can be used to define the division ratio for the main clock in order to obtain the internal frequency lower than 1 MHz required for the calibration. They are applicable only for calibration when PCLK is selected as reference clock (REFCLK_SEL=0). ..."] pub type HSREF_CLK_DIV_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>; impl R { #[doc = "Bit 0 - Temperature sensor 1 enable bit This bit is set and cleared by software. Note: Once enabled, the temperature sensor is active after a specific delay time. The TS1_RDY flag will be set when the sensor is ready."] #[inline(always)] pub fn ts1_en(&self) -> TS1_EN_R { TS1_EN_R::new((self.bits & 1) != 0) } #[doc = "Bit 4 - Start frequency measurement on temperature sensor 1 This bit is set and cleared by software."] #[inline(always)] pub fn ts1_start(&self) -> TS1_START_R { TS1_START_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bits 8:11 - Input trigger selection bit for temperature sensor 1 These bits are set and cleared by software. They select which input triggers a temperature measurement. Refer to Section 19.3.10: Trigger input."] #[inline(always)] pub fn ts1_intrig_sel(&self) -> TS1_INTRIG_SEL_R { TS1_INTRIG_SEL_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:19 - Sampling time for temperature sensor 1 These bits allow increasing the sampling time to improve measurement precision. When the PCLK clock is selected as reference clock (REFCLK_SEL = 0), the measurement will be performed at TS1_SMP_TIME period of CLK_PTAT. When the LSE is selected as reference clock (REFCLK_SEL =1), the measurement will be performed at TS1_SMP_TIME period of LSE."] #[inline(always)] pub fn ts1_smp_time(&self) -> TS1_SMP_TIME_R { TS1_SMP_TIME_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bit 20 - Reference clock selection bit This bit is set and cleared by software. It indicates whether the reference clock is the high speed clock (PCLK) or the low speed clock (LSE)."] #[inline(always)] pub fn refclk_sel(&self) -> REFCLK_SEL_R { REFCLK_SEL_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Quick measurement option bit This bit is set and cleared by software. It is used to increase the measurement speed by suppressing the calibration step. It is effective only when the LSE clock is used as reference clock (REFCLK_SEL=1)."] #[inline(always)] pub fn q_meas_opt(&self) -> Q_MEAS_OPT_R { Q_MEAS_OPT_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bits 24:30 - High speed clock division ratio These bits are set and cleared by software. They can be used to define the division ratio for the main clock in order to obtain the internal frequency lower than 1 MHz required for the calibration. They are applicable only for calibration when PCLK is selected as reference clock (REFCLK_SEL=0). ..."] #[inline(always)] pub fn hsref_clk_div(&self) -> HSREF_CLK_DIV_R { HSREF_CLK_DIV_R::new(((self.bits >> 24) & 0x7f) as u8) } } impl W { #[doc = "Bit 0 - Temperature sensor 1 enable bit This bit is set and cleared by software. Note: Once enabled, the temperature sensor is active after a specific delay time. The TS1_RDY flag will be set when the sensor is ready."] #[inline(always)] #[must_use] pub fn ts1_en(&mut self) -> TS1_EN_W<CFGR1_SPEC, 0> { TS1_EN_W::new(self) } #[doc = "Bit 4 - Start frequency measurement on temperature sensor 1 This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn ts1_start(&mut self) -> TS1_START_W<CFGR1_SPEC, 4> { TS1_START_W::new(self) } #[doc = "Bits 8:11 - Input trigger selection bit for temperature sensor 1 These bits are set and cleared by software. They select which input triggers a temperature measurement. Refer to Section 19.3.10: Trigger input."] #[inline(always)] #[must_use] pub fn ts1_intrig_sel(&mut self) -> TS1_INTRIG_SEL_W<CFGR1_SPEC, 8> { TS1_INTRIG_SEL_W::new(self) } #[doc = "Bits 16:19 - Sampling time for temperature sensor 1 These bits allow increasing the sampling time to improve measurement precision. When the PCLK clock is selected as reference clock (REFCLK_SEL = 0), the measurement will be performed at TS1_SMP_TIME period of CLK_PTAT. When the LSE is selected as reference clock (REFCLK_SEL =1), the measurement will be performed at TS1_SMP_TIME period of LSE."] #[inline(always)] #[must_use] pub fn ts1_smp_time(&mut self) -> TS1_SMP_TIME_W<CFGR1_SPEC, 16> { TS1_SMP_TIME_W::new(self) } #[doc = "Bit 20 - Reference clock selection bit This bit is set and cleared by software. It indicates whether the reference clock is the high speed clock (PCLK) or the low speed clock (LSE)."] #[inline(always)] #[must_use] pub fn refclk_sel(&mut self) -> REFCLK_SEL_W<CFGR1_SPEC, 20> { REFCLK_SEL_W::new(self) } #[doc = "Bit 21 - Quick measurement option bit This bit is set and cleared by software. It is used to increase the measurement speed by suppressing the calibration step. It is effective only when the LSE clock is used as reference clock (REFCLK_SEL=1)."] #[inline(always)] #[must_use] pub fn q_meas_opt(&mut self) -> Q_MEAS_OPT_W<CFGR1_SPEC, 21> { Q_MEAS_OPT_W::new(self) } #[doc = "Bits 24:30 - High speed clock division ratio These bits are set and cleared by software. They can be used to define the division ratio for the main clock in order to obtain the internal frequency lower than 1 MHz required for the calibration. They are applicable only for calibration when PCLK is selected as reference clock (REFCLK_SEL=0). ..."] #[inline(always)] #[must_use] pub fn hsref_clk_div(&mut self) -> HSREF_CLK_DIV_W<CFGR1_SPEC, 24> { HSREF_CLK_DIV_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 = "Temperature sensor configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr1::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 [`cfgr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CFGR1_SPEC; impl crate::RegisterSpec for CFGR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cfgr1::R`](R) reader structure"] impl crate::Readable for CFGR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`cfgr1::W`](W) writer structure"] impl crate::Writable for CFGR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CFGR1 to value 0"] impl crate::Resettable for CFGR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
use yew::{*, prelude::*, services::ConsoleService}; use yew_geolocation::*; use derive_new::*; fn main() { yew::initialize(); App::<Model>::new().mount_to_body(); yew::run_loop(); } #[derive(Debug)] enum Msg { GetPosition, StartWatchingPosition, StopWatchingPosition, CurPosition(Position), PositionChanged(Position), PositionError(PositionError), } #[derive(new)] struct Model { link: ComponentLink<Model>, #[new(default)] geolocation_service: GeolocationService, #[new(value = "ConsoleService::new()")] console: ConsoleService, #[new(default)] watch_task: Option<WatchPositionTask>, #[new(default)] pos_history: Vec<Position>, #[new(default)] cur_pos: Option<Position>, } impl Component for Model { type Message = Msg; type Properties = (); fn create(_props: (), link: ComponentLink<Self>) -> Self { Self::new(link) } fn update(&mut self, msg: Self::Message) -> ShouldRender { self.console.log(&format!("msg: {:?}", msg)); let error_cb = self.link.send_back(Msg::PositionError); let options = PositionOptions { enable_high_accuracy: true, timeout_ms: 10000, ..Default::default() }; use self::Msg::*; match msg { GetPosition => self.geolocation_service.get_current_position(self.link.send_back(Msg::CurPosition), Some(error_cb), Some(options)), StartWatchingPosition => self.watch_task = Some(self.geolocation_service.watch_position(self.link.send_back(Msg::PositionChanged), Some(error_cb), Some(options))), StopWatchingPosition => self.watch_task = None, CurPosition(p) => self.cur_pos = Some(p), PositionChanged(p) => self.pos_history.push(p), PositionError(e) => self.console.error(&e.message), } true } } impl Renderable<Model> for Model { fn view(&self) -> Html<Self> { let render_pos = |p: &Position| html! { <p>{ p.coords.latitude } {", "} { p.coords.longitude }</p> }; html! { <> <button onclick=|_| Msg::GetPosition,>{ "call getCurrentPosition()" }</button> <p>{ "Result from getCurrentPosition:" }</p> { self.cur_pos.as_ref().map_or_else(|| html! { <></> }, render_pos) } <hr/> <button onclick=|_| Msg::StartWatchingPosition, disabled=self.watch_task.is_some(),>{ "Start Watching Position" }</button> <button onclick=|_| Msg::StopWatchingPosition, disabled=self.watch_task.is_none(),>{ "Stop Watching Position" }</button> <p>{ "Position history from watching:" }</p> { for self.pos_history.iter().map(render_pos) } <hr/> </> } } }
use crate::bindings::*; use std::time::Instant; use std::{io, mem::size_of, time::Duration}; fn self_host() -> u32 { unsafe { mach_host_self() } } /// logic processor number pub fn processor_numbers() -> io::Result<i32> { let host = self_host(); let flavor = HOST_BASIC_INFO as i32; let mut host_info_ = host_basic_info::default(); let mut host_info_cnt = size_of::<host_basic_info>() as u32; let ret = unsafe { host_info( host, flavor, (&mut host_info_ as *mut host_basic_info) as *mut i32, &mut host_info_cnt, ) }; if ret != KERN_SUCCESS as i32 { return Err(io::Error::from_raw_os_error(ret)); } Ok(host_info_.logical_cpu) } fn get_thread_basic_info(tid: u32) -> io::Result<thread_basic_info> { let flavor = THREAD_BASIC_INFO; let mut thread_basic_info_ = thread_basic_info::default(); let mut thread_info_cnt = size_of::<thread_basic_info>() as u32; let ret = unsafe { thread_info( tid, flavor, (&mut thread_basic_info_ as *mut thread_basic_info) as *mut i32, &mut thread_info_cnt, ) }; if ret != KERN_SUCCESS as i32 { return Err(io::Error::from_raw_os_error(ret)); } Ok(thread_basic_info_) } pub struct ThreadStat { tid: u32, stat: (thread_basic_info, Instant), } impl ThreadStat { pub fn cur() -> io::Result<Self> { Self::build(cur_thread_id()?) } pub fn build(tid: u32) -> io::Result<Self> { Ok(ThreadStat { tid, stat: (get_thread_basic_info(tid)?, Instant::now()), }) } /// unnormalized pub fn cpu(&mut self) -> io::Result<f64> { let (last_stat, last_time) = self.stat; let cur_stat = get_thread_basic_info(self.tid)?; let cur_time = Instant::now(); let cur_user_time = time_value_to_u64(cur_stat.user_time); let cur_sys_time = time_value_to_u64(cur_stat.system_time); let last_user_time = time_value_to_u64(last_stat.user_time); let last_sys_time = time_value_to_u64(last_stat.system_time); let dt_duration = cur_time - last_time; let cpu_time_us = cur_user_time + cur_sys_time - last_user_time - last_sys_time; let dt_wtime = Duration::from_micros(cpu_time_us); self.stat = (cur_stat, cur_time); Ok(dt_wtime.as_micros() as f64 / dt_duration.as_micros() as f64) } pub fn cpu_time(&mut self) -> io::Result<Duration> { let cur_stat = get_thread_basic_info(self.tid)?; let cur_user_time = time_value_to_u64(cur_stat.user_time); let cur_sys_time = time_value_to_u64(cur_stat.system_time); let last_user_time = time_value_to_u64(self.stat.0.user_time); let last_sys_time = time_value_to_u64(self.stat.0.system_time); let cpu_time_us = cur_user_time + cur_sys_time - last_user_time - last_sys_time; let cpu_time = Duration::from_micros(cpu_time_us); self.stat = (cur_stat, Instant::now()); Ok(cpu_time) } } #[inline] fn time_value_to_u64(t: time_value) -> u64 { (t.seconds as u64) * 1_000_000u64 + (t.microseconds as u64) } #[inline] pub fn cur_thread_id() -> io::Result<u32> { Ok(unsafe { mach_thread_self() }) } // The `clock_gettime` is not supported in older version of mac/ios before 2016, so `getrusage` is used instead. // // `times` is not used, becasuse it's returning value is clock ticks instead of time, lowwer accuracy, different with other platform and deprecated. // // `getrusage` is about 100ns slowwer than `clock_Gettime` each round. pub fn cpu_time() -> io::Result<Duration> { let mut time = unsafe { std::mem::zeroed() }; if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut time) } == 0 { let sec = time.ru_utime.tv_sec as u64 + time.ru_stime.tv_sec as u64; let nsec = (time.ru_utime.tv_usec as u32 + time.ru_stime.tv_usec as u32) * 1000; Ok(Duration::new(sec, nsec)) } else { Err(io::Error::last_os_error()) } } #[cfg(test)] #[allow(clippy::all, clippy::print_stdout)] mod tests { use super::*; use test::Bencher; #[test] fn test_processor_num() { let t = processor_numbers().unwrap(); println!("processor num: {:?}", t); assert!(t >= 1); } // There is a field named `cpu_usage` in `thread_basic_info` which represents the CPU usage of the thread. // However, we have no idea about how long the interval is. And it will make the API being different from other platforms. // We calculate the usage instead of using the field directory to make the API is the same on all platforms. // The cost of the calculation is very very small according to the result of the following benchmark. #[bench] fn bench_cpu_usage_by_calculate(b: &mut Bencher) { let tid = cur_thread_id().unwrap(); let last_stat = get_thread_basic_info(tid).unwrap(); let last_time = Instant::now(); b.iter(|| { let cur_stat = get_thread_basic_info(tid).unwrap(); let cur_time = Instant::now(); let cur_user_time = time_value_to_u64(cur_stat.user_time); let cur_sys_time = time_value_to_u64(cur_stat.system_time); let last_user_time = time_value_to_u64(last_stat.user_time); let last_sys_time = time_value_to_u64(last_stat.system_time); let dt_duration = cur_time - last_time; let cpu_time_us = cur_user_time + cur_sys_time - last_user_time - last_sys_time; let dt_wtime = Duration::from_micros(cpu_time_us); let _ = (cur_stat, cur_time); let _ = dt_wtime.as_micros() as f64 / dt_duration.as_micros() as f64; }); } #[bench] fn bench_cpu_usage_by_field(b: &mut Bencher) { let tid = cur_thread_id().unwrap(); b.iter(|| { let cur_stat = get_thread_basic_info(tid).unwrap(); let _ = cur_stat.cpu_usage / 1000; }); } }
#[doc = "Register `IOPENR` reader"] pub type R = crate::R<IOPENR_SPEC>; #[doc = "Register `IOPENR` writer"] pub type W = crate::W<IOPENR_SPEC>; #[doc = "Field `GPIOAEN` reader - I/O port A clock enable This bit is set and cleared by software."] pub type GPIOAEN_R = crate::BitReader; #[doc = "Field `GPIOAEN` writer - I/O port A clock enable This bit is set and cleared by software."] pub type GPIOAEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GPIOBEN` reader - I/O port B clock enable This bit is set and cleared by software."] pub type GPIOBEN_R = crate::BitReader; #[doc = "Field `GPIOBEN` writer - I/O port B clock enable This bit is set and cleared by software."] pub type GPIOBEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GPIOCEN` reader - I/O port C clock enable This bit is set and cleared by software."] pub type GPIOCEN_R = crate::BitReader; #[doc = "Field `GPIOCEN` writer - I/O port C clock enable This bit is set and cleared by software."] pub type GPIOCEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GPIODEN` reader - I/O port D clock enable This bit is set and cleared by software."] pub type GPIODEN_R = crate::BitReader; #[doc = "Field `GPIODEN` writer - I/O port D clock enable This bit is set and cleared by software."] pub type GPIODEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GPIOFEN` reader - I/O port F clock enable This bit is set and cleared by software."] pub type GPIOFEN_R = crate::BitReader; #[doc = "Field `GPIOFEN` writer - I/O port F clock enable This bit is set and cleared by software."] pub type GPIOFEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - I/O port A clock enable This bit is set and cleared by software."] #[inline(always)] pub fn gpioaen(&self) -> GPIOAEN_R { GPIOAEN_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - I/O port B clock enable This bit is set and cleared by software."] #[inline(always)] pub fn gpioben(&self) -> GPIOBEN_R { GPIOBEN_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - I/O port C clock enable This bit is set and cleared by software."] #[inline(always)] pub fn gpiocen(&self) -> GPIOCEN_R { GPIOCEN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - I/O port D clock enable This bit is set and cleared by software."] #[inline(always)] pub fn gpioden(&self) -> GPIODEN_R { GPIODEN_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 5 - I/O port F clock enable This bit is set and cleared by software."] #[inline(always)] pub fn gpiofen(&self) -> GPIOFEN_R { GPIOFEN_R::new(((self.bits >> 5) & 1) != 0) } } impl W { #[doc = "Bit 0 - I/O port A clock enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn gpioaen(&mut self) -> GPIOAEN_W<IOPENR_SPEC, 0> { GPIOAEN_W::new(self) } #[doc = "Bit 1 - I/O port B clock enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn gpioben(&mut self) -> GPIOBEN_W<IOPENR_SPEC, 1> { GPIOBEN_W::new(self) } #[doc = "Bit 2 - I/O port C clock enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn gpiocen(&mut self) -> GPIOCEN_W<IOPENR_SPEC, 2> { GPIOCEN_W::new(self) } #[doc = "Bit 3 - I/O port D clock enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn gpioden(&mut self) -> GPIODEN_W<IOPENR_SPEC, 3> { GPIODEN_W::new(self) } #[doc = "Bit 5 - I/O port F clock enable This bit is set and cleared by software."] #[inline(always)] #[must_use] pub fn gpiofen(&mut self) -> GPIOFEN_W<IOPENR_SPEC, 5> { GPIOFEN_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 = "RCC I/O port clock enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`iopenr::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 [`iopenr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IOPENR_SPEC; impl crate::RegisterSpec for IOPENR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`iopenr::R`](R) reader structure"] impl crate::Readable for IOPENR_SPEC {} #[doc = "`write(|w| ..)` method takes [`iopenr::W`](W) writer structure"] impl crate::Writable for IOPENR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets IOPENR to value 0"] impl crate::Resettable for IOPENR_SPEC { const RESET_VALUE: Self::Ux = 0; }
// 2019-03-24 // Créons des fonctions que nous testerons individuellement (test private functions) // C'est un sujet discuté chez les programeurs, tout le monde ne fait pas ça // Une fonction d'addition. Noter qu'elle est privée. fn additionneur(a: i32, b: i32) -> i32 { a + b } // Une fonction +2 qui reprend la fonction d'addition. Celle-ci est publique. pub fn plus_deux(a: i32) -> i32 { additionneur(a, 2) } #[cfg(test)] mod tests { use super::*; // On teste la fonction plus_deux (et, passant, la fonction d'addition) #[test] fn interne() { assert_eq!(4, plus_deux(2)); } #[test] fn exploration() { assert_eq!(2 + 2, 4); } #[test] #[should_panic] fn autre() { panic!("Fait faillir ce test"); } }
pub mod test; pub mod api;
fn main() { // Fetch git tag/commit with `git describe --all --always --long --broken --dirty` let git_commit: String = git_commit(); let cargo_data: String = cargo_data().join("\n"); let output = format!( "Built with git commit {}and cargo configuration\n{}", git_commit, cargo_data ); std::fs::write("target/build_data", output).expect("Unable to write buil_data file"); } fn cmd(comand: &str) -> Option<String> { let parts: Vec<&str> = comand.split_whitespace().collect(); let cmd: &str = parts.first().unwrap(); let args: &[&str] = &parts[1..]; std::process::Command::new(cmd) .args(args) .output() .map(|res| String::from_utf8(res.stdout).ok()) .ok() .flatten() } fn git_commit() -> String { cmd("git describe --all --always --long --broken --dirty") .unwrap_or_else(|| String::from("error")) } fn cargo_data() -> Vec<String> { let mut data: Vec<String> = std::env::vars() .filter(|(key, value)| include_env(key) && !value.is_empty()) .map(|(key, value)| format!("{key}={value}")) .collect(); data.sort(); data } fn include_env(key: &str) -> bool { key.starts_with("CARGO") && !CARGO_EXCLUDE.contains(&key) } const CARGO_EXCLUDE: &[&str] = &["CARGO_MANIFEST_DIR", "CARGO_PKG_AUTHORS"];
extern crate libloading; extern crate libc; extern crate encoding; use std::fs; use std::env; use std::os::windows::fs::symlink_file; use std::collections::HashMap; use std::ffi::CString; use libc::*; use libloading::{Library,Symbol}; use encoding::all::GBK; use encoding::{Encoding,EncoderTrap}; struct PDF; type New=unsafe fn()->*const PDF; type BeginDoc=unsafe fn(*const PDF,*const c_char,c_int,*const c_char)->i32; type LoadImage=unsafe fn(*const PDF,*const c_char,*const c_char,c_int,*const c_char)->i32; type Infoimage=unsafe fn(*const PDF,c_int,*const c_char,*const c_char)->c_double; type BeginPage=unsafe fn(*const PDF,c_double,c_double,*const c_char); type FitImage=unsafe fn(*const PDF,c_int,c_double,c_double,*const c_char); type CloseImage=unsafe fn(*const PDF,c_int); type EndPage=unsafe fn(*const PDF,*const c_char); type CreateBookmark =unsafe fn(*const PDF,*const c_char,c_int,*const c_char)->i32; type EndDoc=unsafe fn(*const PDF,*const c_char); fn main(){ let mut arguments = Vec::new(); let mut n=0; for argument in env::args() { arguments.push(argument); n+=1; } if arguments[1]!="" && arguments[2]!=""{ let mut a=env::current_dir().unwrap(); a.push("pdflib.dll"); let lib=Library::new(a).unwrap(); let cd=&arguments[1]; let filn=&arguments[2]; let mut shi:HashMap<i32,&str>=HashMap::new(); shi.insert(1, "一、履历类材料"); shi.insert(2, "二、自传和思想类材料"); shi.insert(3, "三、考核鉴定类材料"); shi.insert(4, "四、学历学位、专业技术职务(职称)、学术评鉴和教育培训类材料"); shi.insert(5, "五、政审、审计和审核类材料"); shi.insert(6, "六、党、团类材料"); shi.insert(7, "七、表彰奖励类材料"); shi.insert(8, "八、违规违纪违法处理处分类材料"); shi.insert(9, "九、工资、任免、出国和会议代表类材料"); shi.insert(10, "十、其他可供组织参考的材料"); if let Ok(dirs) = fs::read_dir(cd) { //人 for path in dirs{ unsafe{ let pdf_new:Symbol<New>=lib.get(b"PDF_new").unwrap(); let pdf_begin_document:Symbol<BeginDoc>=lib.get(b"PDF_begin_document").unwrap(); let pdf_load_image:Symbol<LoadImage>=lib.get(b"PDF_load_image").unwrap(); let pdf_info_image:Symbol<Infoimage>=lib.get(b"PDF_info_image").unwrap(); let pdf_begin_page_ext:Symbol<BeginPage>=lib.get(b"PDF_begin_page_ext").unwrap(); let pdf_fit_image:Symbol<FitImage>=lib.get(b"PDF_fit_image").unwrap(); let pdf_close_image:Symbol<CloseImage>=lib.get(b"PDF_close_image").unwrap(); let pdf_end_page_ext:Symbol<EndPage>=lib.get(b"PDF_end_page_ext").unwrap(); let pdf_create_bookmark:Symbol<CreateBookmark>=lib.get(b"PDF_create_bookmark").unwrap(); let pdf_end_document:Symbol<EndDoc>=lib.get(b"PDF_end_document").unwrap(); if let Ok(path) = path { if path.path().is_dir(){ let p=pdf_new(); let filename=CString::new("temp.pdf").unwrap(); let imagetype=CString::new("jpeg").unwrap(); let iw=CString::new("imagewidth").unwrap(); let ih=CString::new("imageheight").unwrap(); let opt=CString::new("").unwrap(); if n>4{ let psw=CString::new(format!("{} {}",&arguments[3],&arguments[4])).unwrap(); pdf_begin_document(p,filename.as_ptr(),0,psw.as_ptr()); }else{pdf_begin_document(p,filename.as_ptr(),0,opt.as_ptr());} if let Ok(dir) = fs::read_dir(path.path()) { //十 let mut i=1; for _ in dir{ let mut pat=String::from(path.path().to_str().unwrap()); pat.push('/'); pat.push_str(shi.get(&i).unwrap()); //bookmark let bookmark=CString::new(GBK.encode(shi.get(&i).unwrap(),EncoderTrap::Strict).unwrap()).unwrap(); let u= pdf_create_bookmark(p,bookmark.as_ptr(),0,opt.as_ptr()); if let Ok(di) = fs::read_dir(pat) { //一 for pa in di{ if let Ok(pa) = pa { if pa.path().is_dir(){ if let Ok(d) = fs::read_dir(pa.path()) { //2 let f=CString::new(format!("parent={}",u)).unwrap(); //bookmark let bookmark=CString::new(GBK.encode(pa.file_name().to_str().unwrap(),EncoderTrap::Strict).unwrap()).unwrap(); let u2= pdf_create_bookmark(p,bookmark.as_ptr(),0,f.as_ptr()); for a in d{ if let Ok(a) = a { //image let iname=a.file_name(); let sc:Vec<&str>=iname.to_str().unwrap().rsplit(".").collect(); if sc[0]=="jpg"{ symlink_file(a.path(),&iname).unwrap(); let imagename=CString::new(iname.to_str().unwrap()).unwrap(); let j=pdf_load_image(p,imagetype.as_ptr(),imagename.as_ptr(),0,opt.as_ptr()); fs::remove_file(a.file_name()).unwrap(); let w= pdf_info_image(p,j,iw.as_ptr(),opt.as_ptr()); let h=pdf_info_image(p,j,ih.as_ptr(),opt.as_ptr()); if h>w{ pdf_begin_page_ext(p,595.0,842.0,opt.as_ptr()); let adj=CString::new("boxsize={595 842} position=center fitmethod=meet").unwrap(); pdf_fit_image(p,j,0.0,0.0,adj.as_ptr()); pdf_close_image(p,j); }else{ pdf_begin_page_ext(p,842.0,595.0,opt.as_ptr()); let adj=CString::new("boxsize={842 595} position=center fitmethod=meet").unwrap(); pdf_fit_image(p,j,0.0,0.0,adj.as_ptr()); pdf_close_image(p,j); } let f2=CString::new(format!("parent={}",u2)).unwrap(); //bookmark let bookmark=CString::new(GBK.encode(sc[1],EncoderTrap::Strict).unwrap()).unwrap(); pdf_create_bookmark(p,bookmark.as_ptr(),0,f2.as_ptr()); pdf_end_page_ext(p,opt.as_ptr()); } } } } }else{ //image let iname=pa.file_name(); let sc:Vec<&str>=iname.to_str().unwrap().rsplit(".").collect(); if sc[0]=="jpg"{ symlink_file(pa.path(),&iname).unwrap(); let imagename=CString::new(iname.to_str().unwrap()).unwrap(); let j=pdf_load_image(p,imagetype.as_ptr(),imagename.as_ptr(),0,opt.as_ptr()); fs::remove_file(pa.file_name()).unwrap(); let w= pdf_info_image(p,j,iw.as_ptr(),opt.as_ptr()); let h=pdf_info_image(p,j,ih.as_ptr(),opt.as_ptr()); if h>w{ pdf_begin_page_ext(p,595.0,842.0,opt.as_ptr()); let adj=CString::new("boxsize={595 842} position=center fitmethod=meet").unwrap(); pdf_fit_image(p,j,0.0,0.0,adj.as_ptr()); pdf_close_image(p,j); }else{ pdf_begin_page_ext(p,842.0,595.0,opt.as_ptr()); let adj=CString::new("boxsize={842 595} position=center fitmethod=meet").unwrap(); pdf_fit_image(p,j,0.0,0.0,adj.as_ptr()); pdf_close_image(p,j); } let f=CString::new(format!("parent={}",u)).unwrap(); //bookmark let bookmark=CString::new(GBK.encode(sc[1],EncoderTrap::Strict).unwrap()).unwrap(); pdf_create_bookmark(p,bookmark.as_ptr(),0,f.as_ptr()); pdf_end_page_ext(p,opt.as_ptr()); } } } } } i+=1; } } pdf_end_document(p,opt.as_ptr()); let filn=format!("{}{}.pdf",filn,path.file_name().to_str().unwrap()); fs::copy("temp.pdf", filn).unwrap(); fs::remove_file("temp.pdf").unwrap(); } } } } } } }
use std::rc::{Rc}; use std::hash::{Hash, Hasher}; use crate::cell::{ Merge }; use crate::tms::{ TruthManagementSystem, Premise }; use std::ops::{ Add, Sub, Mul, Div }; use core::fmt::Debug; use std::collections::HashSet; #[derive(Debug, Clone, Eq, PartialEq)] pub struct Supported<A> { value: A, premises: HashSet<Premise> } impl<A: Hash> Hash for Supported<A> { fn hash<H>(&self, state: &mut H) where H: Hasher { let mut vec_premises: Vec<&Premise> = self.premises.iter().collect(); vec_premises.sort(); self.value.hash(state); for dependency in vec_premises.iter() { dependency.hash(state); } } } impl<A: Add<Output = A>> Add for Supported<A> { type Output = Supported<A>; fn add(self, other: Self) -> Self { Self { value: self.value + other.value, premises: self.premises.union(&other.premises).cloned().collect() } } } impl<A: Sub<Output = A>> Sub for Supported<A> { type Output = Supported<A>; fn sub(self, other: Self) -> Self { Self { value: self.value - other.value, premises: self.premises.union(&other.premises).cloned().collect() } } } impl<A: Mul<Output = A>> Mul for Supported<A> { type Output = Supported<A>; fn mul(self, other: Self) -> Self { Self { value: self.value * other.value, premises: self.premises.union(&other.premises).cloned().collect() } } } impl<A: Div<Output = A>> Div for Supported<A> { type Output = Supported<A>; fn div(self, other: Self) -> Self { Self { value: self.value / other.value, premises: self.premises.union(&other.premises).cloned().collect() } } } impl<A> Supported<A> { pub fn new(value: A, premises_arr: &[Premise]) -> Self { let mut premises = HashSet::new(); for premise in premises_arr { premises.insert(premise.clone()); } Self { value, premises } } pub fn value(&self) -> &A { &self.value } pub fn premises(&self) -> &HashSet<Premise> { &self.premises } pub fn premise_subset(&self, other: &Self) -> bool { self.premises.is_subset(&other.premises) } } impl<A: Merge + PartialEq> Supported<A> { pub fn subsumes(&self, other: &Self) -> bool { self.value == self.value.merge(&other.value) && self.premises.is_subset(&other.premises) } } impl<A: Debug + Merge + Clone + PartialEq> Merge for Supported<A> { fn is_valid(&self, other: &Self) -> bool { self.value.is_valid(&other.value) } fn merge(&self, other: &Self) -> Self { let merged_value = self.value.merge(&other.value); if merged_value == self.value { if other.value.merge(&merged_value) == other.value { if self.premises != other.premises && other.premises.is_subset(&self.premises) { (*other).clone() } else { (*self).clone() } } else { (*self).clone() } } else if merged_value == other.value { (*other).clone() } else { println!("merge union"); Self { value: merged_value, premises: self.premises.union(&other.premises).cloned().collect() } } } }
//! This module contains a [`Span`] settings, it helps to //! make a cell take more space then it generally takes. //! //! # Example //! //! ``` //! use tabled::{settings::{Span, Modify}, Table}; //! //! let data = [[1, 2, 3], [4, 5, 6]]; //! //! let table = Table::new(data) //! .with(Modify::new((2, 0)).with(Span::column(2))) //! .with(Modify::new((0, 1)).with(Span::column(2))) //! .to_string(); //! //! assert_eq!( //! table, //! concat!( //! "+---+---+---+\n", //! "| 0 | 1 |\n", //! "+---+---+---+\n", //! "| 1 | 2 | 3 |\n", //! "+---+---+---+\n", //! "| 4 | 6 |\n", //! "+---+---+---+", //! ) //! ) //! ``` mod column; mod row; pub use column::ColumnSpan; pub use row::RowSpan; /// Span represent a horizontal/column span setting for any cell on a [`Table`]. /// /// It will be ignored if: /// - cell position is out of scope /// - size is bigger then the total number of columns. /// - size is bigger then the total number of rows. /// /// ```rust,no_run /// # use tabled::{Table, settings::{Style, Span, Modify, object::Columns}}; /// # let data: Vec<&'static str> = Vec::new(); /// let table = Table::new(&data) /// .with(Modify::new(Columns::single(0)).with(Span::column(2))); /// ``` /// /// [`Table`]: crate::Table #[derive(Debug)] pub struct Span; impl Span { /// New constructs a horizontal/column [`Span`]. /// /// If size is bigger then the total number of columns it will be ignored. pub fn column(size: usize) -> ColumnSpan { ColumnSpan::new(size) } /// New constructs a vertical/row [`Span`]. /// /// If size is bigger then the total number of rows it will be ignored. pub fn row(size: usize) -> RowSpan { RowSpan::new(size) } }
use std::convert::TryFrom; use std::sync::{Arc, RwLock}; #[macro_use] extern crate lazy_static; use rayon::iter::{ParallelBridge, ParallelIterator}; use skim::{ prelude::{unbounded, SkimOptionsBuilder}, Skim, SkimItemReceiver, SkimItemSender, }; /// `Action` and its implementations mod action; /// `clap` configuration mod cli; /// `Config` struct and its implementations mod config; /// `FileIter` enum and its implementations mod file_iter; /// `PDFContent` and its implementations mod pdf; use action::Action; use file_iter::FileIter; use pdf::PDFContent; lazy_static! { /// Global configuration for the application pub static ref CONFIG: RwLock<config::Config> = RwLock::new(config::Config::new()); } fn main() { let matches = cli::get_app().get_matches(); CONFIG.write().unwrap().modify_with_argmatches(&matches); let (tx_item, rx_item): (SkimItemSender, SkimItemReceiver) = unbounded(); let path = matches.value_of("PATH").unwrap(); let with_hidden_files = matches.is_present("hidden"); FileIter::new(path, with_hidden_files) .par_bridge() .filter_map(|possible_entry| { let possible_pdf = possible_entry.ok()?.into_path(); if possible_pdf.extension()?.to_str()? == "pdf" { Some(possible_pdf.into_os_string()) } else { None } }) .filter_map(|pdf_path| match PDFContent::try_from(pdf_path) { Ok(pdf_content) => Some(pdf_content), Err((error, file_path)) => { if !CONFIG.read().unwrap().quiet { println!("{:?}: {:?}", file_path, error); } None } }) .for_each_with(tx_item, |tx_item, pdf_content| { let _ = tx_item.send(Arc::new(pdf_content)); }); let skim_options = SkimOptionsBuilder::default() .reverse(true) .exact(true) .preview_window(Some("down:80%")) .preview(Some("")) .build() .unwrap(); match Skim::run_with(&skim_options, Some(rx_item)) { Some(sk_output) => { if sk_output.is_abort { std::process::exit(130) } Action::from_matches(&matches).execute(sk_output); } None => std::process::exit(1), } }
use bytes::Bytes; use http::header::{AsHeaderName, HeaderMap, HeaderName, HeaderValue}; use http::{self, request::Builder}; use serde::{ de::{self, DeserializeOwned, Deserializer}, Deserialize, }; use std::{convert::TryFrom, fmt::Display, str::FromStr}; pub fn format_header_value<D: Display>(value: D) -> Result<HeaderValue, http::Error> { let value: &str = &format(value); Ok(HeaderValue::try_from(value)?) } pub trait HeaderMapExt { fn get_header<K: AsHeaderName>(&self, key: K) -> Option<&HeaderValue>; fn get_as_str<K: AsHeaderName>(&self, key: K) -> Option<&str> { self.get_header(key).and_then(|v| v.to_str().ok()) } fn get_as_string<K: AsHeaderName>(&self, key: K) -> Option<String> { self.get_as_str(key).map(|s| s.to_owned()) } fn get_as_u64<K: AsHeaderName>(&self, key: K) -> Option<u64> { self.get_as_str(key).and_then(|s| s.parse::<u64>().ok()) } fn get_as_enum<K: AsHeaderName, V: FromStr<Err = E>, E>(&self, key: K) -> Result<Option<V>, E> { if let Some(s) = self.get_as_str(key) { return Ok(Some(s.parse::<V>()?)); } Ok(None) } } impl HeaderMapExt for HeaderMap { fn get_header<K: AsHeaderName>(&self, key: K) -> Option<&HeaderValue> { self.get(key) } } pub trait RequestBuilderExt { fn set_header<K, V>(self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<http::Error>, Self: Sized; fn header_formatted<K, D: Display>(self, key: K, value: D) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, Self: Sized, { self.set_header(key, &format(value)) } fn header_static<K>(self, key: K, value: &'static str) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, Self: Sized, { self.set_header(key, HeaderValue::from_static(value)) } fn header_bytes<K, B: Into<Bytes>>(self, key: K, value: B) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, Self: Sized, { self.set_header(key, &value.into() as &[u8]) } } impl RequestBuilderExt for Builder { fn set_header<K, V>(self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<http::Error>, Self: Sized, { self.header(key, value) } } fn format<D: Display>(value: D) -> String { format!("{}", value) } const UTF8_BOM: [u8; 3] = [0xEF, 0xBB, 0xBF]; /// Returns Bytes without the UTF-8 BOM. pub fn slice_bom(bytes: &Bytes) -> Bytes { if bytes.len() > 3 && bytes.slice(0..3).as_ref() == UTF8_BOM { bytes.slice(3..) } else { bytes.clone() } } pub fn case_insensitive_deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error> where T: DeserializeOwned + std::fmt::Debug, D: Deserializer<'de>, { let v = String::deserialize(deserializer)?; T::deserialize(serde_json::Value::String(v.clone())) .or_else(|_| T::deserialize(serde_json::Value::String(v.to_lowercase()))) .map_err(de::Error::custom) } #[cfg(test)] mod test { use super::*; #[test] fn test_slice_bom() { let bytes = Bytes::from_static(&[0xEF, 0xBB, 0xBF, 7]); assert_eq!(Bytes::from_static(&[7]), slice_bom(&bytes)); let bytes = Bytes::from_static(&[8]); assert_eq!(Bytes::from_static(&[8]), slice_bom(&bytes)); } }
// Copyright 2018 (c) rust-themis developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::BTreeMap; use std::rc::Rc; use std::sync::mpsc::{channel, Receiver, Sender}; use themis::keygen::gen_ec_key_pair; use themis::keys::EcdsaPublicKey; use themis::secure_session::{SecureSession, SecureSessionTransport}; struct DummyTransport { key_map: Rc<BTreeMap<Vec<u8>, EcdsaPublicKey>>, } impl DummyTransport { fn new(key_map: &Rc<BTreeMap<Vec<u8>, EcdsaPublicKey>>) -> Self { Self { key_map: key_map.clone(), } } } impl SecureSessionTransport for DummyTransport { fn get_public_key_for_id(&mut self, id: &[u8]) -> Option<EcdsaPublicKey> { self.key_map.get(id).cloned() } } struct ChannelTransport { key_map: Rc<BTreeMap<Vec<u8>, EcdsaPublicKey>>, tx: Sender<Vec<u8>>, rx: Receiver<Vec<u8>>, } impl ChannelTransport { #[allow(clippy::new_ret_no_self)] fn new(key_map: &Rc<BTreeMap<Vec<u8>, EcdsaPublicKey>>) -> (Self, Self) { let (tx12, rx21) = channel(); let (tx21, rx12) = channel(); let transport1 = Self { key_map: key_map.clone(), tx: tx12, rx: rx12, }; let transport2 = Self { key_map: key_map.clone(), tx: tx21, rx: rx21, }; (transport1, transport2) } } impl SecureSessionTransport for ChannelTransport { fn send_data(&mut self, data: &[u8]) -> Result<usize, ()> { self.tx .send(data.to_vec()) .map(|_| data.len()) .map_err(|_| ()) } fn receive_data(&mut self, data: &mut [u8]) -> Result<usize, ()> { let msg = self.rx.recv().map_err(|_| ())?; if msg.len() > data.len() { return Err(()); } data[0..msg.len()].copy_from_slice(&msg); Ok(msg.len()) } fn get_public_key_for_id(&mut self, id: &[u8]) -> Option<EcdsaPublicKey> { self.key_map.get(id).cloned() } } #[test] fn no_transport() { // Peer credentials. Secure Session supports only ECDSA. // TODO: tests that confirm RSA failure let (secret_client, public_client) = gen_ec_key_pair().split(); let (secret_server, public_server) = gen_ec_key_pair().split(); let (name_client, name_server) = ("client", "server"); // Shared storage of public peer credentials. These should be communicated between // the peers beforehand in some unspecified trusted way. let mut key_map = BTreeMap::new(); key_map.insert(name_client.as_bytes().to_vec(), public_client); key_map.insert(name_server.as_bytes().to_vec(), public_server); let key_map = Rc::new(key_map); // The client and the server. let mut client = SecureSession::with_transport(name_client, &secret_client, DummyTransport::new(&key_map)) .unwrap(); let mut server = SecureSession::with_transport(name_server, &secret_server, DummyTransport::new(&key_map)) .unwrap(); assert!(!client.is_established()); assert!(!server.is_established()); assert!(client.get_remote_id().unwrap().is_empty()); assert!(server.get_remote_id().unwrap().is_empty()); // Connection and key negotiation sequence. let connect_request = client.generate_connect_request().expect("connect request"); let connect_reply = server.negotiate(&connect_request).expect("connect reply"); let key_proposed = client.negotiate(&connect_reply).expect("key proposed"); let key_accepted = server.negotiate(&key_proposed).expect("key accepted"); let key_confirmed = client.negotiate(&key_accepted).expect("key confirmed"); assert!(key_confirmed.is_empty()); assert!(client.is_established()); assert!(server.is_established()); assert_eq!(client.get_remote_id().unwrap(), name_server.as_bytes()); assert_eq!(server.get_remote_id().unwrap(), name_client.as_bytes()); // TODO: check connection states reported to transport delegate // Try sending a message back and forth. let plaintext = b"test message please ignore"; let wrapped = client.wrap(&plaintext).expect("wrap 1 -> 2 message"); let unwrapped = server.unwrap(&wrapped).expect("unwrap 1 -> 2 message"); assert_eq!(unwrapped, plaintext); let wrapped = server.wrap(&plaintext).expect("wrap 2 -> 1 message"); let unwrapped = client.unwrap(&wrapped).expect("unwrap 2 -> 1 message"); assert_eq!(unwrapped, plaintext); // TODO: it seems that one cannot wrap an empty message, check it out // Messages are independent, can come out-of-order and be lost. client.wrap(b"some message").expect("lost message 1"); client.wrap(b"some message").expect("lost message 2"); server.wrap(b"some message").expect("lost message 3"); let wrapped1 = client.wrap(b"message 1").expect("message 1"); let wrapped2 = client.wrap(b"message 2").expect("message 2"); let unwrapped2 = server.unwrap(&wrapped2).expect("message 2"); let unwrapped1 = server.unwrap(&wrapped1).expect("message 1"); assert_eq!(unwrapped1, b"message 1"); assert_eq!(unwrapped2, b"message 2"); } #[test] fn with_transport() { // Peer credentials. Secure Session supports only ECDSA. // TODO: tests that confirm RSA failure let (secret_client, public_client) = gen_ec_key_pair().split(); let (secret_server, public_server) = gen_ec_key_pair().split(); let (name_client, name_server) = ("client", "server"); // Shared storage of public peer credentials. These should be communicated between // the peers beforehand in some unspecified trusted way. let mut key_map = BTreeMap::new(); key_map.insert(name_client.as_bytes().to_vec(), public_client); key_map.insert(name_server.as_bytes().to_vec(), public_server); let key_map = Rc::new(key_map); // The client and the server. let (transport_client, transport_server) = ChannelTransport::new(&key_map); let mut client = SecureSession::with_transport(name_client, &secret_client, transport_client).unwrap(); let mut server = SecureSession::with_transport(name_server, &secret_server, transport_server).unwrap(); assert!(!client.is_established()); assert!(!server.is_established()); // Establishing connection. client.connect().expect("client-side connection"); server.negotiate_transport().expect("connect reply"); client.negotiate_transport().expect("key proposed"); server.negotiate_transport().expect("key accepted"); client.negotiate_transport().expect("key confirmed"); assert!(client.is_established()); assert!(server.is_established()); // Try sending a message back and forth. let message = b"test message please ignore"; client.send(&message).expect("send message"); let received = server.receive(1024).expect("receive message"); assert_eq!(received, message); }
/*mod gui; mod plaid; mod datamodel; mod component; mod ewidget; use gui::run_app; use hyper::rt::{self};*/ mod component2; mod xml_test; mod xml_parse; use xml_test::{test_main}; fn main() { /*rt::run(rt::lazy(|| { run_app(); Ok(()) }));*/ test_main(); }
/* * Slack Web API * * One way to interact with the Slack platform is its HTTP RPC-based Web API, a collection of methods requiring OAuth 2.0-based user, bot, or workspace tokens blessed with related OAuth scopes. * * The version of the OpenAPI document: 1.7.0 * * Generated by: https://openapi-generator.tech */ use reqwest; use crate::apis::ResponseContent; use super::{Error, configuration}; /// struct for typed errors of method `workflows_step_completed` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum WorkflowsStepCompletedError { DefaultResponse(::std::collections::HashMap<String, serde_json::Value>), UnknownValue(serde_json::Value), } /// struct for typed errors of method `workflows_step_failed` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum WorkflowsStepFailedError { DefaultResponse(::std::collections::HashMap<String, serde_json::Value>), UnknownValue(serde_json::Value), } /// struct for typed errors of method `workflows_update_step` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum WorkflowsUpdateStepError { DefaultResponse(::std::collections::HashMap<String, serde_json::Value>), UnknownValue(serde_json::Value), } /// Indicate that an app's step in a workflow completed execution. pub async fn workflows_step_completed(configuration: &configuration::Configuration, token: &str, workflow_step_execute_id: &str, outputs: Option<&str>) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<WorkflowsStepCompletedError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/workflows.stepCompleted", configuration.base_path); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("workflow_step_execute_id", &workflow_step_execute_id.to_string())]); if let Some(ref local_var_str) = outputs { local_var_req_builder = local_var_req_builder.query(&[("outputs", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } local_var_req_builder = local_var_req_builder.header("token", token.to_string()); if let Some(ref local_var_token) = configuration.oauth_access_token { local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<WorkflowsStepCompletedError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Indicate that an app's step in a workflow failed to execute. pub async fn workflows_step_failed(configuration: &configuration::Configuration, token: &str, workflow_step_execute_id: &str, error: &str) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<WorkflowsStepFailedError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/workflows.stepFailed", configuration.base_path); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("workflow_step_execute_id", &workflow_step_execute_id.to_string())]); local_var_req_builder = local_var_req_builder.query(&[("error", &error.to_string())]); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } local_var_req_builder = local_var_req_builder.header("token", token.to_string()); if let Some(ref local_var_token) = configuration.oauth_access_token { local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<WorkflowsStepFailedError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Update the configuration for a workflow extension step. pub async fn workflows_update_step(configuration: &configuration::Configuration, token: &str, workflow_step_edit_id: &str, inputs: Option<&str>, outputs: Option<&str>, step_name: Option<&str>, step_image_url: Option<&str>) -> Result<::std::collections::HashMap<String, serde_json::Value>, Error<WorkflowsUpdateStepError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/workflows.updateStep", configuration.base_path); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); local_var_req_builder = local_var_req_builder.query(&[("workflow_step_edit_id", &workflow_step_edit_id.to_string())]); if let Some(ref local_var_str) = inputs { local_var_req_builder = local_var_req_builder.query(&[("inputs", &local_var_str.to_string())]); } if let Some(ref local_var_str) = outputs { local_var_req_builder = local_var_req_builder.query(&[("outputs", &local_var_str.to_string())]); } if let Some(ref local_var_str) = step_name { local_var_req_builder = local_var_req_builder.query(&[("step_name", &local_var_str.to_string())]); } if let Some(ref local_var_str) = step_image_url { local_var_req_builder = local_var_req_builder.query(&[("step_image_url", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } local_var_req_builder = local_var_req_builder.header("token", token.to_string()); if let Some(ref local_var_token) = configuration.oauth_access_token { local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<WorkflowsUpdateStepError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] OAuth2PermissionGrant_ListNext(#[from] o_auth2_permission_grant::list_next::Error), #[error(transparent)] SignedInUser_ListOwnedObjectsNext(#[from] signed_in_user::list_owned_objects_next::Error), #[error(transparent)] Groups_ListNext(#[from] groups::list_next::Error), #[error(transparent)] Groups_GetGroupMembersNext(#[from] groups::get_group_members_next::Error), #[error(transparent)] Applications_ListNext(#[from] applications::list_next::Error), #[error(transparent)] DeletedApplications_ListNext(#[from] deleted_applications::list_next::Error), #[error(transparent)] ServicePrincipals_ListNext(#[from] service_principals::list_next::Error), #[error(transparent)] Users_ListNext(#[from] users::list_next::Error), #[error(transparent)] Objects_GetObjectsByObjectIdsNext(#[from] objects::get_objects_by_object_ids_next::Error), } pub mod o_auth2_permission_grant { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::OAuth2PermissionGrantListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?OAuth2PermissionGrant_ListNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::OAuth2PermissionGrantListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod signed_in_user { use super::{models, API_VERSION}; pub async fn list_owned_objects_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::DirectoryObjectListResult, list_owned_objects_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?SignedInUser_ListOwnedObjectsNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(list_owned_objects_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_owned_objects_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(list_owned_objects_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_owned_objects_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DirectoryObjectListResult = serde_json::from_slice(rsp_body) .map_err(|source| list_owned_objects_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body) .map_err(|source| list_owned_objects_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_owned_objects_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_owned_objects_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod groups { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::GroupListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/{}/{}?Groups_ListNext", operation_config.base_path(), tenant_id, next_link); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::GroupListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get_group_members_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::DirectoryObjectListResult, get_group_members_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?Groups_GetGroupMembersNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(get_group_members_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_group_members_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(get_group_members_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_group_members_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DirectoryObjectListResult = serde_json::from_slice(rsp_body) .map_err(|source| get_group_members_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body) .map_err(|source| get_group_members_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_group_members_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_group_members_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod applications { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::ApplicationListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/{}/{}?Applications_ListNext", operation_config.base_path(), tenant_id, next_link); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplicationListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod deleted_applications { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::ApplicationListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?DeletedApplications_ListNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplicationListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod service_principals { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::ServicePrincipalListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?ServicePrincipals_ListNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ServicePrincipalListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod users { use super::{models, API_VERSION}; pub async fn list_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::UserListResult, list_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/{}/{}?Users_ListNext", operation_config.base_path(), tenant_id, next_link); let mut url = url::Url::parse(url_str).map_err(list_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::UserListResult = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::GraphError = serde_json::from_slice(rsp_body).map_err(|source| list_next::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_next::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::GraphError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod objects { use super::{models, API_VERSION}; pub async fn get_objects_by_object_ids_next( operation_config: &crate::OperationConfig, next_link: &str, tenant_id: &str, ) -> std::result::Result<models::DirectoryObjectListResult, get_objects_by_object_ids_next::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/{}/{}?Objects_GetObjectsByObjectIdsNext", operation_config.base_path(), tenant_id, next_link ); let mut url = url::Url::parse(url_str).map_err(get_objects_by_object_ids_next::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::POST); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_objects_by_object_ids_next::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.header(http::header::CONTENT_LENGTH, 0); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(get_objects_by_object_ids_next::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_objects_by_object_ids_next::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::DirectoryObjectListResult = serde_json::from_slice(rsp_body) .map_err(|source| get_objects_by_object_ids_next::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); Err(get_objects_by_object_ids_next::Error::UnexpectedResponse { status_code, body: rsp_body.clone(), }) } } } pub mod get_objects_by_object_ids_next { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("Unexpected HTTP status code {}", status_code)] UnexpectedResponse { status_code: http::StatusCode, body: bytes::Bytes }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } }
extern crate clap; use clap::{Arg, App, crate_version}; use url::{Url}; use std::error::Error; fn main() { let matches = App::new("Comand Line URL Parser") .version(crate_version!()) .author("Ilya Amelevich <ilya.amelevich@ya.ru>") .about("Parse URLs") .arg(Arg::with_name("URL") .help("Sets URL to parse") .required(true) .index(1)) .get_matches(); let url = matches.value_of("URL").unwrap(); match get_queries_from_url(&url) { Ok(_) => ::std::process::exit(0), Err(err) => { eprintln!("Error: {:?}", err); ::std::process::exit(1); } } } fn get_queries_from_url(url: &str) -> Result<bool, Box<dyn Error>> { let parsed_url = Url::parse(url)?; let parsed_url = match parsed_url.query() { Some(val) => val.split('&').collect(), None => vec![], }; for q in parsed_url.iter() { println!("{:?}", q); } Ok(true) }
pub fn test() -> () { println!("safe!") }
use parser::Node; use lexer::Str; use std::collections::HashMap; use std::cell::RefCell; type Rib = HashMap<Str, Node>; struct Envr { ribs: RefCell<Vec<Rib>>, } struct RibGuard<'a> { envr: &'a Envr, } impl<'a> Drop for RibGuard<'a> { fn drop(&mut self) { assert!(self.envr.ribs.borrow_mut().pop().is_some(), "No ribs to pop"); } } impl Envr { fn new() -> Envr { Envr { ribs: RefCell::new(Vec::new()), } } fn with_value(name: &str, value: Node) -> Envr { let mut map = HashMap::new(); map.insert(Str::new(name), value); Envr { ribs: RefCell::new(vec![map]), } } fn push_rib(&self) -> RibGuard { self.ribs.borrow_mut().push(HashMap::new()); RibGuard { envr: self } } fn store(&self, name: &Str, value: Node) { let mut ribs = self.ribs.borrow_mut(); assert!(ribs.len() > 0, "No ribs in environment"); let len = ribs.len(); let rib = &mut ribs[len - 1]; assert!(!rib.contains_key(name), "Identifier already exists in rib: {}", name); rib.insert(name.clone(), value); } fn lookup(&self, name: &Str) -> Option<Node> { for rib in self.ribs.borrow().iter().rev() { if let Some(value) = rib.get(name) { return Some(value.clone()); } } return None; } } pub fn run_program(input: &Node) -> Vec<Node> { let mut result = Vec::new(); if let &Node::Program(ref ns) = input { for n in ns { let mut envr = Envr::new(); result.push(run_node(n, &mut envr)); } } else { panic!("Expected program, found: {:?}", input); } result } fn run_node(input: &Node, envr: &Envr) -> Node { match *input { ref t if t.is_value() => t.clone(), Node::S(ref ns) => { match ns[0] { Node::Print => { let args = run_args(input, envr); for a in &args { println!("{}", a); } s!() } Node::Plus => { let args = run_args(input, envr); let result = args.iter().fold(0, |a, n| a + n.expect_lit_num()); lit_num!(result) } Node::Let => { let len = ns.len(); let body = &ns[len - 1]; let args = &ns[1..len - 1]; assert!(args.len() % 2 == 0, "Argument without a value in `let`"); let _guard = envr.push_rib(); for i in 0..args.len() / 2 { let arg_name = &args[i * 2].expect_ident(); let arg_value = run_node(&args[i * 2 + 1], envr); envr.store(arg_name, arg_value); } run_node(body, envr) } Node::S(ref sub_ns) if sub_ns.len() > 0 && sub_ns[0] == Node::Fn => { assert!(sub_ns.len() > 1, "No body for function: {:?}", &ns[0]); let len = sub_ns.len(); let fun_body = &sub_ns[len - 1]; let formals: Vec<_> = sub_ns[1..len - 1].iter().map(|n| n.expect_ident()).collect(); let args = run_args(input, envr); assert!(args.len() == formals.len(), "Mismatch in number of function arguments. Expected: {}, found: {}", formals.len(), args.len()); let _guard = envr.push_rib(); for (ref formal, actual) in formals.iter().zip(args.iter()) { envr.store(formal, actual.clone()); } run_node(fun_body, envr) } ref n => { // Some pretty crufty logic down here. // We are inside an s-expr and inspecting the first element. let mut reduced_els = match run_node(n, envr) { // First element is an empty s-expr, forget it: // (() ...) --> (...) Node::S(ref ns) if ns.len() == 0 => Vec::new(), // First and only element is a value, promote it to the value. // (v) --> v ref r if ns.len() == 1 && r.is_value() => return r.clone(), // Otherwise just reduce the first element. // n0 --> n0' // --------------------- // (n0 ...) -> (n0' ...) r => vec!(r), }; reduced_els.extend(ns[1..].iter().map(|n| n.clone())); run_node(&Node::S(reduced_els), envr) } } } Node::Ident(ref s) => { if let Some(n) = envr.lookup(s) { return n; } panic!("Unknown identifier: {}", s); } _ => panic!("Unexpected node: {:?}", input), } } fn run_args(s: &Node, envr: &Envr) -> Vec<Node> { if let &Node::S(ref ns) = s { return ns[1..].iter().map(|n| run_node(n, envr)).collect(); } panic!("Expcted S expression, found {:?}", s); } #[cfg(test)] mod test { use super::{run_node, Envr}; use super::*; use parser::Node; use lexer::Str; #[test] fn test_empty() { assert!(run_program(&program!()) == vec![]); } #[test] fn test_values() { assert!(run_program(&program!(lit_str!("foo"), lit_num!(42))) == vec![lit_str!("foo"), lit_num!(42)]); let envr = &Envr::new(); assert!(run_node(&lit_str!("foo"), envr) == lit_str!("foo")); let s = s!(Node::Fn, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(42))); assert!(run_node(&s, envr) == s); let s = s!(); assert!(run_node(&s, envr) == s); } #[test] fn test_s_reduce() { let envr = &Envr::new(); let s = s!(s!(), s!(lit_num!(42))); assert!(run_node(&s, envr) == lit_num!(42)); let s = s!(s!(Node::Plus, lit_num!(42))); assert!(run_node(&s, envr) == lit_num!(42)); } #[test] fn test_print() { let envr = &Envr::new(); let s = s!(Node::Print, lit_str!("Hello world!")); assert!(run_node(&s, envr) == s!()); } #[test] fn test_plus() { let envr = &Envr::new(); let s = s!(Node::Plus, lit_num!(3)); assert!(run_node(&s, envr) == lit_num!(3)); let s = s!(Node::Plus, lit_num!(3), lit_num!(1)); assert!(run_node(&s, envr) == lit_num!(4)); let s = s!(Node::Plus, lit_num!(3), lit_num!(1), lit_num!(1), lit_num!(1)); assert!(run_node(&s, envr) == lit_num!(6)); } #[test] #[should_panic] fn test_plus_fail() { let envr = &Envr::new(); let s = s!(Node::Plus, lit_num!(3), s!()); run_node(&s, envr); } #[test] fn test_ident() { let envr = &Envr::with_value("x", lit_num!(42)); assert!(run_node(&ident!("x"), envr) == lit_num!(42)); } #[test] #[should_panic] fn test_ident_fail() { let envr = &Envr::with_value("x", lit_num!(42)); run_node(&ident!("y"), envr); } #[test] fn test_envr_push_pop() { let envr = &Envr::new(); { let _guard = envr.push_rib(); envr.store(&Str::new("x"), lit_num!(0)); { let _guard = envr.push_rib(); envr.store(&Str::new("x"), lit_num!(42)); assert!(envr.lookup(&Str::new("x")) == Some(lit_num!(42))); assert!(envr.lookup(&Str::new("y")) == None); } assert!(envr.lookup(&Str::new("x")) == Some(lit_num!(0))); assert!(envr.lookup(&Str::new("y")) == None); } assert!(envr.lookup(&Str::new("x")) == None); assert!(envr.lookup(&Str::new("y")) == None); } #[test] #[should_panic] fn test_ident_dup_fail() { let envr = &Envr::with_value("x", lit_num!(42)); envr.store(&Str::new("x"), lit_num!(42)); } #[test] fn test_scoped_ident() { let envr = &Envr::with_value("x", lit_num!(0)); let _guard = envr.push_rib(); envr.store(&Str::new("x"), lit_num!(42)); assert!(run_node(&ident!("x"), envr) == lit_num!(42)); } #[test] fn test_let() { let envr = &Envr::new(); // trivial assert!(run_node(&s!(Node::Let, s!()), envr) == s!()); assert!(run_node(&s!(Node::Let, lit_num!(42)), envr) == lit_num!(42)); // easy assert!(run_node(&s!(Node::Let, ident!("x"), lit_num!(42), ident!("x")), envr) == lit_num!(42)); assert!(run_node(&s!(Node::Let, ident!("x"), lit_num!(42), s!(Node::Plus, ident!("x"), lit_num!(42))), envr) == lit_num!(84)); // multiple assert!(run_node(&s!(Node::Let, ident!("x"), lit_num!(3), ident!("y"), lit_num!(4), s!(Node::Plus, ident!("x"), ident!("y"))), envr) == lit_num!(7)); // scoped assert!(run_node(&s!(Node::Let, ident!("x"), lit_num!(0), s!(Node::Let, ident!("x"), lit_num!(42), ident!("x"))), envr) == lit_num!(42)); // uses earlier assert!(run_node(&s!(Node::Let, ident!("x"), lit_num!(3), ident!("y"), s!(Node::Plus, ident!("x"), lit_num!(1)), s!(Node::Plus, ident!("x"), ident!("y"))), envr) == lit_num!(7)); } #[test] #[should_panic] fn test_let_not_rec() { let envr = &Envr::new(); run_node(&s!(Node::Let, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(0)), s!()), envr); } #[test] fn test_fn() { let envr = &Envr::new(); // trivial assert!(run_node(&s!(s!(Node::Fn, s!())), envr) == s!()); assert!(run_node(&s!(s!(Node::Fn, lit_num!(42))), envr) == lit_num!(42)); // easy assert!(run_node(&s!(s!(Node::Fn, ident!("x"), ident!("x")), lit_num!(42)), envr) == lit_num!(42)); assert!(run_node(&s!(s!(Node::Fn, ident!("x"), lit_num!(42)), lit_num!(0)), envr) == lit_num!(42)); assert!(run_node(&s!(s!(Node::Fn, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(1))), lit_num!(42)), envr) == lit_num!(43)); // multiple args assert!(run_node(&s!(s!(Node::Fn, ident!("x"), ident!("y"), ident!("x")), lit_num!(42), lit_num!(0)), envr) == lit_num!(42)); assert!(run_node(&s!(s!(Node::Fn, ident!("x"), ident!("y"), s!(Node::Plus, ident!("x"), ident!("y"))), lit_num!(42), lit_num!(1)), envr) == lit_num!(43)); // scopes let f1 = s!(Node::Fn, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(1))); let f2 = s!(Node::Fn, ident!("x"), s!(f1, s!(Node::Plus, ident!("x"), lit_num!(4)))); assert!(run_node(&s!(f2, lit_num!(2)), envr) == lit_num!(7)); // higher order let f1 = s!(Node::Fn, ident!("x"), ident!("y"), s!(ident!("x"), s!(Node::Plus, ident!("y"), lit_num!(3)))); let f2 = s!(Node::Fn, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(2))); assert!(run_node(&s!(f1, f2, lit_num!(5)), envr) == lit_num!(10)); } #[test] fn test_fn_let() { let envr = &Envr::new(); let f = s!(Node::Fn, ident!("x"), s!(Node::Plus, ident!("x"), lit_num!(1))); let l = s!(Node::Let, ident!("y"), f, s!(ident!("y"), lit_num!(42))); assert!(run_node(&l, envr) == lit_num!(43)); } #[test] #[should_panic] fn test_fn_arg_mismatch() { let envr = &Envr::new(); run_node(&s!(s!(Node::Fn, ident!("x"), ident!("x")), lit_num!(42), lit_num!(42)), envr); } }
use std::fs::read_to_string; fn main() { let input = read_to_string("d10-input").expect("something went wrong reading file"); let mut data: Vec<usize> = input.lines().map(|n| n.parse().unwrap()).collect(); data.push(0); data.sort_unstable(); let mut paths: Vec<usize> = vec![0; *data.last().unwrap() + 3]; paths[*data.last().unwrap()] = 1; for n in data.iter().rev().skip(1) { paths[*n] += paths[n + 1] + paths[n + 2] + paths[n + 3]; } println!("Number of distinct paths: {}", paths[0]); }
//! Raw bindings to [VapourSynth](https://github.com/vapoursynth/vapoursynth). #![doc(html_root_url = "https://docs.rs/vapoursynth-sys/0.4.0")] #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] #[macro_use] extern crate cfg_if; mod bindings; pub use crate::bindings::*; macro_rules! api_version { ($major:expr, $minor:expr) => { ($major << 16) | $minor }; } cfg_if! { if #[cfg(feature="vapoursynth-api-36")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 6); } else if #[cfg(feature="vapoursynth-api-35")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 5); } else if #[cfg(feature="vapoursynth-api-34")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 4); } else if #[cfg(feature="vapoursynth-api-33")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 3); } else if #[cfg(feature="vapoursynth-api-32")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 2); } else if #[cfg(feature="vapoursynth-api-31")] { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 1); } else { pub const VAPOURSYNTH_API_VERSION: i32 = api_version!(3, 0); } } cfg_if! { if #[cfg(feature="vsscript-api-32")] { pub const VSSCRIPT_API_VERSION: i32 = api_version!(3, 2); } else if #[cfg(feature="vsscript-api-31")] { pub const VSSCRIPT_API_VERSION: i32 = api_version!(3, 1); } else { pub const VSSCRIPT_API_VERSION: i32 = api_version!(3, 0); } }
mod drop; mod flag_message; mod flagspeed; mod handle_leave; mod leaveupdate; mod loginupdate; mod pickupflag; mod pos_update; mod register; mod return_flag; mod sendmessage; mod drop_on_spec; pub use self::register::register; pub use self::drop::DropSystem; pub use self::flag_message::PickupMessageSystem; pub use self::flagspeed::FlagSpeedSystem; pub use self::handle_leave::UpdateGameModeOnPlayerLeave; pub use self::leaveupdate::LeaveUpdateSystem; pub use self::loginupdate::LoginUpdateSystem; pub use self::pickupflag::PickupFlagSystem; pub use self::pos_update::PosUpdateSystem; pub use self::return_flag::ReturnFlagSystem; pub use self::sendmessage::SendFlagMessageSystem; pub use self::drop_on_spec::DropOnSpec;
#[macro_use] extern crate tantivy; use tantivy::collector::Count; use tantivy::query::QueryParser; use tantivy::schema::{Schema, TEXT}; use tantivy::{Index, Result}; // without Result above it would be this: // fn main() -> tantivy::Result<()> { fn main() -> Result<()> { let mut schema_builder = Schema::builder(); let title = schema_builder.add_text_field("title", TEXT); let schema = schema_builder.build(); let index = Index::create_in_ram(schema); { let mut index_writer = index.writer(3_000_000)?; index_writer.add_document(doc!( title => "The Name of diary the Wind", )); index_writer.add_document(doc!( title => "The Diary of Muadib", )); index_writer.add_document(doc!( title => "A Dairy Cow", )); index_writer.add_document(doc!( title => "The Diary of a Young Girl", )); index_writer.commit().unwrap(); } let reader = index.reader()?; let searcher = reader.searcher(); { let query_parser = QueryParser::for_index(&index, vec![title]); let query = query_parser.parse_query("diary")?; let count = searcher.search(&query, &Count).unwrap(); assert_eq!(count, 3); } Ok(()) }
#![no_std] #![no_main] #![feature(min_type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #![allow(incomplete_features)] #[path = "../example_common.rs"] mod example_common; use embassy_nrf::Peripherals; use example_common::*; use defmt::panic; use embassy::executor::Spawner; use embassy::time::{Duration, Timer}; #[embassy::task] async fn run1() { loop { info!("BIG INFREQUENT TICK"); Timer::after(Duration::from_ticks(64000)).await; } } #[embassy::task] async fn run2() { loop { info!("tick"); Timer::after(Duration::from_ticks(13000)).await; } } #[embassy::main] async fn main(spawner: Spawner, _p: Peripherals) { unwrap!(spawner.spawn(run1())); unwrap!(spawner.spawn(run2())); }
pub mod blob; pub mod container; mod headers; pub mod prelude; use crate::core::Client; use azure_core::No; use http::request::Builder; use std::borrow::Borrow; create_enum!(RehydratePriority, (High, "High"), (Standard, "Standard")); pub trait RehydratePrioritySupport { type O; fn with_rehydrate_priority(self, rehydrate_priority: RehydratePriority) -> Self::O; } pub trait RehydratePriorityOption { fn rehydrate_priority(&self) -> Option<RehydratePriority>; #[must_use] fn add_header(&self, mut builder: Builder) -> Builder { if let Some(rehydrate_priority) = self.rehydrate_priority() { builder = builder.header(headers::REHYDRATE_PRIORITY, rehydrate_priority.as_ref()); } builder } } pub trait Blob<C> where C: Client, { fn get_blob<'a>(&'a self) -> blob::requests::GetBlobBuilder<'a, C, No, No>; fn get_blob_properties<'a>(&'a self) -> blob::requests::GetBlobPropertiesBuilder<'a, C, No, No>; fn put_block_blob<'a>(&'a self) -> blob::requests::PutBlockBlobBuilder<'a, C, No, No, No>; fn put_page_blob<'a>(&'a self) -> blob::requests::PutPageBlobBuilder<'a, C, No, No, No>; fn put_append_blob<'a>(&'a self) -> blob::requests::PutAppendBlobBuilder<'a, C, No, No>; fn put_append_block<'a>(&'a self) -> blob::requests::PutAppendBlockBuilder<'a, C, No, No, No>; fn update_page<'a>(&'a self) -> blob::requests::UpdatePageBuilder<'a, C, No, No, No, No>; fn clear_page<'a>(&'a self) -> blob::requests::ClearPageBuilder<'a, C, No, No, No>; fn put_block<'a>(&'a self) -> blob::requests::PutBlockBuilder<'a, C, No, No, No, No>; fn get_block_list<'a>(&'a self) -> blob::requests::GetBlockListBuilder<'a, C, No, No, No>; fn put_block_list<'a, T: Borrow<[u8]> + 'a>( &'a self, ) -> blob::requests::PutBlockListBuilder<'a, C, T, No, No, No>; fn acquire_blob_lease<'a>( &'a self, ) -> blob::requests::AcquireBlobLeaseBuilder<'a, C, No, No, No>; fn renew_blob_lease<'a>(&'a self) -> blob::requests::RenewBlobLeaseBuilder<'a, C, No, No, No>; fn change_blob_lease<'a>( &'a self, ) -> blob::requests::ChangeBlobLeaseBuilder<'a, C, No, No, No, No>; fn release_blob_lease<'a>( &'a self, ) -> blob::requests::ReleaseBlobLeaseBuilder<'a, C, No, No, No>; fn break_blob_lease<'a>(&'a self) -> blob::requests::BreakBlobLeaseBuilder<'a, C, No, No, No>; fn delete_blob_snapshot<'a>( &'a self, ) -> blob::requests::DeleteBlobSnapshotBuilder<'a, C, No, No, No>; fn delete_blob<'a>(&'a self) -> blob::requests::DeleteBlobBuilder<'a, C, No, No, No>; fn stream_blob<'a>(&'a self) -> blob::requests::BlobStreamBuilder<'a, C, No, No, No>; fn copy_blob_from_url<'a>( &'a self, ) -> blob::requests::CopyBlobFromUrlBuilder<'a, C, No, No, No>; fn copy_blob<'a>(&'a self) -> blob::requests::CopyBlobBuilder<'a, C, No, No, No>; fn generate_signed_blob_url<'a>( &'a self, ) -> blob::requests::SignedUrlBuilder<'a, C, No, No, No>; } pub trait Container<C> where C: Client, { fn create_container<'a>(&'a self) -> container::requests::CreateBuilder<'a, C, No, No>; fn delete_container<'a>(&'a self) -> container::requests::DeleteBuilder<'a, C, No>; fn list_blobs<'a>(&'a self) -> container::requests::ListBlobBuilder<'a, C, No>; fn list_containers<'a>(&'a self) -> container::requests::ListBuilder<'a, C>; fn get_container_acl<'a>(&'a self) -> container::requests::GetACLBuilder<'a, C, No>; fn set_container_acl<'a>(&'a self) -> container::requests::SetACLBuilder<'a, C, No, No>; fn get_container_properties<'a>( &'a self, ) -> container::requests::GetPropertiesBuilder<'a, C, No>; fn acquire_container_lease<'a>( &'a self, ) -> container::requests::AcquireLeaseBuilder<'a, C, No, No>; fn renew_container_lease<'a>(&'a self) -> container::requests::RenewLeaseBuilder<'a, C, No, No>; fn release_container_lease<'a>( &'a self, ) -> container::requests::ReleaseLeaseBuilder<'a, C, No, No>; fn break_container_lease<'a>(&'a self) -> container::requests::BreakLeaseBuilder<'a, C, No>; } impl<C> Blob<C> for C where C: Client, { fn get_blob<'a>(&'a self) -> blob::requests::GetBlobBuilder<'a, C, No, No> { blob::requests::GetBlobBuilder::new(self) } fn get_blob_properties<'a>( &'a self, ) -> blob::requests::GetBlobPropertiesBuilder<'a, C, No, No> { blob::requests::GetBlobPropertiesBuilder::new(self) } fn put_block_blob<'a>(&'a self) -> blob::requests::PutBlockBlobBuilder<'a, C, No, No, No> { blob::requests::PutBlockBlobBuilder::new(self) } fn put_page_blob<'a>(&'a self) -> blob::requests::PutPageBlobBuilder<'a, C, No, No, No> { blob::requests::PutPageBlobBuilder::new(self) } fn put_append_blob<'a>(&'a self) -> blob::requests::PutAppendBlobBuilder<'a, C, No, No> { blob::requests::PutAppendBlobBuilder::new(self) } fn put_append_block<'a>(&'a self) -> blob::requests::PutAppendBlockBuilder<'a, C, No, No, No> { blob::requests::PutAppendBlockBuilder::new(self) } fn update_page<'a>(&'a self) -> blob::requests::UpdatePageBuilder<'a, C, No, No, No, No> { blob::requests::UpdatePageBuilder::new(self) } fn clear_page<'a>(&'a self) -> blob::requests::ClearPageBuilder<'a, C, No, No, No> { blob::requests::ClearPageBuilder::new(self) } fn put_block<'a>(&'a self) -> blob::requests::PutBlockBuilder<'a, C, No, No, No, No> { blob::requests::PutBlockBuilder::new(self) } fn get_block_list<'a>(&'a self) -> blob::requests::GetBlockListBuilder<'a, C, No, No, No> { blob::requests::GetBlockListBuilder::new(self) } fn put_block_list<'a, T: Borrow<[u8]> + 'a>( &'a self, ) -> blob::requests::PutBlockListBuilder<'a, C, T, No, No, No> { blob::requests::PutBlockListBuilder::new(self) } fn acquire_blob_lease<'a>( &'a self, ) -> blob::requests::AcquireBlobLeaseBuilder<'a, C, No, No, No> { blob::requests::AcquireBlobLeaseBuilder::new(self) } fn renew_blob_lease<'a>(&'a self) -> blob::requests::RenewBlobLeaseBuilder<'a, C, No, No, No> { blob::requests::RenewBlobLeaseBuilder::new(self) } fn change_blob_lease<'a>( &'a self, ) -> blob::requests::ChangeBlobLeaseBuilder<'a, C, No, No, No, No> { blob::requests::ChangeBlobLeaseBuilder::new(self) } fn release_blob_lease<'a>( &'a self, ) -> blob::requests::ReleaseBlobLeaseBuilder<'a, C, No, No, No> { blob::requests::ReleaseBlobLeaseBuilder::new(self) } fn break_blob_lease<'a>(&'a self) -> blob::requests::BreakBlobLeaseBuilder<'a, C, No, No, No> { blob::requests::BreakBlobLeaseBuilder::new(self) } fn delete_blob_snapshot<'a>( &'a self, ) -> blob::requests::DeleteBlobSnapshotBuilder<'a, C, No, No, No> { blob::requests::DeleteBlobSnapshotBuilder::new(self) } fn delete_blob<'a>(&'a self) -> blob::requests::DeleteBlobBuilder<'a, C, No, No, No> { blob::requests::DeleteBlobBuilder::new(self) } fn stream_blob<'a>(&'a self) -> blob::requests::BlobStreamBuilder<'a, C, No, No, No> { blob::requests::BlobStreamBuilder::new(self) } fn copy_blob_from_url<'a>( &'a self, ) -> blob::requests::CopyBlobFromUrlBuilder<'a, C, No, No, No> { blob::requests::CopyBlobFromUrlBuilder::new(self) } fn copy_blob<'a>(&'a self) -> blob::requests::CopyBlobBuilder<'a, C, No, No, No> { blob::requests::CopyBlobBuilder::new(self) } fn generate_signed_blob_url<'a>( &'a self, ) -> blob::requests::SignedUrlBuilder<'a, C, No, No, No> { blob::requests::SignedUrlBuilder::new(self) } } impl<C> Container<C> for C where C: Client, { fn list_blobs<'a>(&'a self) -> container::requests::ListBlobBuilder<'a, C, No> { container::requests::ListBlobBuilder::new(self) } fn create_container<'a>(&'a self) -> container::requests::CreateBuilder<'a, C, No, No> { container::requests::CreateBuilder::new(self) } fn delete_container<'a>(&'a self) -> container::requests::DeleteBuilder<'a, C, No> { container::requests::DeleteBuilder::new(self) } fn list_containers<'a>(&'a self) -> container::requests::ListBuilder<'a, C> { container::requests::ListBuilder::new(self) } fn get_container_acl<'a>(&'a self) -> container::requests::GetACLBuilder<'a, C, No> { container::requests::GetACLBuilder::new(self) } fn set_container_acl<'a>(&'a self) -> container::requests::SetACLBuilder<'a, C, No, No> { container::requests::SetACLBuilder::new(self) } fn get_container_properties<'a>( &'a self, ) -> container::requests::GetPropertiesBuilder<'a, C, No> { container::requests::GetPropertiesBuilder::new(self) } fn acquire_container_lease<'a>( &'a self, ) -> container::requests::AcquireLeaseBuilder<'a, C, No, No> { container::requests::AcquireLeaseBuilder::new(self) } fn renew_container_lease<'a>( &'a self, ) -> container::requests::RenewLeaseBuilder<'a, C, No, No> { container::requests::RenewLeaseBuilder::new(self) } fn release_container_lease<'a>( &'a self, ) -> container::requests::ReleaseLeaseBuilder<'a, C, No, No> { container::requests::ReleaseLeaseBuilder::new(self) } fn break_container_lease<'a>(&'a self) -> container::requests::BreakLeaseBuilder<'a, C, No> { container::requests::BreakLeaseBuilder::new(self) } }
#![allow( clippy::boxed_local, clippy::derive_partial_eq_without_eq, clippy::just_underscores_and_digits, clippy::missing_errors_doc, clippy::missing_safety_doc, clippy::must_use_candidate, clippy::needless_lifetimes, clippy::needless_pass_by_ref_mut, clippy::needless_pass_by_value, clippy::ptr_arg, clippy::trivially_copy_pass_by_ref, clippy::unnecessary_wraps, clippy::unused_self )] pub mod cast; pub mod module; use cxx::{type_id, CxxString, CxxVector, ExternType, SharedPtr, UniquePtr}; use std::fmt::{self, Display}; use std::mem::MaybeUninit; use std::os::raw::c_char; #[cxx::bridge(namespace = "tests")] pub mod ffi { #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] struct Shared { z: usize, } #[derive(PartialEq, PartialOrd)] struct SharedString { msg: String, } #[derive(Debug, Hash, PartialOrd, Ord)] enum Enum { AVal, BVal = 2020, #[cxx_name = "CVal"] LastVal, } #[namespace = "A"] #[derive(Copy, Clone, Default)] struct AShared { #[cxx_name = "type"] z: usize, } #[namespace = "A"] enum AEnum { AAVal, ABVal = 2020, ACVal, } #[namespace = "A::B"] enum ABEnum { ABAVal, ABBVal = 2020, ABCVal, } #[namespace = "A::B"] #[derive(Clone)] struct ABShared { z: usize, } #[namespace = "first"] struct First { second: Box<Second>, } #[namespace = "second"] #[derive(Hash)] struct Second { i: i32, e: COwnedEnum, } pub struct Array { a: [i32; 4], b: Buffer, } #[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct StructWithLifetime<'a> { s: &'a str, } unsafe extern "C++" { include!("tests/ffi/tests.h"); type C; fn c_return_primitive() -> usize; fn c_return_shared() -> Shared; fn c_return_box() -> Box<R>; fn c_return_unique_ptr() -> UniquePtr<C>; fn c_return_shared_ptr() -> SharedPtr<C>; fn c_return_ref(shared: &Shared) -> &usize; fn c_return_mut(shared: &mut Shared) -> &mut usize; fn c_return_str(shared: &Shared) -> &str; fn c_return_slice_char(shared: &Shared) -> &[c_char]; fn c_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8]; fn c_return_rust_string() -> String; fn c_return_rust_string_lossy() -> String; fn c_return_unique_ptr_string() -> UniquePtr<CxxString>; fn c_return_unique_ptr_vector_u8() -> UniquePtr<CxxVector<u8>>; fn c_return_unique_ptr_vector_f64() -> UniquePtr<CxxVector<f64>>; fn c_return_unique_ptr_vector_string() -> UniquePtr<CxxVector<CxxString>>; fn c_return_unique_ptr_vector_shared() -> UniquePtr<CxxVector<Shared>>; fn c_return_unique_ptr_vector_opaque() -> UniquePtr<CxxVector<C>>; fn c_return_ref_vector(c: &C) -> &CxxVector<u8>; fn c_return_mut_vector(c: Pin<&mut C>) -> Pin<&mut CxxVector<u8>>; fn c_return_rust_vec_u8() -> Vec<u8>; fn c_return_ref_rust_vec(c: &C) -> &Vec<u8>; fn c_return_mut_rust_vec(c: Pin<&mut C>) -> &mut Vec<u8>; fn c_return_rust_vec_string() -> Vec<String>; fn c_return_rust_vec_bool() -> Vec<bool>; fn c_return_identity(_: usize) -> usize; fn c_return_sum(_: usize, _: usize) -> usize; fn c_return_enum(n: u16) -> Enum; fn c_return_ns_ref(shared: &AShared) -> &usize; fn c_return_nested_ns_ref(shared: &ABShared) -> &usize; fn c_return_ns_enum(n: u16) -> AEnum; fn c_return_nested_ns_enum(n: u16) -> ABEnum; fn c_return_const_ptr(n: usize) -> *const C; fn c_return_mut_ptr(n: usize) -> *mut C; fn c_take_primitive(n: usize); fn c_take_shared(shared: Shared); fn c_take_box(r: Box<R>); fn c_take_ref_r(r: &R); fn c_take_ref_c(c: &C); fn c_take_str(s: &str); fn c_take_slice_char(s: &[c_char]); fn c_take_slice_shared(s: &[Shared]); fn c_take_slice_shared_sort(s: &mut [Shared]); fn c_take_slice_r(s: &[R]); fn c_take_slice_r_sort(s: &mut [R]); fn c_take_rust_string(s: String); fn c_take_unique_ptr_string(s: UniquePtr<CxxString>); fn c_take_unique_ptr_vector_u8(v: UniquePtr<CxxVector<u8>>); fn c_take_unique_ptr_vector_f64(v: UniquePtr<CxxVector<f64>>); fn c_take_unique_ptr_vector_string(v: UniquePtr<CxxVector<CxxString>>); fn c_take_unique_ptr_vector_shared(v: UniquePtr<CxxVector<Shared>>); fn c_take_ref_vector(v: &CxxVector<u8>); fn c_take_rust_vec(v: Vec<u8>); fn c_take_rust_vec_shared(v: Vec<Shared>); fn c_take_rust_vec_string(v: Vec<String>); fn c_take_rust_vec_index(v: Vec<u8>); fn c_take_rust_vec_shared_index(v: Vec<Shared>); fn c_take_rust_vec_shared_push(v: Vec<Shared>); fn c_take_rust_vec_shared_truncate(v: Vec<Shared>); fn c_take_rust_vec_shared_clear(v: Vec<Shared>); fn c_take_rust_vec_shared_forward_iterator(v: Vec<Shared>); fn c_take_rust_vec_shared_sort(v: Vec<Shared>); fn c_take_ref_rust_vec(v: &Vec<u8>); fn c_take_ref_rust_vec_string(v: &Vec<String>); fn c_take_ref_rust_vec_index(v: &Vec<u8>); fn c_take_ref_rust_vec_copy(v: &Vec<u8>); fn c_take_ref_shared_string(s: &SharedString) -> &SharedString; fn c_take_callback(callback: fn(String) -> usize); fn c_take_callback_ref(callback: fn(&String)); #[cxx_name = "c_take_callback_ref"] fn c_take_callback_ref_lifetime<'a>(callback: fn(&'a String)); fn c_take_callback_mut(callback: fn(&mut String)); fn c_take_enum(e: Enum); fn c_take_ns_enum(e: AEnum); fn c_take_nested_ns_enum(e: ABEnum); fn c_take_ns_shared(shared: AShared); fn c_take_nested_ns_shared(shared: ABShared); fn c_take_rust_vec_ns_shared(v: Vec<AShared>); fn c_take_rust_vec_nested_ns_shared(v: Vec<ABShared>); unsafe fn c_take_const_ptr(c: *const C) -> usize; unsafe fn c_take_mut_ptr(c: *mut C) -> usize; fn c_try_return_void() -> Result<()>; fn c_try_return_primitive() -> Result<usize>; fn c_fail_return_primitive() -> Result<usize>; fn c_try_return_box() -> Result<Box<R>>; fn c_try_return_ref(s: &String) -> Result<&String>; fn c_try_return_str(s: &str) -> Result<&str>; fn c_try_return_sliceu8(s: &[u8]) -> Result<&[u8]>; fn c_try_return_mutsliceu8(s: &mut [u8]) -> Result<&mut [u8]>; fn c_try_return_rust_string() -> Result<String>; fn c_try_return_unique_ptr_string() -> Result<UniquePtr<CxxString>>; fn c_try_return_rust_vec() -> Result<Vec<u8>>; fn c_try_return_rust_vec_string() -> Result<Vec<String>>; fn c_try_return_ref_rust_vec(c: &C) -> Result<&Vec<u8>>; fn get(self: &C) -> usize; fn set(self: Pin<&mut C>, n: usize) -> usize; fn get2(&self) -> usize; fn getRef(self: &C) -> &usize; fn getMut(self: Pin<&mut C>) -> &mut usize; fn set_succeed(self: Pin<&mut C>, n: usize) -> Result<usize>; fn get_fail(self: Pin<&mut C>) -> Result<usize>; fn c_method_on_shared(self: &Shared) -> usize; fn c_method_ref_on_shared(self: &Shared) -> &usize; fn c_method_mut_on_shared(self: &mut Shared) -> &mut usize; fn c_set_array(self: &mut Array, value: i32); fn c_get_use_count(weak: &WeakPtr<C>) -> usize; #[rust_name = "i32_overloaded_method"] fn cOverloadedMethod(&self, x: i32) -> String; #[rust_name = "str_overloaded_method"] fn cOverloadedMethod(&self, x: &str) -> String; #[rust_name = "i32_overloaded_function"] fn cOverloadedFunction(x: i32) -> String; #[rust_name = "str_overloaded_function"] fn cOverloadedFunction(x: &str) -> String; #[namespace = "other"] fn ns_c_take_ns_shared(shared: AShared); } extern "C++" { include!("tests/ffi/module.rs.h"); type COwnedEnum; type Job = crate::module::ffi::Job; } extern "Rust" { #[derive(ExternType)] type Reference<'a>; } unsafe extern "C++" { type Borrow<'a>; fn c_return_borrow<'a>(s: &'a CxxString) -> UniquePtr<Borrow<'a>>; #[rust_name = "c_return_borrow_elided"] fn c_return_borrow(s: &CxxString) -> UniquePtr<Borrow>; fn const_member(self: &Borrow); fn nonconst_member(self: Pin<&mut Borrow>); } #[repr(u32)] #[derive(Hash)] enum COwnedEnum { #[cxx_name = "CVAL1"] CVal1, #[cxx_name = "CVAL2"] CVal2, } extern "C++" { type Buffer = crate::Buffer; } extern "Rust" { type R; fn r_return_primitive() -> usize; fn r_return_shared() -> Shared; fn r_return_box() -> Box<R>; fn r_return_unique_ptr() -> UniquePtr<C>; fn r_return_shared_ptr() -> SharedPtr<C>; fn r_return_ref(shared: &Shared) -> &usize; fn r_return_mut(shared: &mut Shared) -> &mut usize; fn r_return_str(shared: &Shared) -> &str; fn r_return_sliceu8(shared: &Shared) -> &[u8]; fn r_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8]; fn r_return_rust_string() -> String; fn r_return_unique_ptr_string() -> UniquePtr<CxxString>; fn r_return_rust_vec() -> Vec<u8>; fn r_return_rust_vec_string() -> Vec<String>; fn r_return_rust_vec_extern_struct() -> Vec<Job>; fn r_return_ref_rust_vec(shared: &Shared) -> &Vec<u8>; fn r_return_mut_rust_vec(shared: &mut Shared) -> &mut Vec<u8>; fn r_return_identity(_: usize) -> usize; fn r_return_sum(_: usize, _: usize) -> usize; fn r_return_enum(n: u32) -> Enum; fn r_take_primitive(n: usize); fn r_take_shared(shared: Shared); fn r_take_box(r: Box<R>); fn r_take_unique_ptr(c: UniquePtr<C>); fn r_take_shared_ptr(c: SharedPtr<C>); fn r_take_ref_r(r: &R); fn r_take_ref_c(c: &C); fn r_take_str(s: &str); fn r_take_slice_char(s: &[c_char]); fn r_take_rust_string(s: String); fn r_take_unique_ptr_string(s: UniquePtr<CxxString>); fn r_take_ref_vector(v: &CxxVector<u8>); fn r_take_ref_empty_vector(v: &CxxVector<u64>); fn r_take_rust_vec(v: Vec<u8>); fn r_take_rust_vec_string(v: Vec<String>); fn r_take_ref_rust_vec(v: &Vec<u8>); fn r_take_ref_rust_vec_string(v: &Vec<String>); fn r_take_enum(e: Enum); fn r_try_return_void() -> Result<()>; fn r_try_return_primitive() -> Result<usize>; fn r_try_return_box() -> Result<Box<R>>; fn r_fail_return_primitive() -> Result<usize>; fn r_try_return_sliceu8(s: &[u8]) -> Result<&[u8]>; fn r_try_return_mutsliceu8(s: &mut [u8]) -> Result<&mut [u8]>; fn get(self: &R) -> usize; fn set(self: &mut R, n: usize) -> usize; fn r_method_on_shared(self: &Shared) -> String; fn r_get_array_sum(self: &Array) -> i32; #[cxx_name = "rAliasedFunction"] fn r_aliased_function(x: i32) -> String; } struct Dag0 { i: i32, } struct Dag1 { dag2: Dag2, vec: Vec<Dag3>, } struct Dag2 { dag4: Dag4, } struct Dag3 { dag1: Dag1, } struct Dag4 { dag0: Dag0, } impl Box<Shared> {} impl CxxVector<SharedString> {} } mod other { use cxx::kind::{Opaque, Trivial}; use cxx::{type_id, CxxString, ExternType}; #[repr(C)] pub struct D { pub d: u64, } #[repr(C)] pub struct E { e: u64, e_str: CxxString, } pub mod f { use cxx::kind::Opaque; use cxx::{type_id, CxxString, ExternType}; #[repr(C)] pub struct F { e: u64, e_str: CxxString, } unsafe impl ExternType for F { type Id = type_id!("F::F"); type Kind = Opaque; } } #[repr(C)] pub struct G { pub g: u64, } unsafe impl ExternType for G { type Id = type_id!("G::G"); type Kind = Trivial; } unsafe impl ExternType for D { type Id = type_id!("tests::D"); type Kind = Trivial; } unsafe impl ExternType for E { type Id = type_id!("tests::E"); type Kind = Opaque; } } #[derive(PartialEq, Debug)] pub struct R(pub usize); impl R { fn get(&self) -> usize { self.0 } fn set(&mut self, n: usize) -> usize { self.0 = n; n } } pub struct Reference<'a>(&'a String); impl ffi::Shared { fn r_method_on_shared(&self) -> String { "2020".to_owned() } } impl ffi::Array { pub fn r_get_array_sum(&self) -> i32 { self.a.iter().sum() } } #[derive(Default)] #[repr(C)] pub struct Buffer([c_char; 12]); unsafe impl ExternType for Buffer { type Id = type_id!("tests::Buffer"); type Kind = cxx::kind::Trivial; } #[derive(Debug)] struct Error; impl std::error::Error for Error {} impl Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("rust error") } } fn r_return_primitive() -> usize { 2020 } fn r_return_shared() -> ffi::Shared { ffi::Shared { z: 2020 } } fn r_return_box() -> Box<R> { Box::new(R(2020)) } fn r_return_unique_ptr() -> UniquePtr<ffi::C> { extern "C" { fn cxx_test_suite_get_unique_ptr() -> *mut ffi::C; } unsafe { UniquePtr::from_raw(cxx_test_suite_get_unique_ptr()) } } fn r_return_shared_ptr() -> SharedPtr<ffi::C> { extern "C" { fn cxx_test_suite_get_shared_ptr(repr: *mut SharedPtr<ffi::C>); } let mut shared_ptr = MaybeUninit::<SharedPtr<ffi::C>>::uninit(); let repr = shared_ptr.as_mut_ptr(); unsafe { cxx_test_suite_get_shared_ptr(repr); shared_ptr.assume_init() } } fn r_return_ref(shared: &ffi::Shared) -> &usize { &shared.z } fn r_return_mut(shared: &mut ffi::Shared) -> &mut usize { &mut shared.z } fn r_return_str(shared: &ffi::Shared) -> &str { let _ = shared; "2020" } fn r_return_sliceu8(shared: &ffi::Shared) -> &[u8] { let _ = shared; b"2020" } fn r_return_mutsliceu8(slice: &mut [u8]) -> &mut [u8] { slice } fn r_return_rust_string() -> String { "2020".to_owned() } fn r_return_unique_ptr_string() -> UniquePtr<CxxString> { extern "C" { fn cxx_test_suite_get_unique_ptr_string() -> *mut CxxString; } unsafe { UniquePtr::from_raw(cxx_test_suite_get_unique_ptr_string()) } } fn r_return_rust_vec() -> Vec<u8> { Vec::new() } fn r_return_rust_vec_string() -> Vec<String> { Vec::new() } fn r_return_rust_vec_extern_struct() -> Vec<ffi::Job> { Vec::new() } fn r_return_ref_rust_vec(shared: &ffi::Shared) -> &Vec<u8> { let _ = shared; unimplemented!() } fn r_return_mut_rust_vec(shared: &mut ffi::Shared) -> &mut Vec<u8> { let _ = shared; unimplemented!() } fn r_return_identity(n: usize) -> usize { n } fn r_return_sum(n1: usize, n2: usize) -> usize { n1 + n2 } fn r_return_enum(n: u32) -> ffi::Enum { if n == 0 { ffi::Enum::AVal } else if n <= 2020 { ffi::Enum::BVal } else { ffi::Enum::LastVal } } fn r_take_primitive(n: usize) { assert_eq!(n, 2020); } fn r_take_shared(shared: ffi::Shared) { assert_eq!(shared.z, 2020); } fn r_take_box(r: Box<R>) { let _ = r; } fn r_take_unique_ptr(c: UniquePtr<ffi::C>) { let _ = c; } fn r_take_shared_ptr(c: SharedPtr<ffi::C>) { let _ = c; } fn r_take_ref_r(r: &R) { let _ = r; } fn r_take_ref_c(c: &ffi::C) { let _ = c; } fn r_take_str(s: &str) { assert_eq!(s, "2020"); } fn r_take_rust_string(s: String) { assert_eq!(s, "2020"); } fn r_take_slice_char(s: &[c_char]) { assert_eq!(s.len(), 5); let s = cast::c_char_to_unsigned(s); assert_eq!(std::str::from_utf8(s).unwrap(), "2020\0"); } fn r_take_unique_ptr_string(s: UniquePtr<CxxString>) { assert_eq!(s.as_ref().unwrap().to_str().unwrap(), "2020"); } fn r_take_ref_vector(v: &CxxVector<u8>) { let slice = v.as_slice(); assert_eq!(slice, [20, 2, 0]); } fn r_take_ref_empty_vector(v: &CxxVector<u64>) { assert!(v.as_slice().is_empty()); assert!(v.is_empty()); } fn r_take_rust_vec(v: Vec<u8>) { let _ = v; } fn r_take_rust_vec_string(v: Vec<String>) { let _ = v; } fn r_take_ref_rust_vec(v: &Vec<u8>) { let _ = v; } fn r_take_ref_rust_vec_string(v: &Vec<String>) { let _ = v; } fn r_take_enum(e: ffi::Enum) { let _ = e; } fn r_try_return_void() -> Result<(), Error> { Ok(()) } fn r_try_return_primitive() -> Result<usize, Error> { Ok(2020) } fn r_try_return_box() -> Result<Box<R>, Error> { Ok(Box::new(R(2020))) } fn r_fail_return_primitive() -> Result<usize, Error> { Err(Error) } fn r_try_return_sliceu8(slice: &[u8]) -> Result<&[u8], Error> { Ok(slice) } fn r_try_return_mutsliceu8(slice: &mut [u8]) -> Result<&mut [u8], Error> { Ok(slice) } fn r_aliased_function(x: i32) -> String { x.to_string() }
pub mod stone_game { use std::collections::HashMap; pub fn stone_game_1(piles: Vec<i32>) -> bool { let mut dp: HashMap<(usize, usize), i32> = HashMap::new(); let n = piles.len(); fn dpf(l: usize, r: usize, dp: &mut HashMap<(usize, usize), i32>, piles: &Vec<i32>) -> i32 { if l > r { return 0; } if dp.contains_key(&(l, r)) { return dp.get(&(l, r)).unwrap().to_owned(); } let is_even = (r - l) % 2 != 0; let left: i32 = if is_even { piles.get(l).unwrap().to_owned() } else { 0 }; let right = if is_even { piles.get(r).unwrap().to_owned() } else { 0 }; let v = std::cmp::max( dpf(l + 1, r, dp, piles) + left, dpf(l, r - 1, dp, piles) + right, ); // let v = (dpf(l + 1, r, dp, piles) + left).max(dpf(l, r - 1, dp, piles) + right); dp.insert((l, r), v); dp.get(&(l, r)).unwrap().to_owned() }; dpf(0, n - 1, &mut dp, &piles) > 0 } #[test] fn test_stone_game_1() { assert_eq!(stone_game_1(vec![5, 3, 4, 5]), true); assert_eq!(stone_game_1(vec![3, 7, 2, 3]), true); } }
use serde::{Deserialize, Serialize}; use serde_json::Result; #[derive(Serialize, Deserialize, Debug)] struct Person { name: String, age: u8, phones: Vec<String>, } #[derive(Serialize)] struct Config { ip: String, port: Option<u16>, keys: Keys, } #[derive(Serialize)] struct Keys { github: String, travis: Option<String>, } fn json_test() { let data = r#" { "name": "John Doe", "age": 43, "phones": [ "+44 1234567", "+44 2345678" ] }"#; let r: serde_json::Result<Person> = serde_json::from_str(data); if r.is_ok() { let p: Person = r.unwrap(); println!("{:?}", serde_json::to_string(&p)); } else { println!("Failed to deserialize json string"); } } fn toml_test() { let data = "foo = 'bar'"; let value = data.parse::<toml::Value>().unwrap(); assert_eq!(value["foo"].as_str(), Some("bar")); let config = Config { ip: "127.0.0.1".to_string(), port: None, keys: Keys { github: "xxxxxxxxxxxxxxxxx".to_string(), travis: Some("yyyyyyyyyyyyyyyyy".to_string()), }, }; let toml = toml::to_string(&config).unwrap(); } pub fn serde_tests() { json_test(); toml_test(); }
extern crate yada; use std::fs::File; use std::io::{Read, Write}; use yada::builder::DoubleArrayBuilder; use yada::DoubleArray; fn main() -> Result<(), Box<dyn std::error::Error>> { // filename to save and load let filename = "load_from_file_example.da"; // make a keyset which have key-value pairs let keyset = &[ ("a".as_bytes(), 0), ("aa".as_bytes(), 1), ("aaa".as_bytes(), 2), ("b".as_bytes(), 3), ("bcd".as_bytes(), 4), ]; // build a double-array trie binary let da_bytes = DoubleArrayBuilder::build(keyset); assert!(da_bytes.is_some()); // create a double-array trie instance let da = DoubleArray::new(da_bytes.unwrap()); // save to file let mut file = File::create(filename)?; file.write_all(da.0.as_slice())?; file.flush()?; // load from file let mut file = File::open(filename)?; let mut buf = Vec::new(); let _ = file.read_to_end(&mut buf)?; let da = DoubleArray::new(buf); // test search for (key, value) in keyset.iter() { let v = da.exact_match_search(key).unwrap(); assert_eq!(v, *value); } assert_eq!( da.common_prefix_search(&"aaaa").collect::<Vec<_>>(), vec![(0, 1), (1, 2), (2, 3)] ); assert_eq!( da.common_prefix_search(&"bcde").collect::<Vec<_>>(), vec![(3, 1), (4, 3)] ); Ok(()) }
// Generated by `scripts/generate.js` use std::os::raw::c_char; use std::ops::Deref; use std::ptr; use std::cmp; use std::mem; use utils::c_bindings::*; use utils::vk_convert::*; use utils::vk_null::*; use utils::vk_ptr::*; use utils::vk_traits::*; use vulkan::vk::*; use vulkan::vk::{VkIndexType,RawVkIndexType}; /// Wrapper for [VkBindIndexBufferIndirectCommandNV](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkBindIndexBufferIndirectCommandNV.html). #[derive(Debug, Clone)] pub struct VkBindIndexBufferIndirectCommand { pub buffer_address: u64, pub size: usize, pub index_type: VkIndexType, } #[doc(hidden)] #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct RawVkBindIndexBufferIndirectCommand { pub buffer_address: u64, pub size: u32, pub index_type: RawVkIndexType, } impl VkWrappedType<RawVkBindIndexBufferIndirectCommand> for VkBindIndexBufferIndirectCommand { fn vk_to_raw(src: &VkBindIndexBufferIndirectCommand, dst: &mut RawVkBindIndexBufferIndirectCommand) { dst.buffer_address = src.buffer_address; dst.size = vk_to_raw_value(&src.size); dst.index_type = vk_to_raw_value(&src.index_type); } } impl VkRawType<VkBindIndexBufferIndirectCommand> for RawVkBindIndexBufferIndirectCommand { fn vk_to_wrapped(src: &RawVkBindIndexBufferIndirectCommand) -> VkBindIndexBufferIndirectCommand { VkBindIndexBufferIndirectCommand { buffer_address: src.buffer_address, size: u32::vk_to_wrapped(&src.size), index_type: RawVkIndexType::vk_to_wrapped(&src.index_type), } } } impl Default for VkBindIndexBufferIndirectCommand { fn default() -> VkBindIndexBufferIndirectCommand { VkBindIndexBufferIndirectCommand { buffer_address: 0, size: 0, index_type: Default::default(), } } } impl VkSetup for VkBindIndexBufferIndirectCommand { fn vk_setup(&mut self, fn_table: *mut VkFunctionTable) { } } impl VkFree for RawVkBindIndexBufferIndirectCommand { fn vk_free(&self) { } }
mod couche; mod neurone; pub mod perceptron; mod learning; mod tests;
use std::io; use std::cmp::Ordering; use rand::Rng; fn main() { println!("Hello, world! {}", sum(10, 20)); ownership(); } fn ownership(){ let mut s = String::from("Hello"); some(&mut s); // Some Comments. println!("{}", s); // Feature 4 SQ Commit 3. // r2 } fn some(a : &mut String){ a.push_str(" some"); } fn array_sample(){ let a = [1,2,3]; let mut index = String::new(); println!("Enter Index"); io::stdin() .read_line(&mut index) .expect("Not an number"); let index: usize = index.trim().parse().expect("Not an number"); println!("Index value is {}", a[index]); } fn tuple_sample() { let tup = (10, 20, 30); let (x, y, z) = tup; println! ("{} {} {}", x, y, z); } fn sum(x: usize, y: usize) -> usize{ x + y } fn get_and_return(x: usize) -> usize { x } fn guess_rnd() { let secret_number = rand::thread_rng().gen_range(1..101); println!("Secret is {}", secret_number); loop { println!("Please input your guess."); let mut guess = String::new(); let _x = io::stdin() .read_line(&mut guess) .expect("Failed to read line."); //let guess:u32 = guess.trim().parse().expect("Please type a number!"); let guess:u32 = match guess.trim().parse() { Ok(num)=>num, Err(_)=>continue }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => {println!("You win!");break;}, } } }
use crate::{ models::{NoIdMember, Member, User}, mapper, errors::* }; pub fn join(current: User, community_id: i32) -> Result<Member, ErrCode>{ let no_id_member = NoIdMember{ user_id: current.id, community_id }; mapper::member::create(&no_id_member) }
#![allow(clippy::too_many_arguments, clippy::trivially_copy_pass_by_ref, clippy::missing_safety_doc)] pub mod vk; pub mod builder; use lazy_static::lazy_static; use std::ffi::CStr; use std::os::raw::{c_void, c_int}; use std::mem; use std::mem::MaybeUninit; use std::path::Path; use std::ptr; use std::result; use std::slice; use shared_library::dynamic_library::DynamicLibrary; #[doc(no_inline)] pub use self::builder::*; // For methods to be generic over array length (until there is language support) pub trait Array { type Item; fn as_mut_ptr(&mut self) -> *mut Self::Item; fn len() -> usize; } macro_rules! array_impl { ($len:expr) => ( impl<T> Array for [T; $len] { type Item = T; fn as_mut_ptr(&mut self) -> *mut T { self as *mut _ as *mut _ } fn len() -> usize { $len } } ) } array_impl!(1); array_impl!(2); array_impl!(3); array_impl!(4); array_impl!(5); array_impl!(6); array_impl!(7); array_impl!(8); pub type Result<T> = result::Result<T, vk::Result>; struct Lib { pub lib: DynamicLibrary, pub fp_get_instance_proc_addr: vk::FnGetInstanceProcAddr, } #[derive(Debug, Clone)] pub enum LoaderError { DynamicLibrary(String), MissingSymbol(String), Vulkan(vk::Result), } impl From<vk::Result> for LoaderError { fn from(err: vk::Result) -> Self { LoaderError::Vulkan(err) } } pub type LoaderResult<T> = result::Result<T, LoaderError>; #[cfg(unix)] const DL_PATH: &str = "libvulkan.so.1"; #[cfg(windows)] const DL_PATH: &str = "vulkan-1.dll"; impl Lib { pub fn new() -> LoaderResult<Self> { match DynamicLibrary::open(Some(&Path::new(&DL_PATH))) { Ok(lib) => match unsafe { lib.symbol("vkGetInstanceProcAddr") .map(|f: *mut c_void| mem::transmute(f)) } { Ok(fp_get_instance_proc_addr) => Ok(Self { lib, fp_get_instance_proc_addr, }), Err(s) => Err(LoaderError::MissingSymbol(s)), }, Err(s) => Err(LoaderError::DynamicLibrary(s)), } } pub unsafe fn get_instance_proc_addr(&self, name: &CStr) -> Option<vk::FnVoidFunction> { (self.fp_get_instance_proc_addr)(None, name.as_ptr()) } } lazy_static! { static ref LIB: LoaderResult<Lib> = Lib::new(); }
use aead::consts::{U16, U4}; use aead::generic_array::typenum::type_operators::{IsGreaterOrEqual, IsLessOrEqual}; use aead::generic_array::typenum::Unsigned; use aead::generic_array::ArrayLength; mod private { // Sealed traits stop other crates from implementing any traits that use it. pub trait SealedTag {} impl<T> SealedTag for T where T: super::IsGreaterOrEqual<super::U4> + super::IsLessOrEqual<super::U16> { } } pub trait TagSize: ArrayLength<u8> + Unsigned + private::SealedTag {} impl<T> TagSize for T where T: ArrayLength<u8> + IsGreaterOrEqual<U4> + IsLessOrEqual<U16> {}
use std::collections::{HashMap, HashSet}; use super::{ posting_list::{DocId, Frequency, PostingList}, retrieve_tokens::{get_document_names, get_punctuations, get_stop_words, tokenize_document}, }; use tokenizers::Tokenizer; pub struct IndexData { pub normalized_index: HashMap<String, PostingList>, pub document_lengths: HashMap<DocId, Frequency>, pub stop_words: HashSet<String>, pub punctuations: HashSet<String>, pub total_tokens_count: Frequency, } pub fn build_index() -> IndexData { let stop_words = get_stop_words().unwrap(); let punctuations = get_punctuations().unwrap(); let tokenizer = Tokenizer::from_pretrained("bert-base-cased", None).unwrap(); let mut index = HashMap::<String, PostingList>::new(); let mut document_lengths = HashMap::<DocId, Frequency>::new(); let parent = "data/documents".to_string(); let mut total_tokens_count: Frequency = 0; for name in get_document_names(&parent).unwrap() { let mut path = parent.clone(); path.push('/'); path.push_str(&name); let doc_id = name.split(".").next().unwrap().parse::<DocId>().unwrap(); let tokens = tokenize_document(&tokenizer, &path).unwrap(); let final_tokens = tokens .iter() .filter(|&token| { if stop_words.contains(token) || punctuations.contains(token) { false } else { true } }) .map(|a| a.to_string()); let mut counter: Frequency = 0; for token in final_tokens { counter += 1; if let Some(list) = index.get_mut(&token) { if !list.dimension_map.contains_key(&doc_id) { list.document_frequency += 1; } list.dimension_map .entry(doc_id) .and_modify(|f| *f += 1.0) .or_insert(1.0); } else { index.insert(token, PostingList::with_doc_id(doc_id)); } } document_lengths.insert(doc_id, counter); total_tokens_count += counter; } index.iter_mut().for_each(|(_, value)| { value .dimension_map .values_mut() .for_each(|v| *v = 1.0 + v.log10()); }); index.iter_mut().for_each(|(_, value)| { let sum_of_squares: f64 = value.dimension_map.values().fold(0.0, |acc, x| acc + x * x); let magnitude = sum_of_squares.sqrt(); for v in value.dimension_map.values_mut() { *v = *v / magnitude; } }); IndexData { normalized_index: index, document_lengths, stop_words, punctuations, total_tokens_count, } }
extern crate itemops; use itemops::ops::*; #[test] fn sum_step_works() { let mut v = vec![5, 6, 14, 2, 17, 21]; assert_eq!(v.sum_step(2), 36); assert_eq!(v[1..4].sum_step(1), 22); assert_eq!(v.sum_step(3), 7); assert_eq!(v.sum_step(0), 0); assert_eq!(v.sum_step(6), 5); v.clear(); assert_eq!(v.sum_step(2), 0); } #[test] #[should_panic] fn sum_step_panics() { let a = [std::i32::MAX, 1]; a.sum_step(1); } #[test] fn product_step_works() { let a = [7, 2, 9, 4, 5, 3]; assert_eq!(a.product_step(1), 7560); assert_eq!(a.product_step(2), 315); assert_eq!(a.product_step(3), 28); assert_eq!(a.product_step(0), 0); assert_eq!(a.product_step(6), 7); } #[test] #[should_panic] fn product_step_panics() { let v = vec![std::i16::MAX, 2]; v.product_step(1); }
use std::collections::HashMap; fn main() { let n = read(); let mut v = Vec::new(); for _ in 0..n { let s = read_line_str(); v.push(s); } let mut m : usize = 0; let mut a : usize = 0; let mut r : usize = 0; let mut c : usize = 0; let mut h : usize = 0; for i in &v { let s = i.chars().nth(0).unwrap(); if s == 'M' { m += 1; } if s == 'A' { a += 1; } if s == 'R' { r += 1; } if s == 'C' { c += 1; } if s == 'H' { h += 1; } } let P : [usize; 10] = [0, 0, 0, 0, 0, 0, 1, 1, 1, 2]; let Q : [usize; 10] = [1, 1, 1, 2, 2, 3, 2, 2, 3, 3]; let R : [usize; 10] = [2, 3, 4, 3, 4, 4, 3, 4, 4, 4]; let mut D : [usize; 5] = [0; 5]; D[0] = m; D[1] = a; D[2] = r; D[3] = c; D[4] = h; let mut res : usize = 0; for d in 0..10 { res += D [ P [ d ]]* D [ Q [ d ]]* D [ R [ d ]]; } println!("{}", res); } fn read() -> i32 { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_line_str() -> String { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); return s; }
use num::bigint::Sign; use num::{BigInt, BigRational, One, Signed, Zero}; use std::iter::{Product, Sum}; use std::ops::{ Add, AddAssign, Deref, Div, DivAssign, Mul, MulAssign, Neg, Rem, RemAssign, Sub, SubAssign, }; use std::rc::Rc; #[derive(Clone, Debug, Hash, Ord, PartialOrd, PartialEq, Eq)] pub struct RationalVar { value: Rc<BigRational>, } impl RationalVar { pub fn new(value: BigRational) -> RationalVar { RationalVar { value: Rc::new(value), } } pub fn into_inner(self) -> BigRational { Rc::try_unwrap(self.value).unwrap_or_else(|x| (*x).clone()) } pub fn from_integer(x: BigInt) -> RationalVar { Self::new(BigRational::from_integer(x)) } pub fn sign(&self) -> Sign { if self.is_zero() { Sign::NoSign } else if self.is_positive() { Sign::Plus } else { // self.is_negative() Sign::Minus } } } impl Deref for RationalVar { type Target = BigRational; fn deref(&self) -> &Self::Target { &*self.value } } macro_rules! impl_op { ($trait:ty, $fn_name: ident, $op:tt) => { impl $trait for RationalVar { type Output = Self; fn $fn_name(self, rhs: Self) -> Self::Output { Self::new(&*self $op &*rhs) } } }; } impl_op!(Add, add, +); impl_op!(Sub, sub, -); impl_op!(Mul, mul, *); impl_op!(Div, div, /); impl_op!(Rem, rem, %); macro_rules! impl_iop { ($trait:ty, $fn_name: ident, $op:tt) => { impl $trait for RationalVar { fn $fn_name(&mut self, rhs: Self) { *self = self.clone() $op rhs; } } }; } impl_iop!(AddAssign, add_assign, +); impl_iop!(SubAssign, sub_assign, -); impl_iop!(MulAssign, mul_assign, *); impl_iop!(DivAssign, div_assign, /); impl_iop!(RemAssign, rem_assign, %); impl Neg for RationalVar { type Output = Self; fn neg(self) -> Self::Output { Self::new(-(*self).clone()) } } impl Zero for RationalVar { fn zero() -> Self { RationalVar::new(Zero::zero()) } fn is_zero(&self) -> bool { self.value.is_zero() } } impl One for RationalVar { fn one() -> Self { RationalVar::new(One::one()) } fn is_one(&self) -> bool { self.value.is_one() } } impl From<BigRational> for RationalVar { fn from(x: BigRational) -> Self { Self::new(x) } } impl Sum for RationalVar { fn sum<I: Iterator<Item = Self>>(iter: I) -> Self { iter.fold(BigRational::zero(), |sum, num| sum + &*num) .into() } } impl Product for RationalVar { fn product<I: Iterator<Item = Self>>(iter: I) -> Self { iter.fold(BigRational::one(), |sum, num| sum * &*num).into() } }
// 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. use std::marker::PhantomData; use bumpalo::Bump; use ocamlrep::Allocator; use ocamlrep::ToOcamlRep; use oxidized::aast; use oxidized::aast_visitor::NodeMut; use oxidized::aast_visitor::Params; use oxidized::aast_visitor::VisitorMut; use pos::ToOxidized; use ty::local; use ty::local::Ty; use ty::reason::Reason; use crate::inference_env::InferenceEnv; #[derive(Clone, Debug)] pub struct SavedEnv<R: Reason> { pub inf_env: InferenceEnv<R>, } pub type Program<R> = aast::Program<Ty<R>, SavedEnv<R>>; pub type Def<R> = aast::Def<Ty<R>, SavedEnv<R>>; pub type Expr<R> = aast::Expr<Ty<R>, SavedEnv<R>>; pub type Expr_<R> = aast::Expr_<Ty<R>, SavedEnv<R>>; pub type Stmt<R> = aast::Stmt<Ty<R>, SavedEnv<R>>; pub type Stmt_<R> = aast::Stmt_<Ty<R>, SavedEnv<R>>; pub type Block<R> = aast::Block<Ty<R>, SavedEnv<R>>; pub type Class_<R> = aast::Class_<Ty<R>, SavedEnv<R>>; pub type ClassId<R> = aast::ClassId<Ty<R>, SavedEnv<R>>; pub type TypeHint<R> = aast::TypeHint<Ty<R>>; pub type Targ<R> = aast::Targ<Ty<R>>; pub type ClassGetExpr<R> = aast::ClassGetExpr<Ty<R>, SavedEnv<R>>; pub type ClassTypeconstDef<R> = aast::ClassTypeconstDef<Ty<R>, SavedEnv<R>>; pub type UserAttribute<R> = aast::UserAttribute<Ty<R>, SavedEnv<R>>; pub type Fun_<R> = aast::Fun_<Ty<R>, SavedEnv<R>>; pub type FileAttribute<R> = aast::FileAttribute<Ty<R>, SavedEnv<R>>; pub type FunDef<R> = aast::FunDef<Ty<R>, SavedEnv<R>>; pub type FunParam<R> = aast::FunParam<Ty<R>, SavedEnv<R>>; pub type FuncBody<R> = aast::FuncBody<Ty<R>, SavedEnv<R>>; pub type Method_<R> = aast::Method_<Ty<R>, SavedEnv<R>>; pub type ClassVar<R> = aast::ClassVar<Ty<R>, SavedEnv<R>>; pub type ClassConst<R> = aast::ClassConst<Ty<R>, SavedEnv<R>>; pub type Tparam<R> = aast::Tparam<Ty<R>, SavedEnv<R>>; pub type Typedef<R> = aast::Typedef<Ty<R>, SavedEnv<R>>; pub type Gconst<R> = aast::Gconst<Ty<R>, SavedEnv<R>>; impl<R: Reason> ToOcamlRep for SavedEnv<R> { fn to_ocamlrep<'a, A: Allocator>(&'a self, alloc: &'a A) -> ocamlrep::Value<'a> { // This implementation of `to_ocamlrep` (which allocates in an arena, // converts to OCaml, then drops the arena) violates a `ToOcamlRep` // requirement: we may not drop values after passing them to `alloc.add` // or invoking `to_ocamlrep`. See comment on impl of ToOcamlRep for Ty. // We must take care not to use `ocamlrep::Allocator::add_root` on // values containing this type. let bump = Bump::new(); let SavedEnv { inf_env } = self; let saved_env = oxidized_by_ref::tast::SavedEnv { tcopt: oxidized_by_ref::global_options::GlobalOptions::default_ref(), inference_env: bump.alloc(inf_env.to_oxidized(&bump)), tpenv: bump.alloc(oxidized_by_ref::type_parameter_env::TypeParameterEnv { tparams: Default::default(), consistent: false, }), condition_types: Default::default(), fun_tast_info: None, }; // SAFETY: Transmute away the lifetime to allow the arena-allocated // value to be converted to OCaml. Won't break type safety in Rust, but // will produce broken OCaml values if used with `add_root` (see comment // on impl of ToOcamlRep for Ty). let saved_env = unsafe { std::mem::transmute::< &'_ oxidized_by_ref::tast::SavedEnv<'_>, &'a oxidized_by_ref::tast::SavedEnv<'a>, >(&saved_env) }; saved_env.to_ocamlrep(alloc) } } pub struct TastExpander<R: Reason> { env: Option<SavedEnv<R>>, } impl<R: Reason> TastExpander<R> { fn new() -> Self { Self { env: None } } pub fn expand_program(program: &mut Program<R>) { Self::new().visit_program(&mut (), program).unwrap() } pub fn set_env(&mut self, env: SavedEnv<R>) { self.env = Some(env); } pub fn env(&mut self) -> &mut SavedEnv<R> { self.env.as_mut().unwrap() } fn exp_ty_mut(&mut self, ty: &mut Ty<R>) { *ty = self.env().inf_env.resolve_ty(ty); use local::Ty_::*; let r = ty.reason().clone(); match &**ty { Tnonnull | Tvar(..) | Tprim(..) | Tany => {} Tfun(ft) => *ty = Ty::fun(r, self.exp_fun_type(ft)), Tgeneric(n, args) => *ty = Ty::generic(r, *n, self.exp_tys(args)), Tclass(n, e, args) => *ty = Ty::class(r, n.clone(), *e, self.exp_tys(args)), Tunion(args) => *ty = Ty::union(r, self.exp_tys(args)), Tintersection(args) => *ty = Ty::intersection(r, self.exp_tys(args)), Toption(arg) => *ty = Ty::option(r, self.exp_ty(arg)), } } #[must_use] fn exp_ty(&mut self, ty: &Ty<R>) -> Ty<R> { let mut ty = ty.clone(); self.exp_ty_mut(&mut ty); ty } fn exp_tys(&mut self, tys: &[Ty<R>]) -> Vec<Ty<R>> { tys.iter().map(|ty| self.exp_ty(ty)).collect() } fn exp_fun_type(&mut self, ft: &local::FunType<R>) -> local::FunType<R> { let mut ft = ft.clone(); let local::FunType { tparams: _, params, ret, flags: _, } = &mut ft; params.iter_mut().for_each(|p| self.exp_fun_param_mut(p)); self.exp_ty_mut(ret); ft } fn exp_fun_param_mut(&mut self, fp: &mut local::FunParam<R>) { self.exp_ty_mut(&mut fp.ty); } } pub struct TastExpanderParams<R>(PhantomData<R>); impl<R: Reason> Params for TastExpanderParams<R> { type Context = (); type Error = (); type Ex = Ty<R>; type En = SavedEnv<R>; } impl<'node, R: Reason> VisitorMut<'node> for TastExpander<R> { type Params = TastExpanderParams<R>; fn object(&mut self) -> &mut dyn VisitorMut<'node, Params = Self::Params> { self } fn visit_expr( &mut self, c: &mut <Self::Params as Params>::Context, p: &'node mut aast::Expr<<Self::Params as Params>::Ex, <Self::Params as Params>::En>, ) -> Result<(), <Self::Params as Params>::Error> { self.exp_ty_mut(&mut p.0); p.recurse(c, self.object()) } fn visit_class_id( &mut self, c: &mut <Self::Params as Params>::Context, p: &'node mut aast::ClassId<<Self::Params as Params>::Ex, <Self::Params as Params>::En>, ) -> Result<(), <Self::Params as Params>::Error> { self.exp_ty_mut(&mut p.0); p.recurse(c, self.object()) } fn visit_ex( &mut self, _c: &mut <Self::Params as Params>::Context, p: &'node mut <Self::Params as Params>::Ex, ) -> Result<(), <Self::Params as Params>::Error> { self.exp_ty_mut(p); Ok(()) } fn visit_def( &mut self, c: &mut <Self::Params as Params>::Context, p: &'node mut aast::Def<<Self::Params as Params>::Ex, <Self::Params as Params>::En>, ) -> Result<(), <Self::Params as Params>::Error> { let env = match p { aast::Def::Fun(box f) => f.fun.annotation.clone(), aast::Def::Class(box c) => c.annotation.clone(), p => rupro_todo!(AST, "{:?}", p), }; self.set_env(env); p.recurse(c, self.object()) } fn visit_fun_( &mut self, c: &mut <Self::Params as Params>::Context, p: &'node mut aast::Fun_<<Self::Params as Params>::Ex, <Self::Params as Params>::En>, ) -> Result<(), <Self::Params as Params>::Error> { self.set_env(p.annotation.clone()); p.recurse(c, self.object()) } fn visit_method_( &mut self, c: &mut <Self::Params as Params>::Context, p: &'node mut aast::Method_<<Self::Params as Params>::Ex, <Self::Params as Params>::En>, ) -> Result<(), <Self::Params as Params>::Error> { self.set_env(p.annotation.clone()); p.recurse(c, self.object()) } }
#![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 AvailableScopeRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AvailableScopeRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AvailableScopeRequestProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub scopes: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CalculateExchangeRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CalculateExchangeRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangeRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExchangeRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CalculateExchangeRequestProperties { #[serde(rename = "reservationsToPurchase", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_purchase: Vec<PurchaseRequest>, #[serde(rename = "reservationsToExchange", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_exchange: Vec<ReservationToReturn>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangeRequestProperties { #[serde(rename = "sessionId", default, skip_serializing_if = "Option::is_none")] pub session_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationToReturn { #[serde(rename = "reservationId", default, skip_serializing_if = "Option::is_none")] pub reservation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quantity: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReservationStatusCode { None, Pending, Active, PurchaseError, PaymentInstrumentError, Split, Merged, Expired, Succeeded, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ErrorResponseCode { NotSpecified, InternalServerError, ServerTimeout, AuthorizationFailed, BadRequest, ClientCertificateThumbprintNotSet, InvalidRequestContent, OperationFailed, HttpMethodNotSupported, InvalidRequestUri, MissingTenantId, InvalidTenantId, InvalidReservationOrderId, InvalidReservationId, ReservationIdNotInReservationOrder, ReservationOrderNotFound, InvalidSubscriptionId, InvalidAccessToken, InvalidLocationId, UnauthenticatedRequestsThrottled, InvalidHealthCheckType, Forbidden, BillingScopeIdCannotBeChanged, AppliedScopesNotAssociatedWithCommerceAccount, PatchValuesSameAsExisting, RoleAssignmentCreationFailed, ReservationOrderCreationFailed, ReservationOrderNotEnabled, CapacityUpdateScopesFailed, UnsupportedReservationTerm, ReservationOrderIdAlreadyExists, RiskCheckFailed, CreateQuoteFailed, ActivateQuoteFailed, NonsupportedAccountId, PaymentInstrumentNotFound, MissingAppliedScopesForSingle, NoValidReservationsToReRate, #[serde(rename = "ReRateOnlyAllowedForEA")] ReRateOnlyAllowedForEa, OperationCannotBePerformedInCurrentState, InvalidSingleAppliedScopesCount, InvalidFulfillmentRequestParameters, NotSupportedCountry, InvalidRefundQuantity, PurchaseError, BillingCustomerInputError, BillingPaymentInstrumentSoftError, BillingPaymentInstrumentHardError, BillingTransientError, BillingError, FulfillmentConfigurationError, FulfillmentOutOfStockError, FulfillmentTransientError, FulfillmentError, CalculatePriceFailed, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuName { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CalculateExchangeOperationResultResponse { #[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<calculate_exchange_operation_result_response::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CalculateExchangeResponseProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<OperationResultError>, } pub mod calculate_exchange_operation_result_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Succeeded, Failed, Cancelled, Pending, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangeOperationResultResponse { #[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<exchange_operation_result_response::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExchangeResponseProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<OperationResultError>, } pub mod exchange_operation_result_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Succeeded, Failed, Cancelled, PendingRefunds, PendingPurchases, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationResultError { #[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 CalculateExchangeResponseProperties { #[serde(rename = "sessionId", default, skip_serializing_if = "Option::is_none")] pub session_id: Option<String>, #[serde(rename = "netPayable", default, skip_serializing_if = "Option::is_none")] pub net_payable: Option<Price>, #[serde(rename = "refundsTotal", default, skip_serializing_if = "Option::is_none")] pub refunds_total: Option<Price>, #[serde(rename = "purchasesTotal", default, skip_serializing_if = "Option::is_none")] pub purchases_total: Option<Price>, #[serde(rename = "reservationsToPurchase", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_purchase: Vec<ReservationToPurchaseCalculateExchange>, #[serde(rename = "reservationsToExchange", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_exchange: Vec<ReservationToExchange>, #[serde(rename = "policyResult", default, skip_serializing_if = "Option::is_none")] pub policy_result: Option<ExchangePolicyErrors>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangeResponseProperties { #[serde(rename = "sessionId", default, skip_serializing_if = "Option::is_none")] pub session_id: Option<String>, #[serde(rename = "netPayable", default, skip_serializing_if = "Option::is_none")] pub net_payable: Option<Price>, #[serde(rename = "refundsTotal", default, skip_serializing_if = "Option::is_none")] pub refunds_total: Option<Price>, #[serde(rename = "purchasesTotal", default, skip_serializing_if = "Option::is_none")] pub purchases_total: Option<Price>, #[serde(rename = "reservationsToPurchase", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_purchase: Vec<ReservationToPurchaseExchange>, #[serde(rename = "reservationsToExchange", default, skip_serializing_if = "Vec::is_empty")] pub reservations_to_exchange: Vec<ReservationToReturnForExchange>, #[serde(rename = "policyResult", default, skip_serializing_if = "Option::is_none")] pub policy_result: Option<ExchangePolicyErrors>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangePolicyErrors { #[serde(rename = "policyErrors", default, skip_serializing_if = "Vec::is_empty")] pub policy_errors: Vec<ExchangePolicyError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExchangePolicyError { #[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 ReservationToExchange { #[serde(rename = "reservationId", default, skip_serializing_if = "Option::is_none")] pub reservation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quantity: Option<i32>, #[serde(rename = "billingRefundAmount", default, skip_serializing_if = "Option::is_none")] pub billing_refund_amount: Option<Price>, #[serde(rename = "billingInformation", default, skip_serializing_if = "Option::is_none")] pub billing_information: Option<BillingInformation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationToReturnForExchange { #[serde(rename = "reservationId", default, skip_serializing_if = "Option::is_none")] pub reservation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quantity: Option<i32>, #[serde(rename = "billingRefundAmount", default, skip_serializing_if = "Option::is_none")] pub billing_refund_amount: Option<Price>, #[serde(rename = "billingInformation", default, skip_serializing_if = "Option::is_none")] pub billing_information: Option<BillingInformation>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<OperationStatus>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BillingInformation { #[serde(rename = "billingCurrencyTotalPaidAmount", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total_paid_amount: Option<Price>, #[serde(rename = "billingCurrencyProratedAmount", default, skip_serializing_if = "Option::is_none")] pub billing_currency_prorated_amount: Option<Price>, #[serde( rename = "billingCurrencyRemainingCommitmentAmount", default, skip_serializing_if = "Option::is_none" )] pub billing_currency_remaining_commitment_amount: Option<Price>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationToPurchaseCalculateExchange { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PurchaseRequest>, #[serde(rename = "billingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total: Option<Price>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationToPurchaseExchange { #[serde(rename = "reservationOrderId", default, skip_serializing_if = "Option::is_none")] pub reservation_order_id: Option<String>, #[serde(rename = "reservationId", default, skip_serializing_if = "Option::is_none")] pub reservation_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PurchaseRequest>, #[serde(rename = "billingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total: Option<Price>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<OperationStatus>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Catalog { #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "billingPlans", default, skip_serializing_if = "Option::is_none")] pub billing_plans: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub terms: Vec<ReservationTerm>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<String>, #[serde(rename = "skuProperties", default, skip_serializing_if = "Vec::is_empty")] pub sku_properties: Vec<SkuProperty>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub restrictions: Vec<SkuRestriction>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SkuProperty { #[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 SkuRestriction { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<String>, #[serde(rename = "reasonCode", default, skip_serializing_if = "Option::is_none")] pub reason_code: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationOrderResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<i64>, #[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 properties: Option<ReservationOrderProperties>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReservationBillingPlan { Upfront, Monthly, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReservationTerm { #[serde(rename = "P1Y")] P1y, #[serde(rename = "P3Y")] P3y, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PaymentStatus { Succeeded, Failed, Scheduled, Cancelled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PaymentDetail { #[serde(rename = "dueDate", default, skip_serializing_if = "Option::is_none")] pub due_date: Option<String>, #[serde(rename = "paymentDate", default, skip_serializing_if = "Option::is_none")] pub payment_date: Option<String>, #[serde(rename = "pricingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub pricing_currency_total: Option<Price>, #[serde(rename = "billingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total: Option<Price>, #[serde(rename = "billingAccount", default, skip_serializing_if = "Option::is_none")] pub billing_account: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<PaymentStatus>, #[serde(rename = "extendedStatusInfo", default, skip_serializing_if = "Option::is_none")] pub extended_status_info: Option<ExtendedStatusInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationOrderBillingPlanInformation { #[serde(rename = "pricingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub pricing_currency_total: Option<Price>, #[serde(rename = "startDate", default, skip_serializing_if = "Option::is_none")] pub start_date: Option<String>, #[serde(rename = "nextPaymentDueDate", default, skip_serializing_if = "Option::is_none")] pub next_payment_due_date: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub transactions: Vec<PaymentDetail>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationOrderProperties { #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "requestDateTime", default, skip_serializing_if = "Option::is_none")] pub request_date_time: Option<String>, #[serde(rename = "createdDateTime", default, skip_serializing_if = "Option::is_none")] pub created_date_time: Option<String>, #[serde(rename = "expiryDate", default, skip_serializing_if = "Option::is_none")] pub expiry_date: Option<String>, #[serde(rename = "originalQuantity", default, skip_serializing_if = "Option::is_none")] pub original_quantity: Option<ReservationQuantity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub term: Option<ReservationTerm>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "billingPlan", default, skip_serializing_if = "Option::is_none")] pub billing_plan: Option<ReservationBillingPlan>, #[serde(rename = "planInformation", default, skip_serializing_if = "Option::is_none")] pub plan_information: Option<ReservationOrderBillingPlanInformation>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub reservations: Vec<ReservationResponse>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<i64>, #[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 sku: Option<SkuName>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ReservationProperties>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RenewPropertiesResponse { #[serde(rename = "purchaseProperties", default, skip_serializing_if = "Option::is_none")] pub purchase_properties: Option<PurchaseRequest>, #[serde(rename = "pricingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub pricing_currency_total: Option<renew_properties_response::PricingCurrencyTotal>, #[serde(rename = "billingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total: Option<renew_properties_response::BillingCurrencyTotal>, } pub mod renew_properties_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PricingCurrencyTotal { #[serde(rename = "currencyCode", default, skip_serializing_if = "Option::is_none")] pub currency_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub amount: Option<f64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BillingCurrencyTotal { #[serde(rename = "currencyCode", default, skip_serializing_if = "Option::is_none")] pub currency_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub amount: Option<f64>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CalculatePriceResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CalculatePriceResponseProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CalculatePriceResponseProperties { #[serde(rename = "billingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub billing_currency_total: Option<calculate_price_response_properties::BillingCurrencyTotal>, #[serde(rename = "isBillingPartnerManaged", default, skip_serializing_if = "Option::is_none")] pub is_billing_partner_managed: Option<bool>, #[serde(rename = "reservationOrderId", default, skip_serializing_if = "Option::is_none")] pub reservation_order_id: Option<String>, #[serde(rename = "skuTitle", default, skip_serializing_if = "Option::is_none")] pub sku_title: Option<String>, #[serde(rename = "skuDescription", default, skip_serializing_if = "Option::is_none")] pub sku_description: Option<String>, #[serde(rename = "pricingCurrencyTotal", default, skip_serializing_if = "Option::is_none")] pub pricing_currency_total: Option<calculate_price_response_properties::PricingCurrencyTotal>, #[serde(rename = "paymentSchedule", default, skip_serializing_if = "Vec::is_empty")] pub payment_schedule: Vec<PaymentDetail>, } pub mod calculate_price_response_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BillingCurrencyTotal { #[serde(rename = "currencyCode", default, skip_serializing_if = "Option::is_none")] pub currency_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub amount: Option<f64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PricingCurrencyTotal { #[serde(rename = "currencyCode", default, skip_serializing_if = "Option::is_none")] pub currency_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub amount: Option<f64>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationProperties { #[serde(rename = "reservedResourceType", default, skip_serializing_if = "Option::is_none")] pub reserved_resource_type: Option<ReservedResourceType>, #[serde(rename = "instanceFlexibility", default, skip_serializing_if = "Option::is_none")] pub instance_flexibility: Option<InstanceFlexibility>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "appliedScopes", default, skip_serializing_if = "Option::is_none")] pub applied_scopes: Option<AppliedScopes>, #[serde(rename = "appliedScopeType", default, skip_serializing_if = "Option::is_none")] pub applied_scope_type: Option<AppliedScopeType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quantity: Option<ReservationQuantity>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(rename = "effectiveDateTime", default, skip_serializing_if = "Option::is_none")] pub effective_date_time: Option<String>, #[serde(rename = "lastUpdatedDateTime", default, skip_serializing_if = "Option::is_none")] pub last_updated_date_time: Option<String>, #[serde(rename = "expiryDate", default, skip_serializing_if = "Option::is_none")] pub expiry_date: Option<String>, #[serde(rename = "skuDescription", default, skip_serializing_if = "Option::is_none")] pub sku_description: Option<String>, #[serde(rename = "extendedStatusInfo", default, skip_serializing_if = "Option::is_none")] pub extended_status_info: Option<ExtendedStatusInfo>, #[serde(rename = "billingPlan", default, skip_serializing_if = "Option::is_none")] pub billing_plan: Option<ReservationBillingPlan>, #[serde(rename = "splitProperties", default, skip_serializing_if = "Option::is_none")] pub split_properties: Option<ReservationSplitProperties>, #[serde(rename = "mergeProperties", default, skip_serializing_if = "Option::is_none")] pub merge_properties: Option<ReservationMergeProperties>, #[serde(rename = "billingScopeId", default, skip_serializing_if = "Option::is_none")] pub billing_scope_id: Option<BillingScopeId>, #[serde(default, skip_serializing_if = "Option::is_none")] pub renew: Option<Renew>, #[serde(rename = "renewSource", default, skip_serializing_if = "Option::is_none")] pub renew_source: Option<String>, #[serde(rename = "renewDestination", default, skip_serializing_if = "Option::is_none")] pub renew_destination: Option<String>, #[serde(rename = "renewProperties", default, skip_serializing_if = "Option::is_none")] pub renew_properties: Option<RenewPropertiesResponse>, #[serde(default, skip_serializing_if = "Option::is_none")] pub term: Option<ReservationTerm>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationSplitProperties { #[serde(rename = "splitDestinations", default, skip_serializing_if = "Vec::is_empty")] pub split_destinations: Vec<String>, #[serde(rename = "splitSource", default, skip_serializing_if = "Option::is_none")] pub split_source: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationMergeProperties { #[serde(rename = "mergeDestination", default, skip_serializing_if = "Option::is_none")] pub merge_destination: Option<String>, #[serde(rename = "mergeSources", default, skip_serializing_if = "Vec::is_empty")] pub merge_sources: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PurchaseRequestProperties { #[serde(rename = "reservedResourceType", default, skip_serializing_if = "Option::is_none")] pub reserved_resource_type: Option<ReservedResourceType>, #[serde(rename = "billingScopeId", default, skip_serializing_if = "Option::is_none")] pub billing_scope_id: Option<BillingScopeId>, #[serde(default, skip_serializing_if = "Option::is_none")] pub term: Option<ReservationTerm>, #[serde(rename = "billingPlan", default, skip_serializing_if = "Option::is_none")] pub billing_plan: Option<ReservationBillingPlan>, #[serde(default, skip_serializing_if = "Option::is_none")] pub quantity: Option<ReservationQuantity>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "appliedScopeType", default, skip_serializing_if = "Option::is_none")] pub applied_scope_type: Option<AppliedScopeType>, #[serde(rename = "appliedScopes", default, skip_serializing_if = "Option::is_none")] pub applied_scopes: Option<AppliedScopes>, #[serde(default, skip_serializing_if = "Option::is_none")] pub renew: Option<Renew>, #[serde(rename = "reservedResourceProperties", default, skip_serializing_if = "Option::is_none")] pub reserved_resource_properties: Option<purchase_request_properties::ReservedResourceProperties>, } pub mod purchase_request_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservedResourceProperties { #[serde(rename = "instanceFlexibility", default, skip_serializing_if = "Option::is_none")] pub instance_flexibility: Option<InstanceFlexibility>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PatchProperties { #[serde(rename = "appliedScopeType", default, skip_serializing_if = "Option::is_none")] pub applied_scope_type: Option<AppliedScopeType>, #[serde(rename = "appliedScopes", default, skip_serializing_if = "Option::is_none")] pub applied_scopes: Option<AppliedScopes>, #[serde(rename = "instanceFlexibility", default, skip_serializing_if = "Option::is_none")] pub instance_flexibility: Option<InstanceFlexibility>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub renew: Option<Renew>, #[serde(rename = "renewProperties", default, skip_serializing_if = "Option::is_none")] pub renew_properties: Option<patch_properties::RenewProperties>, } pub mod patch_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RenewProperties { #[serde(rename = "purchaseProperties", default, skip_serializing_if = "Option::is_none")] pub purchase_properties: Option<PurchaseRequest>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SplitProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub quantities: Vec<i64>, #[serde(rename = "reservationId", default, skip_serializing_if = "Option::is_none")] pub reservation_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MergeProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sources: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MergeRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<MergeProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PurchaseRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<SkuName>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PurchaseRequestProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Patch { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PatchProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SplitRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SplitProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Error { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ExtendedErrorInfo>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExtendedErrorInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<ErrorResponseCode>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExtendedStatusInfo { #[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")] pub status_code: Option<ReservationStatusCode>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationOrderList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ReservationOrderResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReservationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ReservationResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppliedReservations { #[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 properties: Option<AppliedReservationsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppliedReservationsProperties { #[serde(rename = "reservationOrderIds", default, skip_serializing_if = "Option::is_none")] pub reservation_order_ids: Option<AppliedReservationList>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AppliedReservationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] 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 OperationList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplay>, #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplay { #[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 enum InstanceFlexibility { On, Off, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AppliedScopeType { Single, Shared, } pub type AppliedScopes = Vec<String>; pub type BillingScopeId = String; pub type Renew = bool; pub type ReservationQuantity = i32; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AvailableScopeProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<SubscriptionScopeProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubscriptionScopeProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub scopes: Vec<ScopeProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub valid: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ReservedResourceType { VirtualMachines, SqlDatabases, SuseLinux, CosmosDb, RedHat, SqlDataWarehouse, VMwareCloudSimple, RedHatOsa, Databricks, AppService, ManagedDisk, BlockBlob, RedisCache, AzureDataExplorer, MySql, MariaDb, PostgreSql, DedicatedHost, SapHana, SqlAzureHybridBenefit, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Price { #[serde(rename = "currencyCode", default, skip_serializing_if = "Option::is_none")] pub currency_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub amount: Option<f64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum OperationStatus { Succeeded, Failed, Cancelled, Pending, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CurrentQuotaLimit { #[serde(rename = "quotaInformation", default, skip_serializing_if = "Option::is_none")] pub quota_information: Option<CurrentQuotaLimitBase>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<QuotaRequestStatusDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CurrentQuotaLimitBase { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<QuotaProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<ResourceName>, #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<ResourceTypesName>, #[serde(rename = "quotaPeriod", default, skip_serializing_if = "Option::is_none")] pub quota_period: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ResourceName { #[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 QuotaLimits { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CurrentQuotaLimitBase>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaLimitsResponse { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CurrentQuotaLimit>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CreateGenericQuotaRequestParameters { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CurrentQuotaLimitBase>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubRequest { #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<ResourceName>, #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<QuotaRequestState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "subRequestId", default, skip_serializing_if = "Option::is_none")] pub sub_request_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestOneResourceSubmitResponse { #[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 properties: Option<QuotaRequestOneResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestSubmitResponse { #[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 properties: Option<QuotaRequestProperties>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestSubmitResponse201 { #[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 properties: Option<QuotaRequestStatusDetails>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestStatusDetails { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<QuotaRequestState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestDetails { #[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 properties: Option<QuotaRequestProperties>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestDetailsList { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<QuotaRequestDetails>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<QuotaRequestState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "requestSubmitTime", default, skip_serializing_if = "Option::is_none")] pub request_submit_time: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<SubRequest>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuotaRequestOneResourceProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<QuotaRequestState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(rename = "requestSubmitTime", default, skip_serializing_if = "Option::is_none")] pub request_submit_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CurrentQuotaLimitBase>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum QuotaRequestState { Accepted, Invalid, Succeeded, Failed, InProgress, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ResourceTypesName { #[serde(rename = "standard")] Standard, #[serde(rename = "dedicated")] Dedicated, #[serde(rename = "lowPriority")] LowPriority, #[serde(rename = "shared")] Shared, #[serde(rename = "serviceSpecific")] ServiceSpecific, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExceptionResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ServiceError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceError { #[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 = "Vec::is_empty")] pub details: Vec<ServiceErrorDetail>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ServiceErrorDetail { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, }
#[doc = "Reader of register RX_FIFO_RD_SILENT"] pub type R = crate::R<u32, super::RX_FIFO_RD_SILENT>; #[doc = "Reader of field `DATA`"] pub type DATA_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:15 - Data read from the receiver FIFO. Reading a data frame will NOT remove the data frame from the FIFO; i.e. behavior is similar to that of a PEEK operation. Note that when CTRL.BYTE_MODE is '1', only DATA\\[7:0\\] are used. A read from an empty RX FIFO sets INTR_RX.UNDERFLOW to '1'."] #[inline(always)] pub fn data(&self) -> DATA_R { DATA_R::new((self.bits & 0xffff) as u16) } }
use serde::{Deserialize, Serialize}; use crate::response::common::Shards; use std::fmt; #[derive(Debug, Serialize, Deserialize)] pub struct BulkResponse { pub took: i32, pub errors: bool, pub items: Vec<Item>, } impl BulkResponse { pub fn succeed_items(&self) -> impl Iterator<Item = &Item> { self.items.iter().filter(|x| x.success()) } pub fn first_error(&self) -> Option<ItemError> { self.items .iter() .find(|x| !x.success()) .and_then(|x| x.error()) } } #[derive(Debug, Serialize, Deserialize)] pub enum Item { #[serde(rename = "create")] Create(ItemBody), #[serde(rename = "delete")] Delete(ItemBody), #[serde(rename = "index")] Index(ItemBody), #[serde(rename = "update")] Update(ItemBody), } impl Item { pub fn success(&self) -> bool { match *self { Item::Create(ref body) | Item::Delete(ref body) | Item::Index(ref body) | Item::Update(ref body) => body.status >= 200 && body.status < 400, } } pub fn error(&self) -> Option<ItemError> { match *self { Item::Create(ref body) | Item::Delete(ref body) | Item::Index(ref body) | Item::Update(ref body) => body.error.clone(), } } pub fn get_id(&self) -> String { match *self { Item::Create(ref body) | Item::Delete(ref body) | Item::Index(ref body) | Item::Update(ref body) => body.id.clone(), } } } #[derive(Debug, Serialize, Deserialize)] pub struct ItemBody { #[serde(rename = "_index")] pub index: String, #[serde(rename = "_type")] pub ty: String, #[serde(rename = "_id")] pub id: String, #[serde(rename = "_version")] pub version: Option<i32>, #[serde(rename = "_shards")] pub shards: Option<Shards>, #[serde(rename = "_seq_no")] pub seq_no: Option<i64>, #[serde(rename = "_primary_term")] pub primary_term: Option<i64>, pub result: Option<String>, pub status: i32, pub error: Option<ItemError>, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ItemError { #[serde(rename = "type")] ty: String, reason: String, index_uuid: String, shard: Option<String>, index: String, } impl std::error::Error for ItemError {} impl fmt::Display for ItemError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "reason: {}", self.reason) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_deserialize_bulk_response_all_success() { let resp_str = r#"{ "took": 30, "errors": false, "items": [ { "index": { "_index": "test", "_type": "_doc", "_id": "1", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "status": 201, "_seq_no" : 0, "_primary_term": 1 } }, { "delete": { "_index": "test", "_type": "_doc", "_id": "2", "_version": 1, "result": "not_found", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "status": 404, "_seq_no" : 1, "_primary_term" : 2 } }, { "create": { "_index": "test", "_type": "_doc", "_id": "3", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "status": 201, "_seq_no" : 2, "_primary_term" : 3 } }, { "update": { "_index": "test", "_type": "_doc", "_id": "1", "_version": 2, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "status": 200, "_seq_no" : 3, "_primary_term" : 4 } } ] }"#; assert!(serde_json::from_str::<BulkResponse>(resp_str).is_ok()); } #[test] fn test_deserialize_bulk_response_with_error() { let resp_str_1 = r#"{ "took": 486, "errors": true, "items": [ { "update": { "_index": "index1", "_type" : "_doc", "_id": "5", "status": 404, "error": { "type": "document_missing_exception", "reason": "[_doc][5]: document missing", "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA", "shard": "0", "index": "index1" } } }, { "update": { "_index": "index1", "_type" : "_doc", "_id": "6", "status": 404, "error": { "type": "document_missing_exception", "reason": "[_doc][6]: document missing", "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA", "shard": "0", "index": "index1" } } }, { "create": { "_index": "index1", "_type" : "_doc", "_id": "7", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1, "status": 201 } } ] }"#; assert!(serde_json::from_str::<BulkResponse>(resp_str_1).is_ok()); let resp_str_2 = r#"{ "took": 486, "errors": true, "items": [ { "update": { "_index": "index1", "_type" : "_doc", "_id": "5", "status": 404, "error": { "type": "document_missing_exception", "reason": "[_doc][5]: document missing", "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA", "shard": "0", "index": "index1" } } }, { "update": { "_index": "index1", "_type" : "_doc", "_id": "6", "status": 404, "error": { "type": "document_missing_exception", "reason": "[_doc][6]: document missing", "index_uuid": "aAsFqTI0Tc2W0LCWgPNrOA", "shard": "0", "index": "index1" } } }, { "create": { "_index": "index1", "_type" : "_doc", "_id": "7", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 0, "_primary_term": 1, "status": 201 } } ] }"#; assert!(serde_json::from_str::<BulkResponse>(resp_str_2).is_ok()); } }
#[doc = "Register `ISR` reader"] pub type R = crate::R<ISR_SPEC>; #[doc = "Field `CMPM` reader - Compare match"] pub type CMPM_R = crate::BitReader; #[doc = "Field `ARRM` reader - Autoreload match"] pub type ARRM_R = crate::BitReader; #[doc = "Field `EXTTRIG` reader - External trigger edge event"] pub type EXTTRIG_R = crate::BitReader; #[doc = "Field `CMPOK` reader - Compare register update OK"] pub type CMPOK_R = crate::BitReader; #[doc = "Field `ARROK` reader - Autoreload register update OK"] pub type ARROK_R = crate::BitReader; #[doc = "Field `UP` reader - Counter direction change down to up"] pub type UP_R = crate::BitReader; #[doc = "Field `DOWN` reader - Counter direction change up to down"] pub type DOWN_R = crate::BitReader; impl R { #[doc = "Bit 0 - Compare match"] #[inline(always)] pub fn cmpm(&self) -> CMPM_R { CMPM_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Autoreload match"] #[inline(always)] pub fn arrm(&self) -> ARRM_R { ARRM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - External trigger edge event"] #[inline(always)] pub fn exttrig(&self) -> EXTTRIG_R { EXTTRIG_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Compare register update OK"] #[inline(always)] pub fn cmpok(&self) -> CMPOK_R { CMPOK_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Autoreload register update OK"] #[inline(always)] pub fn arrok(&self) -> ARROK_R { ARROK_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Counter direction change down to up"] #[inline(always)] pub fn up(&self) -> UP_R { UP_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Counter direction change up to down"] #[inline(always)] pub fn down(&self) -> DOWN_R { DOWN_R::new(((self.bits >> 6) & 1) != 0) } } #[doc = "Interrupt and Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ISR_SPEC; impl crate::RegisterSpec for ISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`isr::R`](R) reader structure"] impl crate::Readable for ISR_SPEC {} #[doc = "`reset()` method sets ISR to value 0"] impl crate::Resettable for ISR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod p1; pub mod p2; pub mod p3; pub mod p4; pub mod p5; pub mod p6; pub mod p7; pub mod p8; pub mod p9;
#[doc = "Register `TIMEOUTR` reader"] pub type R = crate::R<TIMEOUTR_SPEC>; #[doc = "Register `TIMEOUTR` writer"] pub type W = crate::W<TIMEOUTR_SPEC>; #[doc = "Field `TIMEOUTA` reader - TIMEOUTA"] pub type TIMEOUTA_R = crate::FieldReader<u16>; #[doc = "Field `TIMEOUTA` writer - TIMEOUTA"] pub type TIMEOUTA_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 12, O, u16>; #[doc = "Field `TIDLE` reader - TIDLE"] pub type TIDLE_R = crate::BitReader<TIDLE_A>; #[doc = "TIDLE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIDLE_A { #[doc = "0: TIMEOUTA is used to detect SCL low timeout"] Disabled = 0, #[doc = "1: TIMEOUTA is used to detect both SCL and SDA high timeout (bus idle condition)"] Enabled = 1, } impl From<TIDLE_A> for bool { #[inline(always)] fn from(variant: TIDLE_A) -> Self { variant as u8 != 0 } } impl TIDLE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIDLE_A { match self.bits { false => TIDLE_A::Disabled, true => TIDLE_A::Enabled, } } #[doc = "TIMEOUTA is used to detect SCL low timeout"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TIDLE_A::Disabled } #[doc = "TIMEOUTA is used to detect both SCL and SDA high timeout (bus idle condition)"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TIDLE_A::Enabled } } #[doc = "Field `TIDLE` writer - TIDLE"] pub type TIDLE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIDLE_A>; impl<'a, REG, const O: u8> TIDLE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "TIMEOUTA is used to detect SCL low timeout"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(TIDLE_A::Disabled) } #[doc = "TIMEOUTA is used to detect both SCL and SDA high timeout (bus idle condition)"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(TIDLE_A::Enabled) } } #[doc = "Field `TIMOUTEN` reader - TIMOUTEN"] pub type TIMOUTEN_R = crate::BitReader<TIMOUTEN_A>; #[doc = "TIMOUTEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIMOUTEN_A { #[doc = "0: SCL timeout detection is disabled"] Disabled = 0, #[doc = "1: SCL timeout detection is enabled"] Enabled = 1, } impl From<TIMOUTEN_A> for bool { #[inline(always)] fn from(variant: TIMOUTEN_A) -> Self { variant as u8 != 0 } } impl TIMOUTEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIMOUTEN_A { match self.bits { false => TIMOUTEN_A::Disabled, true => TIMOUTEN_A::Enabled, } } #[doc = "SCL timeout detection is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TIMOUTEN_A::Disabled } #[doc = "SCL timeout detection is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TIMOUTEN_A::Enabled } } #[doc = "Field `TIMOUTEN` writer - TIMOUTEN"] pub type TIMOUTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIMOUTEN_A>; impl<'a, REG, const O: u8> TIMOUTEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "SCL timeout detection is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(TIMOUTEN_A::Disabled) } #[doc = "SCL timeout detection is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(TIMOUTEN_A::Enabled) } } #[doc = "Field `TIMEOUTB` reader - TIMEOUTB"] pub type TIMEOUTB_R = crate::FieldReader<u16>; #[doc = "Field `TIMEOUTB` writer - TIMEOUTB"] pub type TIMEOUTB_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 12, O, u16>; #[doc = "Field `TEXTEN` reader - TEXTEN"] pub type TEXTEN_R = crate::BitReader<TEXTEN_A>; #[doc = "TEXTEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TEXTEN_A { #[doc = "0: Extended clock timeout detection is disabled"] Disabled = 0, #[doc = "1: Extended clock timeout detection is enabled"] Enabled = 1, } impl From<TEXTEN_A> for bool { #[inline(always)] fn from(variant: TEXTEN_A) -> Self { variant as u8 != 0 } } impl TEXTEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TEXTEN_A { match self.bits { false => TEXTEN_A::Disabled, true => TEXTEN_A::Enabled, } } #[doc = "Extended clock timeout detection is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == TEXTEN_A::Disabled } #[doc = "Extended clock timeout detection is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == TEXTEN_A::Enabled } } #[doc = "Field `TEXTEN` writer - TEXTEN"] pub type TEXTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TEXTEN_A>; impl<'a, REG, const O: u8> TEXTEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Extended clock timeout detection is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(TEXTEN_A::Disabled) } #[doc = "Extended clock timeout detection is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(TEXTEN_A::Enabled) } } impl R { #[doc = "Bits 0:11 - TIMEOUTA"] #[inline(always)] pub fn timeouta(&self) -> TIMEOUTA_R { TIMEOUTA_R::new((self.bits & 0x0fff) as u16) } #[doc = "Bit 12 - TIDLE"] #[inline(always)] pub fn tidle(&self) -> TIDLE_R { TIDLE_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 15 - TIMOUTEN"] #[inline(always)] pub fn timouten(&self) -> TIMOUTEN_R { TIMOUTEN_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bits 16:27 - TIMEOUTB"] #[inline(always)] pub fn timeoutb(&self) -> TIMEOUTB_R { TIMEOUTB_R::new(((self.bits >> 16) & 0x0fff) as u16) } #[doc = "Bit 31 - TEXTEN"] #[inline(always)] pub fn texten(&self) -> TEXTEN_R { TEXTEN_R::new(((self.bits >> 31) & 1) != 0) } } impl W { #[doc = "Bits 0:11 - TIMEOUTA"] #[inline(always)] #[must_use] pub fn timeouta(&mut self) -> TIMEOUTA_W<TIMEOUTR_SPEC, 0> { TIMEOUTA_W::new(self) } #[doc = "Bit 12 - TIDLE"] #[inline(always)] #[must_use] pub fn tidle(&mut self) -> TIDLE_W<TIMEOUTR_SPEC, 12> { TIDLE_W::new(self) } #[doc = "Bit 15 - TIMOUTEN"] #[inline(always)] #[must_use] pub fn timouten(&mut self) -> TIMOUTEN_W<TIMEOUTR_SPEC, 15> { TIMOUTEN_W::new(self) } #[doc = "Bits 16:27 - TIMEOUTB"] #[inline(always)] #[must_use] pub fn timeoutb(&mut self) -> TIMEOUTB_W<TIMEOUTR_SPEC, 16> { TIMEOUTB_W::new(self) } #[doc = "Bit 31 - TEXTEN"] #[inline(always)] #[must_use] pub fn texten(&mut self) -> TEXTEN_W<TIMEOUTR_SPEC, 31> { TEXTEN_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 = "Timeout register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timeoutr::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 [`timeoutr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct TIMEOUTR_SPEC; impl crate::RegisterSpec for TIMEOUTR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`timeoutr::R`](R) reader structure"] impl crate::Readable for TIMEOUTR_SPEC {} #[doc = "`write(|w| ..)` method takes [`timeoutr::W`](W) writer structure"] impl crate::Writable for TIMEOUTR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets TIMEOUTR to value 0"] impl crate::Resettable for TIMEOUTR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! `Lexicon` is the basic trait that powers the library, describing a set of words that can be //! filtered in various ways. /// Describes a set of strings that is queryable for specific criteria. Depending on the exact /// implementation, different operations will be faster or slower. pub trait Lexicon { /// Returns `true` if the lexicon contains the given value and `false` otherwise. fn contains(&self, word: &str) -> bool; /// Keeps only the words in the `Lexicon` that have the given letter. fn with_letter(&mut self, letter: char); /// Removes any words from the `Lexicon` that have the given letter. fn without_letter(&mut self, letter: char); /// Keeps only the words in the `Lexicon` that are formed solely from the letters passed in. /// Different from `with_letters` in that, here, words need not have all of the letters from the /// input list: they just can't have any letters from outside of the list. fn only_using_letters<T: IntoIterator<Item = char>>(&mut self, letters: T); /// Keeps only the words in the `Lexicon` that have all of the given letters. /// Implemented via chained `with_letter()` calls by default. Different from `only_using_letters` /// in that, in this method, the returned words must contain all of the letters given. fn with_letters<T: IntoIterator<Item = char>>(&mut self, letters: T) { for letter in letters { self.with_letter(letter); } } /// Removes all words in the `Lexicon` that have any of the given letters. /// Implemented via chained `without_letter()` calls by default. fn without_letters<T: IntoIterator<Item = char>>(&mut self, letters: T) { for letter in letters { self.without_letter(letter); } } /// Keeps only the words in the `Lexicon` that have exactly the given /// length. Note that the exact interpretation of this can vary for some /// Unicode strings. fn with_exact_length(&mut self, length: usize); /// Keeps only the words in the `Lexicon` that are longer than the given /// length. Note that the exact interpretation of this can vary for some /// Unicode strings. fn with_more_length(&mut self, length: usize); /// Keeps only the words in the `Lexicon` that have less than the given /// length. Note that the exact interpretation of this can vary for some /// Unicode strings. fn with_less_length(&mut self, length: usize); }
fn sorted_adapters(path: &str) -> Vec<u32> { let mut input: Vec<u32> = std::fs::read_to_string(path) .unwrap() .lines() .map(|x| x.parse::<u32>().unwrap()) .collect(); input.sort(); input } fn build_distribution(input: &Vec<u32>) -> (usize, usize) { let mut ones = 0; let mut threes = 0; input.iter().zip([0].iter().chain(input.iter())) .for_each(|(larger, smaller)| { match larger - smaller { 1 => ones += 1, 3 => threes +=1, _ => () } }); (ones, threes + 1) } // Could be made more efficient with a cache fn ways(run: u64) -> u64 { match run { 0 | 1 | 2 => 1, 3 => 2, r => ways(r - 3) + ways(r - 2) + ways(r - 1) } } fn possibilities_for(adapters: &Vec<u32>) -> u64 { // Build a diff list let mut diffs: Vec<u32> = adapters.iter().zip([0].iter().chain(adapters.iter())) .map(|(larger, smaller)| larger - smaller) .collect(); diffs.push(3); // Find all of the runs in it let (runs, _) = diffs.iter().fold((Vec::new(), 1 as u64), |(mut runs, current_run), diff| { match diff { 1 => (runs, current_run + 1), 3 => { runs.push(current_run); (runs, 1) }, _ => panic!() } }); // Each run has some number of different combos; multiply them all runs.iter().map(|r| ways(*r)).product() } fn main() { let adapters = sorted_adapters("input.txt"); // Part one let (ones, threes) = build_distribution(&adapters); println!("Part 1: {}", ones * threes); // Part two println!("Part 2: {}", possibilities_for(&adapters)); } #[test] fn test_part_one() { let adapters = sorted_adapters("example2.txt"); let (ones, threes) = build_distribution(&adapters); assert_eq!(ones, 7); assert_eq!(threes, 5); let adapters = sorted_adapters("example.txt"); let (ones, threes) = build_distribution(&adapters); assert_eq!(ones, 22); assert_eq!(threes, 10); } #[test] fn test_part_two() { let adapters = sorted_adapters("example2.txt"); let possibilities = possibilities_for(&adapters); assert_eq!(possibilities, 8); let adapters = sorted_adapters("example.txt"); let possibilities = possibilities_for(&adapters); assert_eq!(possibilities, 19208); }
extern crate rand; extern crate num; use std::cmp::{ min, max }; use self::rand::{ thread_rng, Rng }; pub struct Map { bits: Vec<u8>, map: Vec<i32>, width: i32, height: i32 } impl Map { pub fn new(width: i32, height: i32) -> Map { let mut map = Vec::new(); let mut bits = Vec::new(); map.resize((width * height) as usize, 11i32); bits.resize((width * height) as usize, 0u8); Map { map, bits, width, height } } fn lim_x(&self, x: i32) -> i32 { min(self.width-1, max(x, 0)) } fn lim_y(&self, y: i32) -> i32 { min(self.height-1, max(y, 0)) } pub fn solve(&mut self) { for y in 0..self.height { for x in 0..self.width { if self.get_bit(x, y) == 0 { continue; } self.solve_one(x, y); } } } pub fn valid(&self, x: i32, y: i32) -> bool { x >= 0 && x < self.width && y >= 0 && y < self.height } fn get_neighbors(&self, x: i32, y: i32) -> Vec<(i32, i32, u8)> { let mut vec = Vec::new(); if self.valid(x-1, y) { vec.push((x-1, y, self.get_bit(x-1, y))); } if self.valid(x, y-1) { vec.push((x, y-1, self.get_bit(x, y-1))); } if self.valid(x+1, y) { vec.push((x+1, y, self.get_bit(x+1, y))); } if self.valid(x, y+1) { vec.push((x, y+1, self.get_bit(x, y+1))); } vec } pub fn get_tile(&self, x: i32, y: i32) -> i32 { let s = [ self.get_bit(x, y-1), self.get_bit(x+1, y), self.get_bit(x, y+1), self.get_bit(x-1, y) ]; let bf = s[3] * 8 + s[2] * 4 + s[1] * 2 + s[0]; match bf { 0 => { 0 }, 1 => { 13 }, 2 => { 14 }, 3 => { 3 }, 4 => { 15 }, 5 => { 0 }, 6 => { 4 }, 7 => { 8 }, 8 => { 12 }, 9 => { 2 }, 10 => { 1 }, 11 => { 7 }, 12 => { 5 }, 13 => { 6 }, 14 => { 9 }, 15 => { 10 }, _ => { 11 } } } pub fn solve_one(&mut self, x: i32, y: i32) -> i32 { let solved = self.get_tile(x, y); self.set(x, y, solved); solved } pub fn get_bit(&self, x: i32, y: i32) -> u8 { self.bits[(self.lim_x(x) + self.lim_y(y) * self.width) as usize] } pub fn set_bit(&mut self, x: i32, y: i32, val: u8) { let lx = self.lim_x(x); let ly = self.lim_x(y); self.bits[(lx + ly * self.width) as usize] = val; } pub fn get(&self, x: i32, y: i32) -> i32 { self.map[(self.lim_x(x) + self.lim_y(y) * self.width) as usize] } pub fn set(&mut self, x: i32, y: i32, val: i32) { let lx = self.lim_x(x); let ly = self.lim_x(y); self.map[(lx + ly * self.width) as usize] = val; } pub fn get_random_road_point(&self) -> (i32, i32) { let mut rng = thread_rng(); let mut x: i32 = rng.gen_range(0, self.width-1); let mut y: i32 = rng.gen_range(0, self.height-1); let mut bit = self.get_bit(x, y); while bit == 0 { x = rng.gen_range(0, self.width-1); y = rng.gen_range(0, self.height-1); bit = self.get_bit(x, y); // println!("CHECKED: X={}, Y={} => {}", x, y, bit); } (x, y) } pub fn find_path(&self, sx: i32, sy: i32, ex: i32, ey: i32) -> Vec<(i32, i32)> { let mut seen: Vec<bool> = Vec::new(); seen.resize((self.width * self.height) as usize, false); let mut c = 0usize; let mut path = Vec::new(); path.push((sx, sy)); loop { if c >= seen.len() { return path; } let (cx, cy) = path[path.len().wrapping_sub(1)]; seen[(cx + cy * self.width) as usize] = true; c += 1; let neighs = self.get_neighbors(cx, cy); let mut i = 0; for &(x, y, val) in neighs.iter() { if x == ex && y == ey { path.push((x, y)); return path; } if !seen[(x + y * self.width) as usize] && val == 1 { path.push((x, y)); break; } else { i += 1; } } if i == neighs.len() { path.pop(); } } } pub fn width(&self) -> i32 { self.width } pub fn height(&self) -> i32 { self.height } }
#[doc = "Register `IDCODE` reader"] pub type R = crate::R<IDCODE_SPEC>; #[doc = "Field `DEV_ID` reader - Device Identifier"] pub type DEV_ID_R = crate::FieldReader<u16>; #[doc = "Field `DIV_ID` reader - Division Identifier"] pub type DIV_ID_R = crate::FieldReader; #[doc = "Field `REV_ID` reader - Revision Identifier"] pub type REV_ID_R = crate::FieldReader<u16>; impl R { #[doc = "Bits 0:11 - Device Identifier"] #[inline(always)] pub fn dev_id(&self) -> DEV_ID_R { DEV_ID_R::new((self.bits & 0x0fff) as u16) } #[doc = "Bits 12:15 - Division Identifier"] #[inline(always)] pub fn div_id(&self) -> DIV_ID_R { DIV_ID_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:31 - Revision Identifier"] #[inline(always)] pub fn rev_id(&self) -> REV_ID_R { REV_ID_R::new(((self.bits >> 16) & 0xffff) as u16) } } #[doc = "MCU Device ID Code Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`idcode::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IDCODE_SPEC; impl crate::RegisterSpec for IDCODE_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`idcode::R`](R) reader structure"] impl crate::Readable for IDCODE_SPEC {} #[doc = "`reset()` method sets IDCODE to value 0"] impl crate::Resettable for IDCODE_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::a; // ^ namespace // ^ !keyword use crate::{b, c}; // ^ namespace // ^ !keyword use super::a; // ^ namespace // ^ !keyword use super::{b, c}; // ^ namespace // ^ !keyword
#![feature(type_ascription)] extern crate ammonia; #[macro_use] extern crate log; extern crate number_prefix; extern crate pretty_env_logger; extern crate reqwest; extern crate retry; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate serde_xml_rs; #[macro_use] extern crate maplit; mod teledex; pub use teledex::{DefinitionFetcher, DexBot, MockDefinitionFetcher};
use criterion::{criterion_group, criterion_main, Criterion}; use common_substrings::get_substrings; fn criterion_benchmark(c: &mut Criterion) { c.bench_function("get substring", |b| b.iter(|| get_substrings(vec![ "java", "offe", "coffescript", "typescript", "typed", "javacoffie", "fessss", "fe", ], 2, 3))); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
// Copyright (c) 2018, ilammy // // Licensed under the Apache License, Version 2.0 (see LICENSE in the // root directory). This file may be copied, distributed, and modified // only in accordance with the terms specified by the license. use exonum::{ blockchain::{ExecutionError, Transaction}, storage::{Fork, MapIndex, Snapshot}, }; use schema::{Act, ActId, BodyOfLaw, Clause}; use service::SERVICE_ID; transactions! { pub LegalTransactions { const SERVICE_ID = SERVICE_ID; /// Create a new act effective immediately. struct TxCreateAct { id: ActId, name: &str, clauses: Vec<Clause>, } /// Update clauses of an existing act. struct TxModifyAct { id: ActId, current_revision: u32, clauses: Vec<Clause>, } /// Repeal an existing act, effective immediately. struct TxRepealAct { id: ActId, current_revision: u32, } } } /// Possible errors in legal transactions. #[derive(Debug, Fail)] #[repr(u8)] pub enum Error { #[fail(display = "Act already exists")] ActExists = 0, #[fail(display = "New act content does not reference previous clauses")] InconsistentClauses = 1, #[fail(display = "Act does not exist")] ActMissing = 2, #[fail(display = "Act is already repealed")] ActRepealed = 3, #[fail(display = "Outdated act revision")] OutdatedRevision = 4, } // Conversion of concrete errors into Exonum's generic ones. impl From<Error> for ExecutionError { fn from(value: Error) -> ExecutionError { let description = format!("{}", value); ExecutionError::with_description(value as u8, description) } } // TODO: Currently transactions are acts of God, not parliament. They need to be verified. impl Transaction for TxCreateAct { fn verify(&self) -> bool { true } fn execute(&self, fork: &mut Fork) -> Result<(), ExecutionError> { let mut schema = BodyOfLaw::new(fork); if schema.act(&self.id()).is_some() { Err(Error::ActExists)? } // TODO: validate clause uniqueness let act = Act::new(self.id(), self.name(), false, self.clauses(), 0); schema.acts_mut().put(&self.id(), act); Ok(()) } } impl Transaction for TxModifyAct { fn verify(&self) -> bool { true } fn execute(&self, fork: &mut Fork) -> Result<(), ExecutionError> { let mut schema = BodyOfLaw::new(fork); let mut acts = schema.acts_mut(); if let Some(previous_act) = acts.get(&self.id()) { if previous_act.repealed() { Err(Error::ActRepealed)? } if self.current_revision() != previous_act.revision() { Err(Error::OutdatedRevision)? } if let Ok(new_act) = previous_act.update_clauses(self.clauses()) { acts.put(&self.id(), new_act); Ok(()) } else { Err(Error::InconsistentClauses)? } } else { Err(Error::ActMissing)? } } } impl Transaction for TxRepealAct { fn verify(&self) -> bool { true } fn execute(&self, fork: &mut Fork) -> Result<(), ExecutionError> { let mut schema = BodyOfLaw::new(fork); let mut acts = schema.acts_mut(); if let Some(previous_act) = acts.get(&self.id()) { if self.current_revision() != previous_act.revision() { Err(Error::OutdatedRevision)? } if let Ok(new_act) = previous_act.repeal() { acts.put(&self.id(), new_act); Ok(()) } else { Err(Error::ActRepealed)? } } else { Err(Error::ActMissing)? } } }
use crate::prelude::*; use rustc::mir::StatementKind::*; #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum SsaKind { NotSsa, Ssa, } pub fn analyze(fx: &FunctionCx<'_, '_, impl Backend>) -> HashMap<Local, SsaKind> { let mut flag_map = HashMap::new(); for (local, local_decl) in fx.mir.local_decls.iter_enumerated() { if fx.clif_type(local_decl.ty).is_some() { flag_map.insert(local, SsaKind::Ssa); } else { flag_map.insert(local, SsaKind::NotSsa); } } for bb in fx.mir.basic_blocks().iter() { for stmt in bb.statements.iter() { match &stmt.kind { Assign(place_and_rval) => match &place_and_rval.1 { Rvalue::Ref(_, _, place) => { analyze_non_ssa_place(&mut flag_map, place); } _ => {} }, _ => {} } } match &bb.terminator().kind { TerminatorKind::Call { destination: Some((place, _)), .. } => analyze_non_ssa_place(&mut flag_map, place), _ => {} } } flag_map } fn analyze_non_ssa_place(flag_map: &mut HashMap<Local, SsaKind>, place: &Place) { match place.base { PlaceBase::Local(local) => not_ssa(flag_map, local), _ => {} } } fn not_ssa<L: ::std::borrow::Borrow<Local>>(flag_map: &mut HashMap<Local, SsaKind>, local: L) { *flag_map.get_mut(local.borrow()).unwrap() = SsaKind::NotSsa; }