text
stringlengths
8
4.13M
use std::{fs::File, io::BufReader}; use dicom_core::value::Value; use dicom_encoding::text::SpecificCharacterSet; use dicom_object::{mem::InMemDicomObject, open_file}; use dicom_test_files; #[test] fn test_ob_value_with_unknown_length() { let path = dicom_test_files::path("pydicom/JPEG2000.dcm").expect("test DICOM file should exist"); let object = open_file(&path).unwrap(); let element = object.element_by_name("PixelData").unwrap(); match element.value() { Value::PixelSequence { fragments, offset_table, } => { // check offset table assert_eq!(offset_table.len(), 0); // check if the leading and trailing bytes look right assert_eq!(fragments.len(), 1); let fragment = &fragments[0]; assert_eq!(fragment[0..2], [255, 79]); assert_eq!(fragment[fragment.len() - 2..fragment.len()], [255, 217]); } value => { panic!("expected a pixel sequence, but got {:?}", value); } } } #[test] fn test_expl_vr_le_no_meta() { let path = dicom_test_files::path("pydicom/ExplVR_LitEndNoMeta.dcm") .expect("test DICOM file should exist"); let source = BufReader::new(File::open(path).unwrap()); let ts = dicom_transfer_syntax_registry::entries::EXPLICIT_VR_LITTLE_ENDIAN.erased(); let object = InMemDicomObject::read_dataset_with_ts_cs(source, &ts, SpecificCharacterSet::Default) .unwrap(); let sop_instance_uid = object.element_by_name("SOPInstanceUID").unwrap(); assert_eq!(sop_instance_uid.to_str().unwrap(), "1.2.333.4444.5.6.7.8",); let series_instance_uid = object.element_by_name("SeriesInstanceUID").unwrap(); assert_eq!( series_instance_uid.to_str().unwrap(), "1.2.333.4444.5.6.7.8.99\0", ); let frame_of_reference_uid = object.element_by_name("FrameOfReferenceUID").unwrap(); assert_eq!( frame_of_reference_uid.to_str().unwrap(), "1.2.333.4444.5.6.7.8.9", ); }
use std::{ fs::{File, remove_dir_all}, io::{Read}, path::{PathBuf, Path} }; use toml; use walkdir::WalkDir; use meta::Meta; use image::Image; use state::error::StateError; #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Project { pub id: u32, pub path: PathBuf, pub meta: Meta, pub images: Vec<Image>, pub description: String, pub bw_title_image: bool, } impl Project { pub fn path(&self) -> PathBuf { self.path.clone() } pub fn sort_images(&mut self) { self.images.sort_by(|lhs, rhs| lhs.position.cmp(&rhs.position)); for i in 0..self.images.len() { self.images[i].position = i as u32; } } } impl Project { pub fn update_from_source(&mut self) { for entry in WalkDir::new(&self.path).min_depth(1).max_depth(1) { if let Ok(entry) = entry { let name = entry.file_name(); println!("project file: {:?}", name); if name == "img" { self.update_images_from_source(&entry.path()); } else if name == "content.md" { self.description = super::content(&entry.path()); } else if name == "meta.toml" { self.meta = meta(&entry.path()); } } } } fn update_images_from_source(&mut self, path: &Path) { let mut tmp_images: Vec<Image> = vec!(); for entry in WalkDir::new(path).min_depth(1).max_depth(1) { if let Ok(entry) = entry { if !entry.file_type().is_file() { continue; } match self.images.iter().position(|i| i.path == entry.path().to_path_buf()) { Some(idx) => { let mut img = self.images[idx].clone(); img.path = entry.path().to_path_buf(); tmp_images.push(img); }, None => { let img = Image { position: self.images.len() as u32, path: entry.path().to_path_buf(), }; tmp_images.push(img); } } } } self.images = tmp_images; self.sort_images(); } pub fn delete_files(&self) -> Result<(), String> { match remove_dir_all(&self.path) { Ok(()) => Ok(()), Err(e) => Err(format!("Error deleting files: {:?}", e)), } } pub fn add_image(&mut self, path: &PathBuf) -> Result<(), StateError> { super::copy_file(&path, &self.path.join("img"))?; let img = Image { position: self.images.iter().map(|i| i.position).max().unwrap_or(0), path: path.clone(), }; println!("add_image{:?}", &super::super::serde_json::to_string(&img)); self.images.push(img); Ok(()) } } /// Parse the meta.toml file for this project fn meta(path: &Path) -> Meta { let ret = Meta::default(); let mut buf = String::new(); if let Ok(mut f) = File::open(path) { if let Ok(_size) = f.read_to_string(&mut buf) { if let Ok(m) = toml::from_str(&buf) { return m } } } ret }
pub mod lexer { use crate::{Token, TokenType}; use std::ops::{Deref, DerefMut}; use crate::*; #[derive(Debug)] pub struct Buffer(String); impl Buffer { pub fn new() -> Self { Self(String::new()) } pub fn is_string(&self) -> bool { self.0.starts_with('\'') || self.0.starts_with('"') } pub fn is_escaped(&self) -> bool { self.0.ends_with('\\') } pub fn is_string_beginning(&self, c: char) -> bool { self.is_string() && self.0.starts_with(c) } pub fn is_white(&self) -> bool { self.0.as_str() == " " || self.0.as_str() == "\t" || self.0.as_str() == "\n" || self.0.as_str() == "\r" } } impl Deref for Buffer { type Target = String; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for Buffer { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } pub struct Lexer { content: String, buffer: Buffer, line: usize, character: usize, start: usize, } impl Lexer { pub fn new(content: String) -> Self { Self { content, line: 0, character: 0, start: 0, buffer: Buffer::new(), } } pub fn tokenize(&mut self) -> Vec<TokenType> { let mut tokens = vec![]; let content = self.content.clone(); for c in content.chars() { match c { ' ' | '\n' if self.non_special() => { self.push_non_empty(&mut tokens); self.append_and_push(c, &mut tokens, |b| lexer_whitespace!(b)) } '[' | ']' | '{' | '}' if self.non_special() => { self.push_non_empty(&mut tokens); self.append_and_push(c, &mut tokens, |b| lexer_separator!(b)) } '=' if self.non_special() => { self.push_non_empty(&mut tokens); self.append_and_push(c, &mut tokens, |b| lexer_operator!(b)) } '"' | '\'' if self.is_string_beginning(c) => { self.append_and_push(c, &mut tokens, |b| lexer_string!(b)) } _ => { self.buffer.push(c); } } } if !self.is_empty() { tokens.push(lexer_identifier!(self)); self.clear(); } tokens } fn append_and_push<F>(&mut self, c: char, tokens: &mut Vec<TokenType>, builder: F) where F: Fn(&Lexer) -> TokenType, { self.buffer.push(c); tokens.push(builder(&self)); self.clear(); } fn push_non_empty(&mut self, tokens: &mut Vec<TokenType>) { if self.is_empty() { return; } tokens.push(self.match_token()); } fn non_special(&self) -> bool { !self.buffer.is_string() } fn match_token(&mut self) -> TokenType { let token = if self.buffer.is_string() { lexer_string!(self) } else if self.buffer.is_white() { lexer_whitespace!(self) } else { lexer_identifier!(self) }; self.clear(); token } fn clear(&mut self) { if self.buffer.contains('\n') { self.line += self.buffer.lines().count(); self.character += self.buffer.len() - self.buffer.rfind('\n').unwrap_or(self.buffer.len()); self.start += self.buffer.len(); } else { self.character += self.buffer.len(); self.start += self.buffer.len(); } self.buffer.clear(); } } impl Deref for Lexer { type Target = Buffer; fn deref(&self) -> &Self::Target { &self.buffer } } impl TokenBuilder for Lexer { fn text(&self) -> String { self.buffer.to_string() } fn line(&self) -> usize { self.line } fn character(&self) -> usize { self.character } fn start(&self) -> usize { self.start } fn end(&self, text: &String) -> usize { self.start + text.len() } } #[cfg(test)] mod tests { use super::*; struct BuilderMock { line: usize, character: usize, start: usize, text: String, } impl TokenBuilder for BuilderMock { fn text(&self) -> String { self.text.clone() } fn line(&self) -> usize { self.line } fn character(&self) -> usize { self.character } fn start(&self) -> usize { self.start } fn end(&self, current_text: &String) -> usize { self.start + current_text.len() } } macro_rules! builder { ($text: expr, $line: expr, $character: expr, $start: expr) => { BuilderMock { line: $line, character: $character, start: $start, text: $text.to_owned(), } }; } #[test] fn parse_empty() { let code = "".to_owned(); let mut lexer = Lexer::new(code); let result = lexer.tokenize(); let expected = vec![]; assert_eq!(result, expected) } #[test] fn parse_section() { let code = "[package]".to_owned(); let mut lexer = Lexer::new(code); let result = lexer.tokenize(); let expected = vec![ lexer_separator!(builder!("[", 0, 0, 0)), lexer_identifier!(builder!("package", 0, 1, 1)), lexer_separator!(builder!("]", 0, 8, 8)), ]; assert_eq!(result, expected) } #[test] fn parse_package() { let code = "redis = \"*\"".to_owned(); let mut lexer = Lexer::new(code); let result = lexer.tokenize(); let expected = vec![ lexer_identifier!(builder!("redis", 0, 0, 0)), lexer_whitespace!(builder!(" ", 0, 5, 5)), lexer_operator!(builder!("=", 0, 6, 6)), lexer_whitespace!(builder!(" ", 0, 7, 7)), lexer_string!(builder!("\"*\"", 0, 8, 8)), ]; assert_eq!(result, expected) } #[test] fn parse_complex_package() { let code = "redis = { version = \"*\" }".to_owned(); let mut lexer = Lexer::new(code); let result = lexer.tokenize(); let expected = vec![ lexer_identifier!(builder!("redis", 0, 0, 0)), lexer_whitespace!(builder!(" ", 0, 5, 5)), lexer_operator!(builder!("=", 0, 6, 6)), lexer_whitespace!(builder!(" ", 0, 7, 7)), lexer_separator!(builder!("{", 0, 8, 8)), lexer_whitespace!(builder!(" ", 0, 9, 9)), lexer_identifier!(builder!("version", 0, 10, 10)), lexer_whitespace!(builder!(" ", 0, 17, 17)), lexer_operator!(builder!("=", 0, 18, 18)), lexer_whitespace!(builder!(" ", 0, 19, 19)), lexer_string!(builder!("\"*\"", 0, 20, 20)), lexer_whitespace!(builder!(" ", 0, 23, 23)), lexer_separator!(builder!("}", 0, 24, 24)), ]; assert_eq!(result, expected) } } } mod compiler { // pub struct Compiler {} }
#[doc = "Register `SWIER2` reader"] pub type R = crate::R<SWIER2_SPEC>; #[doc = "Register `SWIER2` writer"] pub type W = crate::W<SWIER2_SPEC>; #[doc = "Field `SWI50` reader - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] pub type SWI50_R = crate::BitReader; #[doc = "Field `SWI50` writer - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] pub type SWI50_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `SWI53` reader - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] pub type SWI53_R = crate::BitReader; #[doc = "Field `SWI53` writer - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] pub type SWI53_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 18 - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] #[inline(always)] pub fn swi50(&self) -> SWI50_R { SWI50_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 21 - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] #[inline(always)] pub fn swi53(&self) -> SWI53_R { SWI53_R::new(((self.bits >> 21) & 1) != 0) } } impl W { #[doc = "Bit 18 - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] #[inline(always)] #[must_use] pub fn swi50(&mut self) -> SWI50_W<SWIER2_SPEC, 18> { SWI50_W::new(self) } #[doc = "Bit 21 - Software interrupt on event x When EXTI_PRIVCFGR.PRIVx is disabled, SWIx can be accessed with unprivileged and privileged access. When EXTI_PRIVCFGR.PRIVx is enabled, SWIx can only be accessed with privileged access. Unprivileged write to this SWIx is discarded, unprivileged read returns 0. A software interrupt is generated independent from the setting in EXTI_RTSR and EXTI_FTSR. It always returns 0 when read."] #[inline(always)] #[must_use] pub fn swi53(&mut self) -> SWI53_W<SWIER2_SPEC, 21> { SWI53_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 = "EXTI software interrupt event register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`swier2::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 [`swier2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SWIER2_SPEC; impl crate::RegisterSpec for SWIER2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`swier2::R`](R) reader structure"] impl crate::Readable for SWIER2_SPEC {} #[doc = "`write(|w| ..)` method takes [`swier2::W`](W) writer structure"] impl crate::Writable for SWIER2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SWIER2 to value 0"] impl crate::Resettable for SWIER2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::component::Component; use crate::AsTable; use clap::{App, AppSettings, ArgMatches}; use digitalocean::prelude::*; use failure::Error; use prettytable::Cell; use prettytable::Row; use prettytable::{self, Table}; mod list; pub use self::list::List; mod get; pub use self::get::Get; mod create; pub use self::create::Create; pub struct Root; impl Component for Root { fn app() -> App<'static, 'static> { App::new("droplet") .about("Interact with droplets") .setting(AppSettings::SubcommandRequired) .subcommand(List::app()) .subcommand(Get::app()) .subcommand(Create::app()) } fn handle(client: DigitalOcean, arg_matches: &ArgMatches) -> Result<(), Error> { match arg_matches.subcommand() { ("list", Some(arg_matches)) => List::handle(client, arg_matches), ("get", Some(arg_matches)) => Get::handle(client, arg_matches), ("create", Some(arg_matches)) => Create::handle(client, arg_matches), _ => panic!("Unknown subcommand provided"), } } } impl AsTable for Droplet { fn as_table(&self) { vec![self.clone()].as_table() } } impl AsTable for Vec<Droplet> { fn as_table(&self) { let mut table = Table::new(); table.set_format(*prettytable::format::consts::FORMAT_NO_BORDER_LINE_SEPARATOR); table.set_titles(Row::new(vec![ Cell::new("id"), Cell::new("name"), Cell::new("size"), Cell::new("region"), Cell::new("image"), ])); for item in self { table.add_row(Row::new(vec![ Cell::new(&format!("{}", item.id())), Cell::new(item.name()), Cell::new(item.size_slug()), Cell::new(item.region().slug()), Cell::new(item.image().name()), ])); } table.printstd(); } }
fn main() { println!("Config path: {:?}", pahkat_client::defaults::config_path()); println!("Tmp path: {:?}", pahkat_client::defaults::tmp_dir()); println!("Cache path: {:?}", pahkat_client::defaults::cache_dir()); println!("\n==As root:=="); println!( "Config path: {:?}", pathos::system::app_config_dir("Pahkat") ); println!( "Tmp path: {:?}", pathos::system::app_temporary_dir("Pahkat") ); println!("Cache path: {:?}", pathos::system::app_cache_dir("Pahkat")); }
use chrono::{DateTime, Utc}; use structopt::StructOpt; use uuid::Uuid; #[derive(Debug, StructOpt)] pub struct Command { art_id: Uuid, activate_at: DateTime<Utc>, } #[derive(Serialize)] #[serde(rename_all = "camelCase")] struct ReqBody { art_id: Uuid, activate_at: DateTime<Utc>, } pub async fn execute(cmd: Command) { let body = ReqBody { art_id: cmd.art_id, activate_at: cmd.activate_at, }; let res = reqwest::Client::new() .post(&format!( "{}/api/v1/admin/add_schedule", crate::API_SERVER_BASE )) .json(&body) .send() .await .unwrap(); println!("{:?}", res); let txt = res.text().await.unwrap(); println!("{:?}", txt); }
use std::fs; use std::io::Write; const TRANSPARENCY_THRESHOLD: u8 = 100; const SIZE_FACTOR: u32 = 10; #[allow(unused_must_use)] fn main() { let in_img = image::open("in.png").unwrap().to_rgba8(); let (width, height) = in_img.dimensions(); let header = fs::read_to_string("header.svg").unwrap() .replace("{width}", &(width * SIZE_FACTOR).to_string()) .replace("{height}", &(height * SIZE_FACTOR).to_string()); let tile_template = fs::read_to_string("tile.svg").unwrap(); let mut out_svg = fs::File::create("out.svg").unwrap(); writeln!(&mut out_svg, "{}", header).unwrap(); for x in 0..width { for y in 0..height { let pix = in_img[(x, y)]; if pix[3] < TRANSPARENCY_THRESHOLD { continue; } let cx = x * SIZE_FACTOR; let cy = y * SIZE_FACTOR; let fill = format!("rgb({}, {}, {})", pix[0], pix[1], pix[2]); let stroke = format!("rgb({}, {}, {})", pix[0] / 4, pix[1] / 4, pix[2] / 4); let tile = tile_template.replace("{cx}", &cx.to_string()) .replace("{cy}", &cy.to_string()) .replace("{fill}", &fill) .replace("{stroke}", &stroke); writeln!(&mut out_svg, "{}", tile); } } writeln!(&mut out_svg, "</svg>"); }
#![deny(unsafe_op_in_unsafe_fn)] use crate::alloc::{GlobalAlloc, Layout, System}; use crate::ptr; use crate::sys_common::alloc::{realloc_fallback, MIN_ALIGN}; // SAFETY: All methods implemented follow the contract rules defined // in `GlobalAlloc`. #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { // SAFETY: `libc::malloc` is guaranteed to be safe, it will allocate // `layout.size()` bytes of memory and return a pointer to it unsafe { libc::malloc(layout.size()) as *mut u8 } } else { // SAFETY: `libc::aligned_alloc` is guaranteed to be safe if // `layout.size()` is a multiple of `layout.align()`. This // constraint can be satisfied if `pad_to_align` is called, // which creates a layout by rounding the size of this layout up // to a multiple of the layout's alignment let aligned_layout = layout.pad_to_align(); unsafe { libc::aligned_alloc(aligned_layout.align(), aligned_layout.size()) as *mut u8 } } } #[inline] unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { // SAFETY: `libc::calloc` is safe as long that `layout.size() * 1` // would not result in integer overflow which cannot happen, // multiplying by one never overflows unsafe { libc::calloc(layout.size(), 1) as *mut u8 } } else { // SAFETY: The safety contract for `alloc` must be upheld by the caller let ptr = unsafe { self.alloc(layout.clone()) }; if !ptr.is_null() { // SAFETY: in the case of the `ptr` being not null // it will be properly aligned and a valid ptr // which satisfies `ptr::write_bytes` safety constrains unsafe { ptr::write_bytes(ptr, 0, layout.size()) }; } ptr } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { // SAFETY: `libc::free` is guaranteed to be safe if `ptr` is allocated // by this allocator or if `ptr` is NULL unsafe { libc::free(ptr as *mut libc::c_void) } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { if layout.align() <= MIN_ALIGN && layout.align() <= new_size { // SAFETY: `libc::realloc` is safe if `ptr` is allocated by this // allocator or NULL // - If `new_size` is 0 and `ptr` is not NULL, it will act as `libc::free` // - If `new_size` is not 0 and `ptr` is NULL, it will act as `libc::malloc` // - Else, it will resize the block accordingly unsafe { libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 } } else { // SAFETY: The safety contract for `realloc_fallback` must be upheld by the caller unsafe { realloc_fallback(self, ptr, layout, new_size) } } } }
use super::*; use math::*; pub struct SliderModel { pub current: f32, pub min: f32, pub max: f32, } impl SliderModel { pub fn set_percent(&mut self, value: f32) { self.current = lerp(self.min, self.max, value); } pub fn percent(&mut self) -> f32 { clamp01((self.current - self.min) / (self.max - self.min)) } } pub struct Slider<H> { pub pressed: H, pub hovered: H, pub normal: H, pub axis: Axis, } impl<'a, D, H> Component<Context<'a, D>, UiState> for Slider<H> where D: ?Sized + Graphics + 'a, H: Painter<D>, { type Event = (); type Model = SliderModel; fn behavior(&self, ctx: &Context<D>, state: &mut UiState, model: &mut Self::Model) -> Self::Event { let axis = self.axis; let id = ctx.reserve_widget_id(); let hovered = ctx.is_cursor_hovering(); let rect = ctx.rect(); let handle = if state.active_widget == Some(id) { ctx.set_hovered(); let (pos, min, delta) = match axis { Axis::Vertical => (ctx.cursor().y, rect.min.y, rect.dy()), Axis::Horizontal => (ctx.cursor().x, rect.min.x, rect.dx()), }; model.set_percent(clamp01((pos - min) / delta)); if ctx.was_released() { state.active_widget = None; } &self.pressed } else if hovered && state.active_widget.is_none() { ctx.set_hovered(); if ctx.was_pressed() { state.active_widget = Some(id); } &self.hovered } else { &self.normal }; let percent = model.percent(); handle.paint(ctx.draw(), match axis { Axis::Vertical => { let delta = rect.dx() / 2.0; let p = Point2::new( rect.min.x + delta, lerp(rect.min.y + delta, rect.max.y - delta, percent), ); (Rect { min: p, max: p }).pad(-delta) } Axis::Horizontal => { let delta = rect.dy() / 2.0; let p = Point2::new( lerp(rect.min.x + delta, rect.max.x - delta, percent), rect.min.y + delta, ); (Rect { min: p, max: p }).pad(-delta) } }); } }
use crate::models::{ComicId, ComicIdInvalidity, ItemId, ItemIdInvalidity, Token}; use crate::util::{ensure_is_authorized, ensure_is_valid}; use actix_web::{error, web, HttpResponse, Result}; use actix_web_grants::permissions::AuthDetails; use anyhow::anyhow; use database::models::{ Comic as DatabaseComic, Item as DatabaseItem, LogEntry, Occurrence as DatabaseOccurrence, }; use database::DbPool; use parse_display::Display; use semval::{context::Context as ValidationContext, Validate}; use serde::Deserialize; use shared::token_permissions; pub(crate) async fn remove_item( pool: web::Data<DbPool>, request: web::Json<RemoveItemFromComicBody>, auth: AuthDetails, ) -> Result<HttpResponse> { ensure_is_authorized(&auth, token_permissions::CAN_REMOVE_ITEM_FROM_COMIC) .map_err(error::ErrorForbidden)?; ensure_is_valid(&*request).map_err(error::ErrorBadRequest)?; let mut transaction = pool .begin() .await .map_err(error::ErrorInternalServerError)?; let comic_exists = DatabaseComic::exists_by_id(&mut *transaction, request.comic_id.into_inner()) .await .map_err(error::ErrorInternalServerError)?; if !comic_exists { return Err(error::ErrorBadRequest(anyhow!("Comic does not exist"))); } let item = DatabaseItem::by_id(&mut *transaction, request.item_id.into_inner()) .await .map_err(error::ErrorInternalServerError)? .ok_or_else(|| error::ErrorBadRequest(anyhow!("Item does not exist")))?; let item_id = request.item_id.into_inner(); let comic_id = request.comic_id.into_inner(); let result = DatabaseOccurrence::delete(&mut *transaction, item_id, comic_id) .await .map_err(error::ErrorInternalServerError)?; if result.rows_affected() != 1 { return Err(error::ErrorNotFound(format!( "Could not delete item {} from comic {}; the item is not in the comic", item_id, comic_id ))); } LogEntry::log_action( &mut *transaction, request.token.to_string(), format!( "Removed {} #{} ({}) from comic #{}", item.r#type, item.id, item.name, request.comic_id ), ) .await .map_err(error::ErrorInternalServerError)?; transaction .commit() .await .map_err(error::ErrorInternalServerError)?; Ok(HttpResponse::Ok().body("Item removed from comic")) } #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub(crate) struct RemoveItemFromComicBody { token: Token, comic_id: ComicId, item_id: ItemId, } impl Validate for RemoveItemFromComicBody { type Invalidity = RemoveItemFromComicBodyInvalidity; fn validate(&self) -> semval::ValidationResult<Self::Invalidity> { ValidationContext::new() .validate_with(&self.comic_id, RemoveItemFromComicBodyInvalidity::ComicId) .validate_with(&self.item_id, RemoveItemFromComicBodyInvalidity::ItemId) .into() } } #[derive(Copy, Clone, Debug, Display, Eq, PartialEq)] pub(crate) enum RemoveItemFromComicBodyInvalidity { #[display("{0}")] ComicId(ComicIdInvalidity), #[display("{0}")] ItemId(ItemIdInvalidity), }
use std::fs::File; use std::io::prelude::*; fn main() { let filename = "input.txt"; println!("In file {}", filename); let mut f = File::open(filename).expect("file not found"); let mut contents = String::new(); f.read_to_string(&mut contents) .expect("something went wrong reading the file"); let result = adder(contents); println!("With text:\n{}", result); } pub fn adder(input: String) -> u32 { let mut sum = 0; let numbers: Vec<u32> = input.chars() .filter_map(|c| c.to_digit(10)) .collect(); for n in 0..numbers.len() { let mut next_index = n + 1; if n == numbers.len() - 1 { next_index = 0; } if numbers[n] == numbers[next_index] { sum += numbers[n]; } } return sum; } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { assert_eq!(1, adder(String::from("1"))); } #[test] fn test_111() { assert_eq!(3, adder(String::from("111"))); } #[test] fn test_22() { assert_eq!(4, adder(String::from("22"))); } #[test] fn test_1122() { assert_eq!(3, adder(String::from("1122"))); } #[test] fn test_1111() { assert_eq!(4, adder(String::from("1111"))); } #[test] fn test_1234() { assert_eq!(0, adder(String::from("1234"))); } #[test] fn test_91212129() { assert_eq!(9, adder(String::from("91212129"))); } }
//! Contains a set of commonly used behavior tree nodes. mod sequence; pub use self::sequence::{ActiveSequence, Sequence}; mod selector; pub use self::selector::{Selector, StatefulSelector}; mod parallel; pub use self::parallel::Parallel; mod decorator; pub use self::decorator::{Decorator, Invert, Repeat, UntilFail, UntilSuccess}; mod action; pub use self::action::{Action, InlineAction}; mod condition; pub use self::condition::Condition; mod constants; pub use self::constants::{AlwaysFail, AlwaysRunning, AlwaysSucceed}; #[cfg(test)] mod testing; #[cfg(test)] pub use self::testing::CountedTick; #[cfg(test)] pub use self::testing::NoTick; #[cfg(test)] pub use self::testing::YesTick;
use anyhow::*; use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender}; use futures::lock::Mutex; use futures::stream::StreamExt; use libra_crypto::HashValue; use libra_logger::prelude::*; use libra_types::account_address::AccountAddress; use sgtypes::system_event::Event; use std::collections::HashMap; use std::sync::Arc; use tokio::runtime::Handle; pub struct Stats { executor: Handle, inner: Arc<StatsInner>, data_receiver: Option<UnboundedReceiver<(DirectedChannel, PaymentInfo)>>, data_sender: UnboundedSender<(DirectedChannel, PaymentInfo)>, control_receiver: Option<UnboundedReceiver<Event>>, control_sender: UnboundedSender<Event>, } struct StatsInner { user_channel_stats: Mutex<HashMap<DirectedChannel, ChannelStats>>, } struct ChannelStats { payment_data: Mutex<HashMap<HashValue, u64>>, } pub enum PayEnum { Paying, Payed, } pub type DirectedChannel = (AccountAddress, AccountAddress); pub type PaymentInfo = (HashValue, u64, PayEnum); impl ChannelStats { fn new() -> Self { Self { payment_data: Mutex::new(HashMap::new()), } } async fn insert(&self, amount: u64, hash_value: HashValue) { self.payment_data.lock().await.insert(hash_value, amount); } async fn remove(&self, hash_value: HashValue) { self.payment_data.lock().await.remove(&hash_value); } async fn sum(&self) -> u64 { let payment_data = self.payment_data.lock().await; let mut result = 0; for (_, amount) in payment_data.iter() { result += amount; } result } } impl Stats { pub fn new(executor: Handle) -> Self { let (control_sender, control_receiver) = futures::channel::mpsc::unbounded(); let (data_sender, data_receiver) = futures::channel::mpsc::unbounded(); let inner = StatsInner { user_channel_stats: Mutex::new(HashMap::new()), }; Self { data_sender, data_receiver: Some(data_receiver), inner: Arc::new(inner), control_sender, control_receiver: Some(control_receiver), executor, } } pub async fn back_pressure(&self, channel: &DirectedChannel) -> Result<u64> { self.inner.payment_pressure(channel).await } pub fn start(&mut self) -> Result<()> { let data_receiver = self.data_receiver.take().expect("already taken"); let control_receiver = self.control_receiver.take().expect("already taken"); self.executor.spawn(StatsInner::start( self.inner.clone(), data_receiver, control_receiver, )); Ok(()) } pub fn stats(&self, channel: DirectedChannel, payment_info: PaymentInfo) -> Result<()> { self.data_sender.unbounded_send((channel, payment_info))?; Ok(()) } pub async fn shutdown(&self) -> Result<()> { self.control_sender.unbounded_send(Event::SHUTDOWN)?; Ok(()) } } impl StatsInner { async fn start( inner: Arc<StatsInner>, mut data_receiver: UnboundedReceiver<(DirectedChannel, PaymentInfo)>, mut control_receiver: UnboundedReceiver<Event>, ) -> Result<()> { loop { futures::select! { (channel, amount) = data_receiver.select_next_some() =>{ Self::handle_data_message( inner.clone(), channel, amount, ).await?; }, _ = control_receiver.select_next_some() =>{ info!("shutdown"); break; }, } } Ok(()) } async fn handle_data_message( inner: Arc<StatsInner>, channel: DirectedChannel, payment_info: PaymentInfo, ) -> Result<()> { match payment_info.2 { PayEnum::Paying => match inner.user_channel_stats.lock().await.get(&channel) { Some(channel_stats) => { channel_stats.insert(payment_info.1, payment_info.0).await; } None => { let channel_stats = ChannelStats::new(); channel_stats.insert(payment_info.1, payment_info.0).await; inner.insert_channel_stats(channel, channel_stats).await; } }, PayEnum::Payed => match inner.user_channel_stats.lock().await.get(&channel) { Some(channel_stats) => { channel_stats.remove(payment_info.0).await; } None => {} }, } Ok(()) } async fn insert_channel_stats(&self, channel: DirectedChannel, stats: ChannelStats) { self.user_channel_stats.lock().await.insert(channel, stats); } async fn payment_pressure(&self, channel: &DirectedChannel) -> Result<u64> { match self.user_channel_stats.lock().await.get(channel) { Some(channel_stats) => Ok(channel_stats.sum().await), None => Ok(0), } } }
#[macro_export] macro_rules! yield_all { ($gen: expr) => {{ use std::ops::{Generator, GeneratorState}; use std::pin::Pin; let mut gen = $gen; loop { match Pin::new(&mut gen).resume(()) { GeneratorState::Yielded(yielded) => { yield yielded; } GeneratorState::Complete(result) => { break result; } } } }}; }
use regex::Regex; use std::collections::HashMap; use std::collections::HashSet; use std::io::{self}; #[derive(Debug, Clone)] struct Range { lower_min: usize, lower_max: usize, upper_min: usize, upper_max: usize, } impl Range { fn in_range(&self, number: usize) -> bool { (self.lower_min <= number && self.lower_max >= number) || (self.upper_min <= number && self.upper_max >= number) } fn from_vec(numbers: &Vec<usize>) -> Range { let mut tmp_vec = numbers.to_vec(); tmp_vec.sort(); assert_eq!(numbers.len(), 4); assert_eq!(&tmp_vec, numbers); Range { lower_min: numbers[0], lower_max: numbers[1], upper_min: numbers[2], upper_max: numbers[3], } } } fn main() -> io::Result<()> { let files_results = vec![ ("test.txt", 71, 1), ("test2.txt", 0, 1), ("input.txt", 18227, 2355350878831), ]; for (f, result_1, result_2) in files_results.iter() { println!("{}", f); let file_content: Vec<String> = std::fs::read_to_string(f)? .lines() .map(|x| x.to_string()) .collect(); let position_your_ticket = file_content .iter() .position(|x| x.as_str() == "your ticket:") .unwrap(); let re_field = Regex::new(r"^([a-zA-Z ]*): (\d+)-(\d+) or (\d+)-(\d+)$").unwrap(); let mut fields: HashMap<String, Range> = HashMap::new(); for field_line in file_content[0..position_your_ticket - 1].iter() { if !re_field.is_match(&field_line) { println!("NOPE {}", field_line); continue; } let caps = re_field.captures(&field_line).unwrap(); let name = caps.get(1).map_or("", |m| m.as_str()).to_string(); let numbers: Vec<usize> = (2..=5) .map(|x| { caps.get(x) .map_or("", |m| m.as_str()) .parse::<usize>() .unwrap() }) .collect(); fields.insert(name, Range::from_vec(&numbers)); } let mut invalid_fields_sum = 0; let position_nearby_tickets = file_content .iter() .position(|x| x.as_str() == "nearby tickets:") .unwrap(); let mut valid_tickets: Vec<Vec<usize>> = Vec::new(); let all_tickets: Vec<Vec<usize>> = file_content [position_nearby_tickets + 1..file_content.len()] .iter() .map(|x| x.split(",").map(|x| x.parse::<usize>().unwrap()).collect()) .collect(); for ticket_fields in all_tickets.into_iter() { let mut is_valid_ticket = true; for field_value in ticket_fields.iter() { if !fields.iter().any(|(_, range)| range.in_range(*field_value)) { invalid_fields_sum += field_value; is_valid_ticket = false; } } if is_valid_ticket { valid_tickets.push(ticket_fields); } } println!("Part 1, invalid fields sum: {}", invalid_fields_sum); assert_eq!(invalid_fields_sum, *result_1); let no_cols = valid_tickets[0].len(); assert!(valid_tickets.iter().all(|row| row.len() == no_cols)); let mut columns: Vec<Vec<usize>> = Vec::new(); for col in 0..no_cols { columns.push(valid_tickets.iter().map(|row| row[col]).collect()); } let mut maybe_keys: Vec<(usize, Vec<String>)> = Vec::new(); for (col_id, column) in columns.iter().enumerate() { let mut tmp: Vec<String> = Vec::new(); for (key, range) in fields.iter() { if column.iter().all(|x| range.in_range(*x)) { tmp.push(key.to_string()); } } maybe_keys.push((col_id, tmp)); } maybe_keys.sort_by_key(|(_k, val)| val.len()); let sorted_keys = maybe_keys; let mut seen: HashSet<String> = HashSet::new(); let mut valid_keys: Vec<String> = vec!["".to_string(); no_cols]; for (col_id, keys) in sorted_keys.into_iter() { for key in keys.into_iter() { if !seen.contains(&key) { seen.insert(key.to_string()); valid_keys[col_id] = key; break; } } } println!("{:?}", valid_keys); let my_ticket: Vec<usize> = file_content[position_your_ticket + 1] .split(",") .map(|x| x.parse::<usize>().unwrap()) .collect(); let product = valid_keys .into_iter() .zip(my_ticket.into_iter()) .filter(|(key, _val)| key.contains("departure")) .fold(1, |acc, (_, val)| val * acc); println!("Product: {}", product); assert_eq!(product, *result_2) } Ok(()) }
#[doc = "Register `FDCAN_XIDFC` reader"] pub type R = crate::R<FDCAN_XIDFC_SPEC>; #[doc = "Register `FDCAN_XIDFC` writer"] pub type W = crate::W<FDCAN_XIDFC_SPEC>; #[doc = "Field `FLESA` reader - Filter List Standard Start Address"] pub type FLESA_R = crate::FieldReader<u16>; #[doc = "Field `FLESA` writer - Filter List Standard Start Address"] pub type FLESA_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 14, O, u16>; #[doc = "Field `LSE` reader - List Size Extended"] pub type LSE_R = crate::FieldReader; #[doc = "Field `LSE` writer - List Size Extended"] pub type LSE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; impl R { #[doc = "Bits 2:15 - Filter List Standard Start Address"] #[inline(always)] pub fn flesa(&self) -> FLESA_R { FLESA_R::new(((self.bits >> 2) & 0x3fff) as u16) } #[doc = "Bits 16:23 - List Size Extended"] #[inline(always)] pub fn lse(&self) -> LSE_R { LSE_R::new(((self.bits >> 16) & 0xff) as u8) } } impl W { #[doc = "Bits 2:15 - Filter List Standard Start Address"] #[inline(always)] #[must_use] pub fn flesa(&mut self) -> FLESA_W<FDCAN_XIDFC_SPEC, 2> { FLESA_W::new(self) } #[doc = "Bits 16:23 - List Size Extended"] #[inline(always)] #[must_use] pub fn lse(&mut self) -> LSE_W<FDCAN_XIDFC_SPEC, 16> { LSE_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 = "FDCAN Extended ID Filter Configuration Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fdcan_xidfc::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 [`fdcan_xidfc::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FDCAN_XIDFC_SPEC; impl crate::RegisterSpec for FDCAN_XIDFC_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fdcan_xidfc::R`](R) reader structure"] impl crate::Readable for FDCAN_XIDFC_SPEC {} #[doc = "`write(|w| ..)` method takes [`fdcan_xidfc::W`](W) writer structure"] impl crate::Writable for FDCAN_XIDFC_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets FDCAN_XIDFC to value 0"] impl crate::Resettable for FDCAN_XIDFC_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[doc = "Register `ECCCORR` reader"] pub type R = crate::R<ECCCORR_SPEC>; #[doc = "Register `ECCCORR` writer"] pub type W = crate::W<ECCCORR_SPEC>; #[doc = "Field `ADDR_ECC` reader - ECC error address When an ECC error occurs (for single correction) during a read operation, the ADDR_ECC contains the address that generated the error. ADDR_ECC is reset when the flag error is reset. The embedded Flash memory programs the address in this register only when no ECC error flags are set. This means that only the first address that generated an ECC error is saved. The address in ADDR_ECC is relative to the Flash memory area where the error occurred (user Flash memory, system Flash memory, data area, read-only/OTP area)."] pub type ADDR_ECC_R = crate::FieldReader<u16>; #[doc = "Field `BK_ECC` reader - ECC bank flag for corrected ECC error It indicates which bank is concerned by ECC error"] pub type BK_ECC_R = crate::BitReader; #[doc = "Field `SYSF_ECC` reader - ECC flag for corrected ECC error in system FLASH It indicates if system Flash memory is concerned by ECC error."] pub type SYSF_ECC_R = crate::BitReader; #[doc = "Field `OTP_ECC` reader - OTP ECC error bit This bit is set to 1 when one single ECC correction occurred during the last successful read operation from the read-only/ OTP area. The address of the ECC error is available in ADDR_ECC bitfield."] pub type OTP_ECC_R = crate::BitReader; #[doc = "Field `ECCCIE` reader - ECC single correction error interrupt enable bit When ECCCIE bit is set to 1, an interrupt is generated when an ECC single correction error occurs during a read operation."] pub type ECCCIE_R = crate::BitReader; #[doc = "Field `ECCCIE` writer - ECC single correction error interrupt enable bit When ECCCIE bit is set to 1, an interrupt is generated when an ECC single correction error occurs during a read operation."] pub type ECCCIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ECCC` reader - ECC correction set by hardware when single ECC error has been detected and corrected. Cleared by writing 1."] pub type ECCC_R = crate::BitReader; #[doc = "Field `ECCC` writer - ECC correction set by hardware when single ECC error has been detected and corrected. Cleared by writing 1."] pub type ECCC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bits 0:15 - ECC error address When an ECC error occurs (for single correction) during a read operation, the ADDR_ECC contains the address that generated the error. ADDR_ECC is reset when the flag error is reset. The embedded Flash memory programs the address in this register only when no ECC error flags are set. This means that only the first address that generated an ECC error is saved. The address in ADDR_ECC is relative to the Flash memory area where the error occurred (user Flash memory, system Flash memory, data area, read-only/OTP area)."] #[inline(always)] pub fn addr_ecc(&self) -> ADDR_ECC_R { ADDR_ECC_R::new((self.bits & 0xffff) as u16) } #[doc = "Bit 22 - ECC bank flag for corrected ECC error It indicates which bank is concerned by ECC error"] #[inline(always)] pub fn bk_ecc(&self) -> BK_ECC_R { BK_ECC_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - ECC flag for corrected ECC error in system FLASH It indicates if system Flash memory is concerned by ECC error."] #[inline(always)] pub fn sysf_ecc(&self) -> SYSF_ECC_R { SYSF_ECC_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - OTP ECC error bit This bit is set to 1 when one single ECC correction occurred during the last successful read operation from the read-only/ OTP area. The address of the ECC error is available in ADDR_ECC bitfield."] #[inline(always)] pub fn otp_ecc(&self) -> OTP_ECC_R { OTP_ECC_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 25 - ECC single correction error interrupt enable bit When ECCCIE bit is set to 1, an interrupt is generated when an ECC single correction error occurs during a read operation."] #[inline(always)] pub fn ecccie(&self) -> ECCCIE_R { ECCCIE_R::new(((self.bits >> 25) & 1) != 0) } #[doc = "Bit 30 - ECC correction set by hardware when single ECC error has been detected and corrected. Cleared by writing 1."] #[inline(always)] pub fn eccc(&self) -> ECCC_R { ECCC_R::new(((self.bits >> 30) & 1) != 0) } } impl W { #[doc = "Bit 25 - ECC single correction error interrupt enable bit When ECCCIE bit is set to 1, an interrupt is generated when an ECC single correction error occurs during a read operation."] #[inline(always)] #[must_use] pub fn ecccie(&mut self) -> ECCCIE_W<ECCCORR_SPEC, 25> { ECCCIE_W::new(self) } #[doc = "Bit 30 - ECC correction set by hardware when single ECC error has been detected and corrected. Cleared by writing 1."] #[inline(always)] #[must_use] pub fn eccc(&mut self) -> ECCC_W<ECCCORR_SPEC, 30> { ECCC_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "FLASH Flash ECC correction register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ecccorr::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 [`ecccorr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ECCCORR_SPEC; impl crate::RegisterSpec for ECCCORR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ecccorr::R`](R) reader structure"] impl crate::Readable for ECCCORR_SPEC {} #[doc = "`write(|w| ..)` method takes [`ecccorr::W`](W) writer structure"] impl crate::Writable for ECCCORR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ECCCORR to value 0"] impl crate::Resettable for ECCCORR_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! #Art //! //! A library for modeling artistic concepts pub use kinds::PrimaryColor; pub use kinds::SecondaryColor; pub use utils::mix; pub mod kinds { /// the primary colors according to the RYB color model. pub enum PrimaryColor { Red, Yellow, Blue, } /// The secondary colors according to the RYB color model. pub enum SecondaryColor { Orange, Green, Purple, } } pub mod utils { use kinds::*; /// Combine two primary colors in euqal amounts to create a secondary color pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> Option<SecondaryColor> { match (c1, c2) { (PrimaryColor::Red, PrimaryColor::Yellow) => Some(SecondaryColor::Orange), (PrimaryColor::Red, PrimaryColor::Blue) => Some(SecondaryColor::Purple), (PrimaryColor::Red, PrimaryColor::Red) => None, (PrimaryColor::Yellow, PrimaryColor::Blue) => Some(SecondaryColor::Green), (PrimaryColor::Yellow, PrimaryColor::Red) => Some(SecondaryColor::Orange), (PrimaryColor::Yellow, PrimaryColor::Yellow) => None, (PrimaryColor::Blue, PrimaryColor::Red) => Some(SecondaryColor::Purple), (PrimaryColor::Blue, PrimaryColor::Yellow) => Some(SecondaryColor::Green), (PrimaryColor::Blue, PrimaryColor::Blue) => None, } } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
use crate::context_handle::PtrWrap; use crate::enums::CapStyle; use crate::{ AsRaw, AsRawMut, ContextHandle, ContextHandling, ContextInteractions, Error, GResult, JoinStyle, }; use geos_sys::*; use std::sync::Arc; /// Contains the parameters which describe how a [Geometry](crate::Geometry) buffer should be constructed using [buffer_with_params](crate::Geom::buffer_with_params) pub struct BufferParams<'a> { ptr: PtrWrap<*mut GEOSBufferParams>, context: Arc<ContextHandle<'a>>, } /// Build options for a [`BufferParams`] object #[derive(Default)] pub struct BufferParamsBuilder { end_cap_style: Option<CapStyle>, join_style: Option<JoinStyle>, mitre_limit: Option<f64>, quadrant_segments: Option<i32>, single_sided: Option<bool>, } impl<'a> BufferParams<'a> { pub fn new() -> GResult<BufferParams<'a>> { match ContextHandle::init_e(Some("BufferParams::new")) { Ok(context) => unsafe { let ptr = GEOSBufferParams_create_r(context.as_raw()); Ok(BufferParams { ptr: PtrWrap(ptr), context: Arc::new(context), }) }, Err(e) => Err(e), } } pub fn builder() -> BufferParamsBuilder { BufferParamsBuilder::default() } /// Specifies the end cap style of the generated buffer. pub fn set_end_cap_style(&mut self, style: CapStyle) -> GResult<()> { unsafe { let ret = GEOSBufferParams_setEndCapStyle_r( self.get_raw_context(), self.as_raw_mut_override(), style.into(), ); if ret == 0 { Err(Error::GeosError("GEOSBufferParams_setEndCapStyle_r".into())) } else { Ok(()) } } } /// Sets the join style for outside (reflex) corners between line segments. pub fn set_join_style(&mut self, style: JoinStyle) -> GResult<()> { unsafe { let ret = GEOSBufferParams_setJoinStyle_r( self.get_raw_context(), self.as_raw_mut_override(), style.into(), ); if ret == 0 { Err(Error::GeosError("GEOSBufferParams_setJoinStyle_r".into())) } else { Ok(()) } } } /// Sets the limit on the mitre ratio used for very sharp corners. /// /// The mitre ratio is the ratio of the distance from the corner /// to the end of the mitred offset corner. /// When two line segments meet at a sharp angle, /// a miter join will extend far beyond the original geometry. /// (and in the extreme case will be infinitely far.) /// To prevent unreasonable geometry, the mitre limit /// allows controlling the maximum length of the join corner. /// Corners with a ratio which exceed the limit will be beveled. pub fn set_mitre_limit(&mut self, limit: f64) -> GResult<()> { unsafe { let ret = GEOSBufferParams_setMitreLimit_r( self.get_raw_context(), self.as_raw_mut_override(), limit, ); if ret == 0 { Err(Error::GeosError("GEOSBufferParams_setMitreLimit_r".into())) } else { Ok(()) } } } /// Sets the number of line segments used to approximate /// an angle fillet. /// /// - If `quadsegs` >= 1, joins are round, and `quadsegs` indicates the number of /// segments to use to approximate a quarter-circle. /// - If `quadsegs` = 0, joins are bevelled (flat) /// - If `quadSegs` < 0, joins are mitred, and the value of qs /// indicates the mitre ration limit as `mitreLimit = |quadsegs|` /// /// For round joins, `quadsegs` determines the maximum /// error in the approximation to the true buffer curve. /// /// The default value of 8 gives less than 2% max error in the /// buffer distance. /// /// For a max error of < 1%, use QS = 12. /// For a max error of < 0.1%, use QS = 18. /// The error is always less than the buffer distance /// (in other words, the computed buffer curve is always inside /// the true curve). pub fn set_quadrant_segments(&mut self, quadsegs: i32) -> GResult<()> { unsafe { let ret = GEOSBufferParams_setQuadrantSegments_r( self.get_raw_context(), self.as_raw_mut_override(), quadsegs as _, ); if ret == 0 { Err(Error::GeosError( "GEOSBufferParams_setQuadrantSegments_r".into(), )) } else { Ok(()) } } } /// Sets whether the computed buffer should be single-sided. /// /// A single-sided buffer is constructed on only one side of each input line. /// /// The side used is determined by the sign of the buffer distance: /// - a positive distance indicates the left-hand side /// - a negative distance indicates the right-hand side /// /// The single-sided buffer of point geometries is the same as the regular buffer. /// /// The End Cap Style for single-sided buffers is always ignored, and forced to the /// equivalent of [`CapStyle::Flat`]. pub fn set_single_sided(&mut self, is_single_sided: bool) -> GResult<()> { unsafe { let single_sided = if is_single_sided { 1 } else { 0 }; let ret = GEOSBufferParams_setSingleSided_r( self.get_raw_context(), self.as_raw_mut_override(), single_sided, ); if ret == 0 { Err(Error::GeosError("GEOSBufferParams_setSingleSided_r".into())) } else { Ok(()) } } } } unsafe impl<'a> Send for BufferParams<'a> {} unsafe impl<'a> Sync for BufferParams<'a> {} impl<'a> Drop for BufferParams<'a> { fn drop(&mut self) { if !self.ptr.is_null() { unsafe { GEOSBufferParams_destroy_r(self.get_raw_context(), self.as_raw_mut()) }; } } } impl<'a> AsRaw for BufferParams<'a> { type RawType = GEOSBufferParams; fn as_raw(&self) -> *const Self::RawType { *self.ptr } } impl<'a> AsRawMut for BufferParams<'a> { type RawType = GEOSBufferParams; unsafe fn as_raw_mut_override(&self) -> *mut Self::RawType { *self.ptr } } impl<'a> ContextInteractions<'a> for BufferParams<'a> { fn set_context_handle(&mut self, context: ContextHandle<'a>) { self.context = Arc::new(context); } fn get_context_handle(&self) -> &ContextHandle<'a> { &self.context } } impl<'a> ContextHandling for BufferParams<'a> { type Context = Arc<ContextHandle<'a>>; fn get_raw_context(&self) -> GEOSContextHandle_t { self.context.as_raw() } fn clone_context(&self) -> Arc<ContextHandle<'a>> { Arc::clone(&self.context) } } impl BufferParamsBuilder { pub fn end_cap_style(mut self, style: CapStyle) -> BufferParamsBuilder { self.end_cap_style = Some(style); self } pub fn join_style(mut self, style: JoinStyle) -> BufferParamsBuilder { self.join_style = Some(style); self } pub fn mitre_limit(mut self, limit: f64) -> BufferParamsBuilder { self.mitre_limit = Some(limit); self } pub fn quadrant_segments(mut self, quadsegs: i32) -> BufferParamsBuilder { self.quadrant_segments = Some(quadsegs); self } pub fn single_sided(mut self, is_single_sided: bool) -> BufferParamsBuilder { self.single_sided = Some(is_single_sided); self } pub fn build(self) -> GResult<BufferParams<'static>> { let mut params = BufferParams::new()?; if let Some(style) = self.end_cap_style { params.set_end_cap_style(style)?; } if let Some(style) = self.join_style { params.set_join_style(style)?; } if let Some(limit) = self.mitre_limit { params.set_mitre_limit(limit)?; } if let Some(quad_segs) = self.quadrant_segments { params.set_quadrant_segments(quad_segs)?; } if let Some(is_single_sided) = self.single_sided { params.set_single_sided(is_single_sided)?; } Ok(params) } }
pub mod utils { mod macros; } pub mod input { mod formatter; mod iterator; mod source; pub use self::formatter::*; pub use self::iterator::*; pub use self::source::*; } pub mod errors { mod format; mod sort; mod source; pub use self::format::*; pub use self::sort::*; pub use self::source::*; }
use eyre::{eyre, Result}; use serde::{Deserialize, Serialize}; use std::fs; use std::{borrow::Cow, collections::HashSet}; use tera::Context; use yaml_front_matter::{Document, YamlFrontMatter}; use crate::{ item::Item, item::RenderContext, item::TeraItem, markdown::find_markdown_files, markdown::markdown_to_html, paths::AbsPath, site_url::SiteUrl, }; pub fn load_standalones(dir: AbsPath) -> Result<HashSet<StandaloneItem>> { find_markdown_files(dir) .into_iter() .map(|path| StandaloneItem::from_file(path.abs_path())) .collect::<Result<HashSet<StandaloneItem>>>() } #[derive(Debug)] pub struct StandaloneItem { pub title: String, pub path: AbsPath, pub url: SiteUrl, pub content: String, } impl PartialEq for StandaloneItem { fn eq(&self, other: &Self) -> bool { self.id() == other.id() } } impl Eq for StandaloneItem {} impl std::hash::Hash for StandaloneItem { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { self.id().hash(state) } } impl StandaloneItem { pub fn from_file(path: AbsPath) -> Result<Self> { let raw_content = fs::read_to_string(&path)?; Self::from_string(path, raw_content) } pub fn from_string(path: AbsPath, raw_content: String) -> Result<Self> { let slug = path .file_stem() .ok_or_else(|| eyre!("Missing file stem: {path}"))? .to_string(); let Document { metadata, content } = YamlFrontMatter::parse::<StandaloneMetadata>(&raw_content) .map_err(|err| eyre!("Failed to parse metadata for post: {:#?}\n{}", path, err))?; let url = SiteUrl::parse(&format!("/{slug}/")).expect("Should be able to create a url"); Ok(Self { title: metadata.title, path, url, content, }) } } impl TeraItem for StandaloneItem { fn context(&self, _ctx: &RenderContext) -> Context { Context::from_serialize(StandaloneContext { title: html_escape::encode_text(&self.title), content: &markdown_to_html(&self.content), }) .unwrap() } fn template(&self) -> &str { "static.html" } fn url(&self) -> &SiteUrl { &self.url } } #[derive(Debug, Clone, Serialize)] struct StandaloneContext<'a> { title: Cow<'a, str>, content: &'a str, } #[derive(Deserialize, Debug)] struct StandaloneMetadata { title: String, }
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // ----------------------------------------------- // This file is generated, Please do not edit it manually. // Run the following in the root of the repo to regenerate: // // cargo make generate-api // ----------------------------------------------- //! Security APIs //! //! [Perform security related activities](https://www.elastic.co/guide/en/elasticsearch/reference/master/security-api.html), including //! //! - Manage users //! - Manage application privileges //! - Manage roles //! - Manage role mappings //! - Manage API keys //! - Manage Bearer tokens //! - Authenticate users against an OpenID Connect or SAML authentication realm when using a //! custom web application other than Kibana # ! [ allow ( unused_imports ) ]use crate::{ client::Elasticsearch, error::Error, http::{ headers::{HeaderMap, HeaderName, HeaderValue, ACCEPT, CONTENT_TYPE}, request::{Body, JsonBody, NdBody, PARTS_ENCODED}, response::Response, transport::Transport, Method, }, params::*, }; use percent_encoding::percent_encode; use serde::Serialize; use std::{borrow::Cow, time::Duration}; #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Authenticate API"] pub enum SecurityAuthenticateParts { #[doc = "No parts"] None, } impl SecurityAuthenticateParts { #[doc = "Builds a relative URL path to the Security Authenticate API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityAuthenticateParts::None => "/_security/_authenticate".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Authenticate API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-authenticate.html)\n\nEnables authentication as a user and retrieve information about the authenticated user."] pub struct SecurityAuthenticate<'a, 'b> { transport: &'a Transport, parts: SecurityAuthenticateParts, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityAuthenticate<'a, 'b> { #[doc = "Creates a new instance of [SecurityAuthenticate]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityAuthenticate { transport, parts: SecurityAuthenticateParts::None, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Authenticate API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Change Password API"] pub enum SecurityChangePasswordParts<'b> { #[doc = "Username"] Username(&'b str), #[doc = "No parts"] None, } impl<'b> SecurityChangePasswordParts<'b> { #[doc = "Builds a relative URL path to the Security Change Password API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityChangePasswordParts::Username(ref username) => { let encoded_username: Cow<str> = percent_encode(username.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(26usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.push_str("/_password"); p.into() } SecurityChangePasswordParts::None => "/_security/user/_password".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Change Password API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-change-password.html)\n\nChanges the passwords of users in the native realm and built-in users."] pub struct SecurityChangePassword<'a, 'b, B> { transport: &'a Transport, parts: SecurityChangePasswordParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityChangePassword<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityChangePassword] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityChangePasswordParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityChangePassword { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityChangePassword<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityChangePassword { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Change Password API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Clear Api Key Cache API"] pub enum SecurityClearApiKeyCacheParts<'b> { #[doc = "Ids"] Ids(&'b [&'b str]), } impl<'b> SecurityClearApiKeyCacheParts<'b> { #[doc = "Builds a relative URL path to the Security Clear Api Key Cache API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityClearApiKeyCacheParts::Ids(ref ids) => { let ids_str = ids.join(","); let encoded_ids: Cow<str> = percent_encode(ids_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(32usize + encoded_ids.len()); p.push_str("/_security/api_key/"); p.push_str(encoded_ids.as_ref()); p.push_str("/_clear_cache"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Clear Api Key Cache API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-api-key-cache.html)\n\nClear a subset or all entries from the API key cache."] pub struct SecurityClearApiKeyCache<'a, 'b, B> { transport: &'a Transport, parts: SecurityClearApiKeyCacheParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityClearApiKeyCache<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityClearApiKeyCache] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityClearApiKeyCacheParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityClearApiKeyCache { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityClearApiKeyCache<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityClearApiKeyCache { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Clear Api Key Cache API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Clear Cached Privileges API"] pub enum SecurityClearCachedPrivilegesParts<'b> { #[doc = "Application"] Application(&'b [&'b str]), } impl<'b> SecurityClearCachedPrivilegesParts<'b> { #[doc = "Builds a relative URL path to the Security Clear Cached Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityClearCachedPrivilegesParts::Application(ref application) => { let application_str = application.join(","); let encoded_application: Cow<str> = percent_encode(application_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(34usize + encoded_application.len()); p.push_str("/_security/privilege/"); p.push_str(encoded_application.as_ref()); p.push_str("/_clear_cache"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Clear Cached Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-privilege-cache.html)\n\nEvicts application privileges from the native application privileges cache."] pub struct SecurityClearCachedPrivileges<'a, 'b, B> { transport: &'a Transport, parts: SecurityClearCachedPrivilegesParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityClearCachedPrivileges<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityClearCachedPrivileges] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityClearCachedPrivilegesParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityClearCachedPrivileges { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityClearCachedPrivileges<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityClearCachedPrivileges { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Clear Cached Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Clear Cached Realms API"] pub enum SecurityClearCachedRealmsParts<'b> { #[doc = "Realms"] Realms(&'b [&'b str]), } impl<'b> SecurityClearCachedRealmsParts<'b> { #[doc = "Builds a relative URL path to the Security Clear Cached Realms API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityClearCachedRealmsParts::Realms(ref realms) => { let realms_str = realms.join(","); let encoded_realms: Cow<str> = percent_encode(realms_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(30usize + encoded_realms.len()); p.push_str("/_security/realm/"); p.push_str(encoded_realms.as_ref()); p.push_str("/_clear_cache"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Clear Cached Realms API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-cache.html)\n\nEvicts users from the user cache. Can completely clear the cache or evict specific users."] pub struct SecurityClearCachedRealms<'a, 'b, B> { transport: &'a Transport, parts: SecurityClearCachedRealmsParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, usernames: Option<&'b [&'b str]>, } impl<'a, 'b, B> SecurityClearCachedRealms<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityClearCachedRealms] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityClearCachedRealmsParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityClearCachedRealms { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, usernames: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityClearCachedRealms<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityClearCachedRealms { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, usernames: self.usernames, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Comma-separated list of usernames to clear from the cache"] pub fn usernames(mut self, usernames: &'b [&'b str]) -> Self { self.usernames = Some(usernames); self } #[doc = "Creates an asynchronous call to the Security Clear Cached Realms API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] usernames: Option<&'b [&'b str]>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, usernames: self.usernames, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Clear Cached Roles API"] pub enum SecurityClearCachedRolesParts<'b> { #[doc = "Name"] Name(&'b [&'b str]), } impl<'b> SecurityClearCachedRolesParts<'b> { #[doc = "Builds a relative URL path to the Security Clear Cached Roles API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityClearCachedRolesParts::Name(ref name) => { let name_str = name.join(","); let encoded_name: Cow<str> = percent_encode(name_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(29usize + encoded_name.len()); p.push_str("/_security/role/"); p.push_str(encoded_name.as_ref()); p.push_str("/_clear_cache"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Clear Cached Roles API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-role-cache.html)\n\nEvicts roles from the native role cache."] pub struct SecurityClearCachedRoles<'a, 'b, B> { transport: &'a Transport, parts: SecurityClearCachedRolesParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityClearCachedRoles<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityClearCachedRoles] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityClearCachedRolesParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityClearCachedRoles { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityClearCachedRoles<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityClearCachedRoles { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Clear Cached Roles API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Create Api Key API"] pub enum SecurityCreateApiKeyParts { #[doc = "No parts"] None, } impl SecurityCreateApiKeyParts { #[doc = "Builds a relative URL path to the Security Create Api Key API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityCreateApiKeyParts::None => "/_security/api_key".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Create Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-create-api-key.html)\n\nCreates an API key for access without requiring basic authentication."] pub struct SecurityCreateApiKey<'a, 'b, B> { transport: &'a Transport, parts: SecurityCreateApiKeyParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityCreateApiKey<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityCreateApiKey]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityCreateApiKey { transport, parts: SecurityCreateApiKeyParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityCreateApiKey<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityCreateApiKey { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Create Api Key API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Delete Privileges API"] pub enum SecurityDeletePrivilegesParts<'b> { #[doc = "Application and Name"] ApplicationName(&'b str, &'b str), } impl<'b> SecurityDeletePrivilegesParts<'b> { #[doc = "Builds a relative URL path to the Security Delete Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityDeletePrivilegesParts::ApplicationName(ref application, ref name) => { let encoded_application: Cow<str> = percent_encode(application.as_bytes(), PARTS_ENCODED).into(); let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(22usize + encoded_application.len() + encoded_name.len()); p.push_str("/_security/privilege/"); p.push_str(encoded_application.as_ref()); p.push_str("/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Delete Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-privilege.html)\n\nRemoves application privileges."] pub struct SecurityDeletePrivileges<'a, 'b> { transport: &'a Transport, parts: SecurityDeletePrivilegesParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityDeletePrivileges<'a, 'b> { #[doc = "Creates a new instance of [SecurityDeletePrivileges] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityDeletePrivilegesParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityDeletePrivileges { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Delete Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Delete Role API"] pub enum SecurityDeleteRoleParts<'b> { #[doc = "Name"] Name(&'b str), } impl<'b> SecurityDeleteRoleParts<'b> { #[doc = "Builds a relative URL path to the Security Delete Role API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityDeleteRoleParts::Name(ref name) => { let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_name.len()); p.push_str("/_security/role/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Delete Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-role.html)\n\nRemoves roles in the native realm."] pub struct SecurityDeleteRole<'a, 'b> { transport: &'a Transport, parts: SecurityDeleteRoleParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityDeleteRole<'a, 'b> { #[doc = "Creates a new instance of [SecurityDeleteRole] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityDeleteRoleParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityDeleteRole { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Delete Role API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Delete Role Mapping API"] pub enum SecurityDeleteRoleMappingParts<'b> { #[doc = "Name"] Name(&'b str), } impl<'b> SecurityDeleteRoleMappingParts<'b> { #[doc = "Builds a relative URL path to the Security Delete Role Mapping API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityDeleteRoleMappingParts::Name(ref name) => { let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(24usize + encoded_name.len()); p.push_str("/_security/role_mapping/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Delete Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-role-mapping.html)\n\nRemoves role mappings."] pub struct SecurityDeleteRoleMapping<'a, 'b> { transport: &'a Transport, parts: SecurityDeleteRoleMappingParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityDeleteRoleMapping<'a, 'b> { #[doc = "Creates a new instance of [SecurityDeleteRoleMapping] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityDeleteRoleMappingParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityDeleteRoleMapping { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Delete Role Mapping API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Delete User API"] pub enum SecurityDeleteUserParts<'b> { #[doc = "Username"] Username(&'b str), } impl<'b> SecurityDeleteUserParts<'b> { #[doc = "Builds a relative URL path to the Security Delete User API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityDeleteUserParts::Username(ref username) => { let encoded_username: Cow<str> = percent_encode(username.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Delete User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-user.html)\n\nDeletes users from the native realm."] pub struct SecurityDeleteUser<'a, 'b> { transport: &'a Transport, parts: SecurityDeleteUserParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityDeleteUser<'a, 'b> { #[doc = "Creates a new instance of [SecurityDeleteUser] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityDeleteUserParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityDeleteUser { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Delete User API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Disable User API"] pub enum SecurityDisableUserParts<'b> { #[doc = "Username"] Username(&'b str), } impl<'b> SecurityDisableUserParts<'b> { #[doc = "Builds a relative URL path to the Security Disable User API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityDisableUserParts::Username(ref username) => { let encoded_username: Cow<str> = percent_encode(username.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(25usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.push_str("/_disable"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Disable User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-disable-user.html)\n\nDisables users in the native realm."] pub struct SecurityDisableUser<'a, 'b, B> { transport: &'a Transport, parts: SecurityDisableUserParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityDisableUser<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityDisableUser] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityDisableUserParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityDisableUser { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityDisableUser<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityDisableUser { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Disable User API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Enable User API"] pub enum SecurityEnableUserParts<'b> { #[doc = "Username"] Username(&'b str), } impl<'b> SecurityEnableUserParts<'b> { #[doc = "Builds a relative URL path to the Security Enable User API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityEnableUserParts::Username(ref username) => { let encoded_username: Cow<str> = percent_encode(username.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(24usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.push_str("/_enable"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Enable User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-enable-user.html)\n\nEnables users in the native realm."] pub struct SecurityEnableUser<'a, 'b, B> { transport: &'a Transport, parts: SecurityEnableUserParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityEnableUser<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityEnableUser] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityEnableUserParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityEnableUser { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityEnableUser<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityEnableUser { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Enable User API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Api Key API"] pub enum SecurityGetApiKeyParts { #[doc = "No parts"] None, } impl SecurityGetApiKeyParts { #[doc = "Builds a relative URL path to the Security Get Api Key API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetApiKeyParts::None => "/_security/api_key".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-api-key.html)\n\nRetrieves information for one or more API keys."] pub struct SecurityGetApiKey<'a, 'b> { transport: &'a Transport, parts: SecurityGetApiKeyParts, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, id: Option<&'b str>, name: Option<&'b str>, owner: Option<bool>, pretty: Option<bool>, realm_name: Option<&'b str>, request_timeout: Option<Duration>, source: Option<&'b str>, username: Option<&'b str>, } impl<'a, 'b> SecurityGetApiKey<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetApiKey]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityGetApiKey { transport, parts: SecurityGetApiKeyParts::None, headers, error_trace: None, filter_path: None, human: None, id: None, name: None, owner: None, pretty: None, realm_name: None, request_timeout: None, source: None, username: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "API key id of the API key to be retrieved"] pub fn id(mut self, id: &'b str) -> Self { self.id = Some(id); self } #[doc = "API key name of the API key to be retrieved"] pub fn name(mut self, name: &'b str) -> Self { self.name = Some(name); self } #[doc = "flag to query API keys owned by the currently authenticated user"] pub fn owner(mut self, owner: bool) -> Self { self.owner = Some(owner); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "realm name of the user who created this API key to be retrieved"] pub fn realm_name(mut self, realm_name: &'b str) -> Self { self.realm_name = Some(realm_name); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "user name of the user who created this API key to be retrieved"] pub fn username(mut self, username: &'b str) -> Self { self.username = Some(username); self } #[doc = "Creates an asynchronous call to the Security Get Api Key API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, id: Option<&'b str>, name: Option<&'b str>, owner: Option<bool>, pretty: Option<bool>, realm_name: Option<&'b str>, source: Option<&'b str>, username: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, id: self.id, name: self.name, owner: self.owner, pretty: self.pretty, realm_name: self.realm_name, source: self.source, username: self.username, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Builtin Privileges API"] pub enum SecurityGetBuiltinPrivilegesParts { #[doc = "No parts"] None, } impl SecurityGetBuiltinPrivilegesParts { #[doc = "Builds a relative URL path to the Security Get Builtin Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetBuiltinPrivilegesParts::None => "/_security/privilege/_builtin".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Builtin Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-builtin-privileges.html)\n\nRetrieves the list of cluster privileges and index privileges that are available in this version of Elasticsearch."] pub struct SecurityGetBuiltinPrivileges<'a, 'b> { transport: &'a Transport, parts: SecurityGetBuiltinPrivilegesParts, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetBuiltinPrivileges<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetBuiltinPrivileges]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityGetBuiltinPrivileges { transport, parts: SecurityGetBuiltinPrivilegesParts::None, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get Builtin Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Privileges API"] pub enum SecurityGetPrivilegesParts<'b> { #[doc = "No parts"] None, #[doc = "Application"] Application(&'b str), #[doc = "Application and Name"] ApplicationName(&'b str, &'b str), } impl<'b> SecurityGetPrivilegesParts<'b> { #[doc = "Builds a relative URL path to the Security Get Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetPrivilegesParts::None => "/_security/privilege".into(), SecurityGetPrivilegesParts::Application(ref application) => { let encoded_application: Cow<str> = percent_encode(application.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(21usize + encoded_application.len()); p.push_str("/_security/privilege/"); p.push_str(encoded_application.as_ref()); p.into() } SecurityGetPrivilegesParts::ApplicationName(ref application, ref name) => { let encoded_application: Cow<str> = percent_encode(application.as_bytes(), PARTS_ENCODED).into(); let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(22usize + encoded_application.len() + encoded_name.len()); p.push_str("/_security/privilege/"); p.push_str(encoded_application.as_ref()); p.push_str("/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-privileges.html)\n\nRetrieves application privileges."] pub struct SecurityGetPrivileges<'a, 'b> { transport: &'a Transport, parts: SecurityGetPrivilegesParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetPrivileges<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetPrivileges] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityGetPrivilegesParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityGetPrivileges { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Role API"] pub enum SecurityGetRoleParts<'b> { #[doc = "Name"] Name(&'b [&'b str]), #[doc = "No parts"] None, } impl<'b> SecurityGetRoleParts<'b> { #[doc = "Builds a relative URL path to the Security Get Role API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetRoleParts::Name(ref name) => { let name_str = name.join(","); let encoded_name: Cow<str> = percent_encode(name_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_name.len()); p.push_str("/_security/role/"); p.push_str(encoded_name.as_ref()); p.into() } SecurityGetRoleParts::None => "/_security/role".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-role.html)\n\nRetrieves roles in the native realm."] pub struct SecurityGetRole<'a, 'b> { transport: &'a Transport, parts: SecurityGetRoleParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetRole<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetRole] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityGetRoleParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityGetRole { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get Role API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Role Mapping API"] pub enum SecurityGetRoleMappingParts<'b> { #[doc = "Name"] Name(&'b [&'b str]), #[doc = "No parts"] None, } impl<'b> SecurityGetRoleMappingParts<'b> { #[doc = "Builds a relative URL path to the Security Get Role Mapping API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetRoleMappingParts::Name(ref name) => { let name_str = name.join(","); let encoded_name: Cow<str> = percent_encode(name_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(24usize + encoded_name.len()); p.push_str("/_security/role_mapping/"); p.push_str(encoded_name.as_ref()); p.into() } SecurityGetRoleMappingParts::None => "/_security/role_mapping".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-role-mapping.html)\n\nRetrieves role mappings."] pub struct SecurityGetRoleMapping<'a, 'b> { transport: &'a Transport, parts: SecurityGetRoleMappingParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetRoleMapping<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetRoleMapping] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityGetRoleMappingParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityGetRoleMapping { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get Role Mapping API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get Token API"] pub enum SecurityGetTokenParts { #[doc = "No parts"] None, } impl SecurityGetTokenParts { #[doc = "Builds a relative URL path to the Security Get Token API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetTokenParts::None => "/_security/oauth2/token".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get Token API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-token.html)\n\nCreates a bearer token for access without requiring basic authentication."] pub struct SecurityGetToken<'a, 'b, B> { transport: &'a Transport, parts: SecurityGetTokenParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityGetToken<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityGetToken]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityGetToken { transport, parts: SecurityGetTokenParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityGetToken<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityGetToken { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get Token API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get User API"] pub enum SecurityGetUserParts<'b> { #[doc = "Username"] Username(&'b [&'b str]), #[doc = "No parts"] None, } impl<'b> SecurityGetUserParts<'b> { #[doc = "Builds a relative URL path to the Security Get User API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetUserParts::Username(ref username) => { let username_str = username.join(","); let encoded_username: Cow<str> = percent_encode(username_str.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.into() } SecurityGetUserParts::None => "/_security/user".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-user.html)\n\nRetrieves information about users in the native realm and built-in users."] pub struct SecurityGetUser<'a, 'b> { transport: &'a Transport, parts: SecurityGetUserParts<'b>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetUser<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetUser] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityGetUserParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityGetUser { transport, parts, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get User API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Get User Privileges API"] pub enum SecurityGetUserPrivilegesParts { #[doc = "No parts"] None, } impl SecurityGetUserPrivilegesParts { #[doc = "Builds a relative URL path to the Security Get User Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGetUserPrivilegesParts::None => "/_security/user/_privileges".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Get User Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-privileges.html)\n\nRetrieves application privileges."] pub struct SecurityGetUserPrivileges<'a, 'b> { transport: &'a Transport, parts: SecurityGetUserPrivilegesParts, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b> SecurityGetUserPrivileges<'a, 'b> { #[doc = "Creates a new instance of [SecurityGetUserPrivileges]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityGetUserPrivileges { transport, parts: SecurityGetUserPrivilegesParts::None, headers, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Get User Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Get; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = Option::<()>::None; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Grant Api Key API"] pub enum SecurityGrantApiKeyParts { #[doc = "No parts"] None, } impl SecurityGrantApiKeyParts { #[doc = "Builds a relative URL path to the Security Grant Api Key API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityGrantApiKeyParts::None => "/_security/api_key/grant".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Grant Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-grant-api-key.html)\n\nCreates an API key on behalf of another user."] pub struct SecurityGrantApiKey<'a, 'b, B> { transport: &'a Transport, parts: SecurityGrantApiKeyParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityGrantApiKey<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityGrantApiKey]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityGrantApiKey { transport, parts: SecurityGrantApiKeyParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityGrantApiKey<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityGrantApiKey { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Grant Api Key API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Post; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Has Privileges API"] pub enum SecurityHasPrivilegesParts<'b> { #[doc = "No parts"] None, #[doc = "User"] User(&'b str), } impl<'b> SecurityHasPrivilegesParts<'b> { #[doc = "Builds a relative URL path to the Security Has Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityHasPrivilegesParts::None => "/_security/user/_has_privileges".into(), SecurityHasPrivilegesParts::User(ref user) => { let encoded_user: Cow<str> = percent_encode(user.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(32usize + encoded_user.len()); p.push_str("/_security/user/"); p.push_str(encoded_user.as_ref()); p.push_str("/_has_privileges"); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Has Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-has-privileges.html)\n\nDetermines whether the specified user has a specified list of privileges."] pub struct SecurityHasPrivileges<'a, 'b, B> { transport: &'a Transport, parts: SecurityHasPrivilegesParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityHasPrivileges<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityHasPrivileges] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityHasPrivilegesParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityHasPrivileges { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityHasPrivileges<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityHasPrivileges { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Has Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = match self.body { Some(_) => Method::Post, None => Method::Get, }; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Invalidate Api Key API"] pub enum SecurityInvalidateApiKeyParts { #[doc = "No parts"] None, } impl SecurityInvalidateApiKeyParts { #[doc = "Builds a relative URL path to the Security Invalidate Api Key API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityInvalidateApiKeyParts::None => "/_security/api_key".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Invalidate Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-invalidate-api-key.html)\n\nInvalidates one or more API keys."] pub struct SecurityInvalidateApiKey<'a, 'b, B> { transport: &'a Transport, parts: SecurityInvalidateApiKeyParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityInvalidateApiKey<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityInvalidateApiKey]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityInvalidateApiKey { transport, parts: SecurityInvalidateApiKeyParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityInvalidateApiKey<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityInvalidateApiKey { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Invalidate Api Key API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Invalidate Token API"] pub enum SecurityInvalidateTokenParts { #[doc = "No parts"] None, } impl SecurityInvalidateTokenParts { #[doc = "Builds a relative URL path to the Security Invalidate Token API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityInvalidateTokenParts::None => "/_security/oauth2/token".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Invalidate Token API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-invalidate-token.html)\n\nInvalidates one or more access tokens or refresh tokens."] pub struct SecurityInvalidateToken<'a, 'b, B> { transport: &'a Transport, parts: SecurityInvalidateTokenParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityInvalidateToken<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityInvalidateToken]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityInvalidateToken { transport, parts: SecurityInvalidateTokenParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityInvalidateToken<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityInvalidateToken { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Invalidate Token API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Delete; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Put Privileges API"] pub enum SecurityPutPrivilegesParts { #[doc = "No parts"] None, } impl SecurityPutPrivilegesParts { #[doc = "Builds a relative URL path to the Security Put Privileges API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityPutPrivilegesParts::None => "/_security/privilege/".into(), } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Put Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-privileges.html)\n\nAdds or updates application privileges."] pub struct SecurityPutPrivileges<'a, 'b, B> { transport: &'a Transport, parts: SecurityPutPrivilegesParts, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityPutPrivileges<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityPutPrivileges]"] pub fn new(transport: &'a Transport) -> Self { let headers = HeaderMap::new(); SecurityPutPrivileges { transport, parts: SecurityPutPrivilegesParts::None, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityPutPrivileges<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityPutPrivileges { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Put Privileges API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Put; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Put Role API"] pub enum SecurityPutRoleParts<'b> { #[doc = "Name"] Name(&'b str), } impl<'b> SecurityPutRoleParts<'b> { #[doc = "Builds a relative URL path to the Security Put Role API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityPutRoleParts::Name(ref name) => { let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_name.len()); p.push_str("/_security/role/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Put Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-role.html)\n\nAdds and updates roles in the native realm."] pub struct SecurityPutRole<'a, 'b, B> { transport: &'a Transport, parts: SecurityPutRoleParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityPutRole<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityPutRole] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityPutRoleParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityPutRole { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityPutRole<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityPutRole { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Put Role API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Put; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Put Role Mapping API"] pub enum SecurityPutRoleMappingParts<'b> { #[doc = "Name"] Name(&'b str), } impl<'b> SecurityPutRoleMappingParts<'b> { #[doc = "Builds a relative URL path to the Security Put Role Mapping API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityPutRoleMappingParts::Name(ref name) => { let encoded_name: Cow<str> = percent_encode(name.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(24usize + encoded_name.len()); p.push_str("/_security/role_mapping/"); p.push_str(encoded_name.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Put Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-role-mapping.html)\n\nCreates and updates role mappings."] pub struct SecurityPutRoleMapping<'a, 'b, B> { transport: &'a Transport, parts: SecurityPutRoleMappingParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityPutRoleMapping<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityPutRoleMapping] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityPutRoleMappingParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityPutRoleMapping { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityPutRoleMapping<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityPutRoleMapping { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Put Role Mapping API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Put; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[derive(Debug, Clone, PartialEq)] #[doc = "API parts for the Security Put User API"] pub enum SecurityPutUserParts<'b> { #[doc = "Username"] Username(&'b str), } impl<'b> SecurityPutUserParts<'b> { #[doc = "Builds a relative URL path to the Security Put User API"] pub fn url(self) -> Cow<'static, str> { match self { SecurityPutUserParts::Username(ref username) => { let encoded_username: Cow<str> = percent_encode(username.as_bytes(), PARTS_ENCODED).into(); let mut p = String::with_capacity(16usize + encoded_username.len()); p.push_str("/_security/user/"); p.push_str(encoded_username.as_ref()); p.into() } } } } #[derive(Clone, Debug)] #[doc = "Builder for the [Security Put User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-user.html)\n\nAdds and updates users in the native realm. These users are commonly referred to as native users."] pub struct SecurityPutUser<'a, 'b, B> { transport: &'a Transport, parts: SecurityPutUserParts<'b>, body: Option<B>, error_trace: Option<bool>, filter_path: Option<&'b [&'b str]>, headers: HeaderMap, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, request_timeout: Option<Duration>, source: Option<&'b str>, } impl<'a, 'b, B> SecurityPutUser<'a, 'b, B> where B: Body, { #[doc = "Creates a new instance of [SecurityPutUser] with the specified API parts"] pub fn new(transport: &'a Transport, parts: SecurityPutUserParts<'b>) -> Self { let headers = HeaderMap::new(); SecurityPutUser { transport, parts, headers, body: None, error_trace: None, filter_path: None, human: None, pretty: None, refresh: None, request_timeout: None, source: None, } } #[doc = "The body for the API call"] pub fn body<T>(self, body: T) -> SecurityPutUser<'a, 'b, JsonBody<T>> where T: Serialize, { SecurityPutUser { transport: self.transport, parts: self.parts, body: Some(body.into()), error_trace: self.error_trace, filter_path: self.filter_path, headers: self.headers, human: self.human, pretty: self.pretty, refresh: self.refresh, request_timeout: self.request_timeout, source: self.source, } } #[doc = "Include the stack trace of returned errors."] pub fn error_trace(mut self, error_trace: bool) -> Self { self.error_trace = Some(error_trace); self } #[doc = "A comma-separated list of filters used to reduce the response."] pub fn filter_path(mut self, filter_path: &'b [&'b str]) -> Self { self.filter_path = Some(filter_path); self } #[doc = "Adds a HTTP header"] pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self { self.headers.insert(key, value); self } #[doc = "Return human readable values for statistics."] pub fn human(mut self, human: bool) -> Self { self.human = Some(human); self } #[doc = "Pretty format the returned JSON response."] pub fn pretty(mut self, pretty: bool) -> Self { self.pretty = Some(pretty); self } #[doc = "If `true` (the default) then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` then do nothing with refreshes."] pub fn refresh(mut self, refresh: Refresh) -> Self { self.refresh = Some(refresh); self } #[doc = "Sets a request timeout for this API call.\n\nThe timeout is applied from when the request starts connecting until the response body has finished."] pub fn request_timeout(mut self, timeout: Duration) -> Self { self.request_timeout = Some(timeout); self } #[doc = "The URL-encoded request definition. Useful for libraries that do not accept a request body for non-POST requests."] pub fn source(mut self, source: &'b str) -> Self { self.source = Some(source); self } #[doc = "Creates an asynchronous call to the Security Put User API that can be awaited"] pub async fn send(self) -> Result<Response, Error> { let path = self.parts.url(); let method = Method::Put; let headers = self.headers; let timeout = self.request_timeout; let query_string = { #[serde_with::skip_serializing_none] #[derive(Serialize)] struct QueryParams<'b> { error_trace: Option<bool>, #[serde(serialize_with = "crate::client::serialize_coll_qs")] filter_path: Option<&'b [&'b str]>, human: Option<bool>, pretty: Option<bool>, refresh: Option<Refresh>, source: Option<&'b str>, } let query_params = QueryParams { error_trace: self.error_trace, filter_path: self.filter_path, human: self.human, pretty: self.pretty, refresh: self.refresh, source: self.source, }; Some(query_params) }; let body = self.body; let response = self .transport .send(method, &path, headers, query_string.as_ref(), body, timeout) .await?; Ok(response) } } #[doc = "Namespace client for Security APIs"] pub struct Security<'a> { transport: &'a Transport, } impl<'a> Security<'a> { #[doc = "Creates a new instance of [Security]"] pub fn new(transport: &'a Transport) -> Self { Self { transport } } pub fn transport(&self) -> &Transport { self.transport } #[doc = "[Security Authenticate API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-authenticate.html)\n\nEnables authentication as a user and retrieve information about the authenticated user."] pub fn authenticate<'b>(&'a self) -> SecurityAuthenticate<'a, 'b> { SecurityAuthenticate::new(self.transport()) } #[doc = "[Security Change Password API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-change-password.html)\n\nChanges the passwords of users in the native realm and built-in users."] pub fn change_password<'b>( &'a self, parts: SecurityChangePasswordParts<'b>, ) -> SecurityChangePassword<'a, 'b, ()> { SecurityChangePassword::new(self.transport(), parts) } #[doc = "[Security Clear Api Key Cache API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-api-key-cache.html)\n\nClear a subset or all entries from the API key cache."] pub fn clear_api_key_cache<'b>( &'a self, parts: SecurityClearApiKeyCacheParts<'b>, ) -> SecurityClearApiKeyCache<'a, 'b, ()> { SecurityClearApiKeyCache::new(self.transport(), parts) } #[doc = "[Security Clear Cached Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-privilege-cache.html)\n\nEvicts application privileges from the native application privileges cache."] pub fn clear_cached_privileges<'b>( &'a self, parts: SecurityClearCachedPrivilegesParts<'b>, ) -> SecurityClearCachedPrivileges<'a, 'b, ()> { SecurityClearCachedPrivileges::new(self.transport(), parts) } #[doc = "[Security Clear Cached Realms API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-cache.html)\n\nEvicts users from the user cache. Can completely clear the cache or evict specific users."] pub fn clear_cached_realms<'b>( &'a self, parts: SecurityClearCachedRealmsParts<'b>, ) -> SecurityClearCachedRealms<'a, 'b, ()> { SecurityClearCachedRealms::new(self.transport(), parts) } #[doc = "[Security Clear Cached Roles API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-clear-role-cache.html)\n\nEvicts roles from the native role cache."] pub fn clear_cached_roles<'b>( &'a self, parts: SecurityClearCachedRolesParts<'b>, ) -> SecurityClearCachedRoles<'a, 'b, ()> { SecurityClearCachedRoles::new(self.transport(), parts) } #[doc = "[Security Create Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-create-api-key.html)\n\nCreates an API key for access without requiring basic authentication."] pub fn create_api_key<'b>(&'a self) -> SecurityCreateApiKey<'a, 'b, ()> { SecurityCreateApiKey::new(self.transport()) } #[doc = "[Security Delete Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-privilege.html)\n\nRemoves application privileges."] pub fn delete_privileges<'b>( &'a self, parts: SecurityDeletePrivilegesParts<'b>, ) -> SecurityDeletePrivileges<'a, 'b> { SecurityDeletePrivileges::new(self.transport(), parts) } #[doc = "[Security Delete Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-role.html)\n\nRemoves roles in the native realm."] pub fn delete_role<'b>( &'a self, parts: SecurityDeleteRoleParts<'b>, ) -> SecurityDeleteRole<'a, 'b> { SecurityDeleteRole::new(self.transport(), parts) } #[doc = "[Security Delete Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-role-mapping.html)\n\nRemoves role mappings."] pub fn delete_role_mapping<'b>( &'a self, parts: SecurityDeleteRoleMappingParts<'b>, ) -> SecurityDeleteRoleMapping<'a, 'b> { SecurityDeleteRoleMapping::new(self.transport(), parts) } #[doc = "[Security Delete User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-delete-user.html)\n\nDeletes users from the native realm."] pub fn delete_user<'b>( &'a self, parts: SecurityDeleteUserParts<'b>, ) -> SecurityDeleteUser<'a, 'b> { SecurityDeleteUser::new(self.transport(), parts) } #[doc = "[Security Disable User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-disable-user.html)\n\nDisables users in the native realm."] pub fn disable_user<'b>( &'a self, parts: SecurityDisableUserParts<'b>, ) -> SecurityDisableUser<'a, 'b, ()> { SecurityDisableUser::new(self.transport(), parts) } #[doc = "[Security Enable User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-enable-user.html)\n\nEnables users in the native realm."] pub fn enable_user<'b>( &'a self, parts: SecurityEnableUserParts<'b>, ) -> SecurityEnableUser<'a, 'b, ()> { SecurityEnableUser::new(self.transport(), parts) } #[doc = "[Security Get Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-api-key.html)\n\nRetrieves information for one or more API keys."] pub fn get_api_key<'b>(&'a self) -> SecurityGetApiKey<'a, 'b> { SecurityGetApiKey::new(self.transport()) } #[doc = "[Security Get Builtin Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-builtin-privileges.html)\n\nRetrieves the list of cluster privileges and index privileges that are available in this version of Elasticsearch."] pub fn get_builtin_privileges<'b>(&'a self) -> SecurityGetBuiltinPrivileges<'a, 'b> { SecurityGetBuiltinPrivileges::new(self.transport()) } #[doc = "[Security Get Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-privileges.html)\n\nRetrieves application privileges."] pub fn get_privileges<'b>( &'a self, parts: SecurityGetPrivilegesParts<'b>, ) -> SecurityGetPrivileges<'a, 'b> { SecurityGetPrivileges::new(self.transport(), parts) } #[doc = "[Security Get Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-role.html)\n\nRetrieves roles in the native realm."] pub fn get_role<'b>(&'a self, parts: SecurityGetRoleParts<'b>) -> SecurityGetRole<'a, 'b> { SecurityGetRole::new(self.transport(), parts) } #[doc = "[Security Get Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-role-mapping.html)\n\nRetrieves role mappings."] pub fn get_role_mapping<'b>( &'a self, parts: SecurityGetRoleMappingParts<'b>, ) -> SecurityGetRoleMapping<'a, 'b> { SecurityGetRoleMapping::new(self.transport(), parts) } #[doc = "[Security Get Token API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-token.html)\n\nCreates a bearer token for access without requiring basic authentication."] pub fn get_token<'b>(&'a self) -> SecurityGetToken<'a, 'b, ()> { SecurityGetToken::new(self.transport()) } #[doc = "[Security Get User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-user.html)\n\nRetrieves information about users in the native realm and built-in users."] pub fn get_user<'b>(&'a self, parts: SecurityGetUserParts<'b>) -> SecurityGetUser<'a, 'b> { SecurityGetUser::new(self.transport(), parts) } #[doc = "[Security Get User Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-get-privileges.html)\n\nRetrieves application privileges."] pub fn get_user_privileges<'b>(&'a self) -> SecurityGetUserPrivileges<'a, 'b> { SecurityGetUserPrivileges::new(self.transport()) } #[doc = "[Security Grant Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-grant-api-key.html)\n\nCreates an API key on behalf of another user."] pub fn grant_api_key<'b>(&'a self) -> SecurityGrantApiKey<'a, 'b, ()> { SecurityGrantApiKey::new(self.transport()) } #[doc = "[Security Has Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-has-privileges.html)\n\nDetermines whether the specified user has a specified list of privileges."] pub fn has_privileges<'b>( &'a self, parts: SecurityHasPrivilegesParts<'b>, ) -> SecurityHasPrivileges<'a, 'b, ()> { SecurityHasPrivileges::new(self.transport(), parts) } #[doc = "[Security Invalidate Api Key API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-invalidate-api-key.html)\n\nInvalidates one or more API keys."] pub fn invalidate_api_key<'b>(&'a self) -> SecurityInvalidateApiKey<'a, 'b, ()> { SecurityInvalidateApiKey::new(self.transport()) } #[doc = "[Security Invalidate Token API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-invalidate-token.html)\n\nInvalidates one or more access tokens or refresh tokens."] pub fn invalidate_token<'b>(&'a self) -> SecurityInvalidateToken<'a, 'b, ()> { SecurityInvalidateToken::new(self.transport()) } #[doc = "[Security Put Privileges API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-privileges.html)\n\nAdds or updates application privileges."] pub fn put_privileges<'b>(&'a self) -> SecurityPutPrivileges<'a, 'b, ()> { SecurityPutPrivileges::new(self.transport()) } #[doc = "[Security Put Role API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-role.html)\n\nAdds and updates roles in the native realm."] pub fn put_role<'b>(&'a self, parts: SecurityPutRoleParts<'b>) -> SecurityPutRole<'a, 'b, ()> { SecurityPutRole::new(self.transport(), parts) } #[doc = "[Security Put Role Mapping API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-role-mapping.html)\n\nCreates and updates role mappings."] pub fn put_role_mapping<'b>( &'a self, parts: SecurityPutRoleMappingParts<'b>, ) -> SecurityPutRoleMapping<'a, 'b, ()> { SecurityPutRoleMapping::new(self.transport(), parts) } #[doc = "[Security Put User API](https://www.elastic.co/guide/en/elasticsearch/reference/8.0/security-api-put-user.html)\n\nAdds and updates users in the native realm. These users are commonly referred to as native users."] pub fn put_user<'b>(&'a self, parts: SecurityPutUserParts<'b>) -> SecurityPutUser<'a, 'b, ()> { SecurityPutUser::new(self.transport(), parts) } } impl Elasticsearch { #[doc = "Creates a namespace client for Security APIs"] pub fn security(&self) -> Security { Security::new(self.transport()) } }
use failure::bail; use failure::format_err; use failure::Error; use std::convert::TryFrom; use std::ops::Deref; pub trait AtCollection<T> where Self: Sized, { fn as_slice(&self) -> &[T]; fn as_vec(self) -> Vec<T>; fn into_iter(self) -> std::vec::IntoIter<T> { self.as_vec().into_iter() } fn iter(&self) -> std::slice::Iter<T> { self.as_slice().iter() } } macro_rules! atleast { ($name:ident, $n:literal, $($cons:ident),*) => { #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct $name<T> { raw: Vec<T>, } impl<T> $name<T> { pub fn new( $($cons: T),* ) -> $name<T> { $name::new_and($($cons),*, Vec::new()) } pub fn new_and($($cons: T),*, mut v: Vec<T>) -> $name<T> { let mut raw = vec![$($cons),*]; raw.append(&mut v); $name { raw } } } impl<T> AtCollection<T> for $name<T> { fn as_slice(&self) -> &[T] { self.raw.as_slice() } fn as_vec(self) -> Vec<T> { self.raw } } impl<T> Deref for $name<T> { type Target = [T]; fn deref(&self) -> &Self::Target { &self.as_slice() } } impl<T> TryFrom<Vec<T>> for $name<T> { type Error = Error; fn try_from(value: Vec<T>) -> Result<Self, Self::Error> { if value.len() < $n { bail!("{} requires at least {} values", stringify!($name), stringify!($n)) } else { Ok($name { raw: value }) } } } }; } atleast! {AtLeastOne, 1, a} atleast! {AtLeastTwo, 2, a, b} atleast! {AtLeastThree, 3, a, b, c} atleast! {AtLeastFour, 4, a, b, c, d} impl<T> AtLeastOne<T> { pub fn one(&self) -> Result<&T, Error> { match self.raw.len() { 1 => Ok(&self.raw[0]), _ => Err(format_err!("AtLeastOne has more than one element")), } } pub fn to_one(&self) -> &T { self.one().unwrap() } } #[macro_export] macro_rules! atl1 { ($($cons:expr),*) => { AtLeastOne::try_from(vec![$($cons),*]) } } #[macro_export] macro_rules! atl2 { ($($cons:expr),*) => { $crate::AtLeastTwo::try_from(vec![$($cons),*]) } } #[macro_export] macro_rules! atl3 { ($($cons:expr),*) => { AtLeastThree::try_from(vec![$($cons),*]) } } #[macro_export] macro_rules! atl4 { ($($cons:expr),*) => { AtLeastFour::try_from(vec![$($cons),*]) } } pub struct AtMostOne<T> { raw: Vec<T>, } impl<T> AtMostOne<T> { pub fn new(a: T) -> AtMostOne<T> { let raw = vec![a]; AtMostOne { raw } } } impl<T> AtCollection<T> for AtMostOne<T> { fn as_slice(&self) -> &[T] { self.raw.as_slice() } fn as_vec(self) -> Vec<T> { self.raw } } pub struct AtMostTwo<T> { raw: Vec<T>, } impl<T> AtMostTwo<T> { pub fn new(a: T) -> AtMostTwo<T> { let raw = vec![a]; AtMostTwo { raw } } } impl<T> AtCollection<T> for AtMostTwo<T> { fn as_slice(&self) -> &[T] { self.raw.as_slice() } fn as_vec(self) -> Vec<T> { self.raw } } pub struct AtMostThree<T> { raw: Vec<T>, } impl<T> AtMostThree<T> { pub fn new(a: T) -> AtMostThree<T> { let raw = vec![a]; AtMostThree { raw } } } impl<T> AtCollection<T> for AtMostThree<T> { fn as_slice(&self) -> &[T] { self.raw.as_slice() } fn as_vec(self) -> Vec<T> { self.raw } } #[cfg(test)] mod tests { use super::*; #[test] fn iter() { let alt = AtLeastTwo::new(1, 2); let mut i = alt.iter(); assert_eq!(i.next(), Some(&1)); assert_eq!(i.next(), Some(&2)); } #[test] fn into_iter() { let alt = AtLeastTwo::new(1, 2); let mut i = alt.into_iter(); assert_eq!(i.next(), Some(1)); assert_eq!(i.next(), Some(2)); } #[test] fn for_iter() { let alt = AtLeastOne::new(1); for i in alt.into_iter() { assert_eq!(i, 1); } } #[test] fn length() { let alt = AtLeastTwo::new(1, 2); assert_eq!(alt.len(), 2); } #[test] fn try_from() { assert!(AtLeastThree::try_from(vec![1, 2, 3]).is_ok()); assert!(AtLeastThree::try_from(vec![1, 2]).is_err()); assert!(AtLeastTwo::try_from(vec![1, 2, 3]).is_ok()); assert!(AtLeastTwo::try_from(vec![1]).is_err()); } #[test] fn at_least_one_macro() { let atl1 = atl1![1].unwrap(); assert_eq!(1, atl1.len()); let atl1 = atl1![1, 2, 3].unwrap(); assert_eq!(3, atl1.len()); } #[test] fn at_least_two_macro() { let atl2 = atl2![1]; assert!(atl2.is_err()); } #[test] fn at_least_two_expr() { let atl2 = atl2![1 + 2, 3 + 4]; assert_eq!(atl2.unwrap().len(), 2); } #[test] fn to_one() { let ato1 = atl1![1].unwrap(); let ato2 = atl1![1, 2].unwrap(); assert!(ato1.one().is_ok()); assert!(ato2.one().is_err()); assert_eq!(ato1.to_one(), &1); } }
use byteorder::{ByteOrder, LittleEndian}; use bytes::{BufMut, BytesMut, IntoBuf}; use std::io; use tokio_io::codec::{Decoder, Encoder}; pub mod types; pub use self::types::*; use actix::Message; #[derive(Debug, Clone)] pub enum AdsPacket { WriteReq(AmsTcpHeader<types::AdsWriteReq>), WriteRes(AmsTcpHeader<types::AdsWriteRes>), ReadReq(AmsTcpHeader<types::AdsReadReq>), ReadRes(AmsTcpHeader<types::AdsReadRes>), } impl Message for AdsPacket { type Result = AdsPacket; } pub struct AdsClientCodec; impl Decoder for AdsClientCodec { type Item = AdsPacket; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { let src_len = src.len(); let p = src.to_vec(); let size = { if src_len < 6 { return Ok(None); } LittleEndian::read_u32(&p[2..]) }; if src_len >= size as usize + 6 { let c_id = LittleEndian::read_u16(&p[6 + 16..]); let s_flag = LittleEndian::read_u16(&p[24..]); let mut b = io::Cursor::new(src); let r = match (c_id, s_flag) { (3, 4) => Some(AdsPacket::WriteReq(AmsTcpHeader::from_buf(&mut b))), (3, 5) => Some(AdsPacket::WriteRes(AmsTcpHeader::from_buf(&mut b))), (2, 4) => Some(AdsPacket::ReadReq(AmsTcpHeader::from_buf(&mut b))), (2, 5) => Some(AdsPacket::ReadRes(AmsTcpHeader::from_buf(&mut b))), _ => None, }; b.into_inner().clear(); Ok(r) } else { Ok(None) } } } impl Encoder for AdsClientCodec { type Item = AdsPacket; type Error = io::Error; fn encode(&mut self, msg: AdsPacket, dst: &mut BytesMut) -> Result<(), Self::Error> { match msg { AdsPacket::ReadReq(r) => { dst.reserve(r.size()); dst.put(r.into_buf()); } AdsPacket::ReadRes(r) => { dst.reserve(r.size()); dst.put(r.into_buf()); } AdsPacket::WriteReq(r) => { dst.reserve(r.size()); dst.put(r.into_buf()); } AdsPacket::WriteRes(r) => { dst.reserve(r.size()); dst.put(r.into_buf()); } } Ok(()) } }
pub fn a() { println!("I'm a line2"); println!("I'm a line3"); println!("I'm a line4"); }
// Copyright 2016 Taku Fukushima. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// The packet mirror interfaces and functions. extern crate pcap; extern crate pnet; use std::io::Result; use self::pnet::datalink::Channel::Ethernet; use self::pnet::packet::ethernet::EthernetPacket; /// Maximum size of TCP packets in bytes, which is 64K bytes. pub const MAX_TCP_PACKET_SIZE: i32 = 65535; /// The generic interface for packet mirror. pub trait PacketMirror { fn new(src: &str, dst: &str) -> Self; /// Does the acutal mirroring against the given Ethernet packet. fn mirror(&mut self, packet: &EthernetPacket) -> Result<()>; } /// Start packet mirroring. pub fn start_mirroring<T: PacketMirror>(src: &str, dst: &str, filter: &str) { let interfaces = pnet::datalink::interfaces(); let src_if = interfaces.iter().find(|i| i.name == src) .expect(format!("Failed to get interface {}", src).as_str()); let channel = pnet::datalink::channel(&src_if, Default::default()); let (_, mut rx) = match channel { Ok(Ethernet(tx, rx)) => (tx, rx), Ok(_) => panic!("unhandled channel type."), Err(e) => panic!("unable to create channel: {}", e), }; let mut rx_iter = rx.iter(); let mut mirror = T::new(src, dst); loop { match rx_iter.next() { Ok(packet) => { match mirror.mirror(&packet) { Ok(_) => (), Err(e) => error!("Failed to mirror the packet: {:?}", e), } }, Err(e) => { error!("Couldn't capture any packet: {:?}", e); break }, } } } pub mod gtpu_pdu;
extern crate rand; use crate::common::did::DidValue; use crate::ledger::constants; use crate::ledger::identifiers::rich_schema::RichSchemaId; use crate::tests::utils::constants::{TRUSTEE_DID, TRUSTEE_DID_FQ}; use crate::tests::utils::helpers; use crate::tests::utils::pool::*; use rand::Rng; #[cfg(test)] mod builder { use super::*; use crate::ledger::requests::rich_schema::{RSContent, RichSchema}; use crate::ledger::PreparedRequest; use crate::utils::test::get_rand_string; use std; // const RS_CONTENT_STRING: &str = r#"{"@id": "did:sov:some_hash_value", "json": "ld", "valid": "object", "@type": "sch"}"#; fn _rs_id_str() -> String { let mut id = "did:sov:".to_string(); id.push_str(&get_rand_string(32)); return id; } fn _rs_id(str_repr: String) -> RichSchemaId { return RichSchemaId::new(_rs_id_str()); } fn _rs_version() -> String { let mut rng = rand::thread_rng(); return format!( "{}.{}.{}", rng.gen::<u32>(), rng.gen::<u32>(), rng.gen::<u32>() ) .to_string(); } fn _rs_content(rs_id: RichSchemaId) -> RSContent { let rs_as_json = json!({ "@id": rs_id, "@type": constants::RS_SCHEMA_TYPE_VALUE.to_string(), "some": "other".to_string(), "valid": "objects".to_string(), }); return RSContent(rs_as_json.to_string()); } pub(crate) fn _rich_schema() -> RichSchema { let rs_id = _rs_id(_rs_id_str()); RichSchema::new( rs_id.clone(), _rs_content(rs_id), "test_rich_schema".to_string(), _rs_version(), constants::RS_SCHEMA_TYPE_VALUE.to_string(), "1".to_string(), ) } pub fn _build_rs_req(identity: DidValue, rich_schema: RichSchema) -> PreparedRequest { let pool = TestPool::new(); return pool .request_builder() .build_rich_schema_request(&identity, rich_schema) .unwrap(); } #[test] fn test_rs_request_general() { let rich_schema = _rich_schema(); let rs_req = _build_rs_req(DidValue(String::from(TRUSTEE_DID)), rich_schema.clone()); let rs_id = _rs_id(_rs_id_str()); let expected_result = json!({ "type": constants::RICH_SCHEMA, "id": rich_schema.id, "content": _rs_content(rich_schema.id), "rsName": "test_rich_schema".to_string(), "rsVersion": rich_schema.rs_version, "rsType": constants::RS_SCHEMA_TYPE_VALUE.to_string(), "ver": "1".to_string() }); helpers::check_request_operation(&rs_req, expected_result); } #[test] fn test_rs_request_works_for_fully_qualified_did() { let rich_schema = _rich_schema(); let rs_req = _build_rs_req(DidValue(String::from(TRUSTEE_DID_FQ)), rich_schema.clone()); let rs_id = _rs_id(_rs_id_str()); let expected_result = json!({ "type": constants::RICH_SCHEMA, "id": rich_schema.id, "content": _rs_content(rich_schema.id), "rsName": "test_rich_schema".to_string(), "rsVersion": rich_schema.rs_version, "rsType": constants::RS_SCHEMA_TYPE_VALUE.to_string(), "ver": "1".to_string() }); helpers::check_request_operation(&rs_req, expected_result); } } mod sender { use super::*; use crate::tests::utils::crypto::Identity; use builder; fn _test_pool() -> TestPool { return TestPool::new(); } #[test] fn test_rs_request_send_to_ledger() { let pool = _test_pool(); let trustee = Identity::trustee(); let rich_schema = builder::_rich_schema(); let mut rs_req = builder::_build_rs_req(DidValue(String::from(TRUSTEE_DID)), rich_schema); trustee.sign_request(&mut rs_req); let rs_response = pool.send_request(&rs_req).unwrap(); println!("{:?}", rs_response); } }
extern crate theca; use theca::{ThecaItem}; use theca::lineformat::{LineFormat}; struct LineTest { input_notes: Vec<ThecaItem>, condensed: bool, search: bool, expected_format: LineFormat } fn test_formatter(tests: &[LineTest]) { for t in tests.iter() { let wrapped_format = LineFormat::new(&t.input_notes, t.condensed, t.search); assert!(wrapped_format.is_ok()); let actual_format = wrapped_format.ok().unwrap(); assert_eq!(t.expected_format.colsep, actual_format.colsep); assert_eq!(t.expected_format.id_width, actual_format.id_width); assert_eq!(t.expected_format.title_width, actual_format.title_width); assert_eq!(t.expected_format.status_width, actual_format.status_width); assert_eq!(t.expected_format.touched_width, actual_format.touched_width); } } #[test] fn test_new_line_format_basic() { let basic_tests = vec![ LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: false, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 14, status_width: 0, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: false, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 14, status_width: 0, touched_width: 10 } } ]; test_formatter(&basic_tests[..]); } #[test] fn test_new_line_format_statuses() { let status_tests = vec![ LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "Started".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: false, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 14, status_width: 7, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "".to_string(), status: "Urgent".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: false, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 14, status_width: 6, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "".to_string(), status: "Urgent".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: false, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 14, status_width: 1, touched_width: 10 } } ]; test_formatter(&status_tests[..]); } #[test] fn test_new_line_format_body() { let body_tests = vec![ LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: false, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 18, status_width: 0, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: false, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 18, status_width: 0, touched_width: 10 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: true, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 14, status_width: 0, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: true, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 14, status_width: 0, touched_width: 10 } } ]; test_formatter(&body_tests[..]); } #[test] fn test_new_line_format_full() { let body_tests = vec![ LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "Started".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: false, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 18, status_width: 7, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "Started".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: false, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 18, status_width: 1, touched_width: 10 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "Urgent".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: false, search: true, expected_format: LineFormat { colsep: 2, id_width: 2, title_width: 14, status_width: 6, touched_width: 19 } }, LineTest { input_notes: vec![ ThecaItem { id: 1, title: "a title".to_string(), body: "".to_string(), status: "".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() }, ThecaItem { id: 2, title: "a longer title".to_string(), body: "this is a body".to_string(), status: "Urgent".to_string(), last_touched: "2015-01-22 19:43:24 -0800".to_string() } ], condensed: true, search: true, expected_format: LineFormat { colsep: 1, id_width: 1, title_width: 14, status_width: 1, touched_width: 10 } } ]; test_formatter(&body_tests[..]); }
#![allow(non_snake_case)] #![allow(unused_imports)] #![allow(dead_code)] use std::fs; use std::path::Path; use std::fs::File; use std::io::BufWriter; use std::borrow::Cow; use png::*; use indicatif::ProgressBar; use indicatif::ProgressStyle; use threadpool::ThreadPool; use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; mod file_loader; use file_loader::*; mod rasterizer; use rasterizer::*; mod arguments; use arguments::*; mod defs; use defs::RenderedQuadrant; mod master_img; use master_img::*; fn main() { let possible_program_args = ProgramArgs::new(); let program_args; match possible_program_args { Some(val) => program_args = val, None => { println!("No command line arguments given and no config file found. Exiting. "); return; } } program_args.dump("run_config"); println!("Running gcode rendering on input file: {:?} and base output file name of {:?}", program_args.input_file, program_args.output_file); println!("Using a threadpool with {:?} workers. ", program_args.thread_count); println!("Loading gcode file... "); let loader_result: Result<FileLoader, String>; let raw_data = fs::read_to_string(program_args.input_file); match raw_data { Ok(data) => loader_result = FileLoader::load(data), _ => { println!("Error: Input file must point to a valid file. "); return } } let loader: FileLoader; match loader_result { Ok(fl) => loader = fl, Err(e) => { println!("Error: Input file was invalid ->{:?}", e); return;} } println!("Rendering with a width of {:?}mm and a height of {:?}mm. Using {:?} pixels per mm. ", loader.settings.printbed_width, loader.settings.printbed_height, program_args.pixel_size); let progress_bar = ProgressBar::new(loader.commands.len() as u64); progress_bar.set_style(ProgressStyle::default_bar().progress_chars("#>-")); let printbed_width = loader.settings.printbed_width as i32; let printbed_height = loader.settings.printbed_height as i32; let pixel_scaling = program_args.pixel_size as i32; let draw_points = program_args.render_all_points; let workers = threadpool::ThreadPool::new(program_args.thread_count as usize); let command_len = loader.commands.len(); let (tx, rx): (Sender<RenderedQuadrant>, Receiver<RenderedQuadrant>) = mpsc::channel(); for command in loader.commands { let output_base = program_args.output_file.clone(); let transmitter = tx.clone(); workers.execute( move || { let img = Rasterizer::create( &command, printbed_width, printbed_height, pixel_scaling, draw_points); let quad_data = RenderedQuadrant { id: (command.quadrant.x, command.quadrant.y), image_data: img.data.clone() }; let mut filename_builder = string_builder::Builder::default(); filename_builder.append(output_base); filename_builder.append(command.quadrant.x.to_string()); filename_builder.append("_"); filename_builder.append(command.quadrant.y.to_string()); filename_builder.append(".png"); write_png(&filename_builder.string().unwrap(), img.width, img.height, img.data).unwrap(); if transmitter.send(quad_data).is_err() {} }); } let mut master_image_data: Vec<RenderedQuadrant> = Vec::new(); let mut largest_quadrant: (i32, i32) = (0, 0); // Note: I dont know if this could break. As in, I dont know if theres a scenario // where the active workers is 0 but there is still queued jobs. - Austin Haskell while master_image_data.len() != command_len { let master_img_quadrant = rx.try_recv(); if master_img_quadrant.is_ok() { let image_data = master_img_quadrant.unwrap(); let id = image_data.id.clone(); if id.0 > largest_quadrant.0 { largest_quadrant.0 = id.0; } if id.1 > largest_quadrant.1 { largest_quadrant.1 = id.1; } master_image_data.push(image_data); } progress_bar.set_position(master_image_data.len() as u64); } workers.join(); progress_bar.finish(); if program_args.create_joined { println!("Creating master image from quadrants... "); //create_joined_image(master_image_data, printbed_width, printbed_height, program_args.pixel_size as i32, program_args.outline_quadrants); let mut master_img = MasterImage::new( (printbed_width as u32 * program_args.pixel_size) as usize, (printbed_height as u32 * program_args.pixel_size) as usize, largest_quadrant); for quad in master_image_data { master_img.add(quad); } if program_args.outline_quadrants { master_img.outline(255, 0, 0); } let mut filename_builder = string_builder::Builder::default(); filename_builder.append(program_args.output_file); filename_builder.append("_"); filename_builder.append("master.png"); write_png(&filename_builder.string().unwrap(), master_img.image_width, master_img.image_height, master_img.data ).unwrap(); println!("Done."); } println!("Completed rendering. "); } // TODO: Figure out if the library is causing the slowdown. Seems to me like the write takes wayyyy too long for how much I'm writing. // maybe use the native library calls and make the header myself? - Austin Haskell fn write_png(filename: &str, width: usize, height: usize, img_data: Vec<u8>) -> Result<(), &str> { let file = File::create(Path::new(filename)); if file.is_err() { return Err("Failed to create file. Is the path valid?"); } let ref mut buffered_writer = BufWriter::new(file.unwrap()); let mut encoder = png::Encoder::new(buffered_writer, width as u32, height as u32); encoder.set_color(png::ColorType::RGB); encoder.set_depth(png::BitDepth::Eight); let writer = encoder.write_header(); if writer.is_err() { return Err("Failed to encode PNG header. "); } match writer.unwrap().write_image_data(&img_data) { Err(e) => println!("{:?}", e), _ => {}, } Ok(()) }
// https://www.codewars.com/kata/593c9175933500f33400003e fn multiples(m: i32, n: f64) -> Vec<f64> { (1..=m).map(|i| i as f64 * n).collect() } fn main(){ assert_eq!(multiples(3, 5.0), vec![5.0, 10.0, 15.0]); assert_eq!(multiples(5, -1.0), vec![-1.0, -2.0, -3.0, -4.0, -5.0]); assert_eq!(multiples(1, 3.14), vec![3.14]); }
pub mod board; pub mod enums; pub mod AI;
use wasmer::Store; /// New fresh `Store`. #[cfg(feature = "default-cranelift")] #[must_use] pub fn new_store() -> Store { use wasmer::{Cranelift, Universal}; let engine = Universal::new(Cranelift::default()).engine(); Store::new(&engine) } /// New fresh `Store`. #[cfg(feature = "default-singlepass")] #[must_use] pub fn new_store() -> Store { use wasmer::{Singlepass, Universal}; let engine = Universal::new(Singlepass::default()).engine(); Store::new(&engine) }
//reexport Timestamp, so other modules don't need to use stderrlog pub use stderrlog::Timestamp; #[derive(Debug)] pub struct Settings { pub verbosity: usize, pub quiet: bool, pub timestamp: Timestamp, pub module_path: Option<String>, } impl Default for Settings { fn default() -> Settings { Settings { verbosity: 0, quiet: false, timestamp: Timestamp::Off, module_path: None, } } }
mod display_message; mod set_respawn_timer; mod update_score; pub use self::display_message::DisplayMessage; pub use self::set_respawn_timer::SetRespawnTimer; pub use self::update_score::UpdateScore;
pub struct Cell { pub state: i32, } impl Cell { pub fn to_string(&self) -> String { (if self.state == 0 { "." } else { "O" }).to_string() } pub fn next_state(&self, neighbours: i32) -> i32 { if self.state == 1 { if neighbours == 2 || neighbours == 3 { 1 } else { 0 } } else { if neighbours == 3 { 1 } else { 0 } } } } #[cfg(test)] mod test { use super::Cell; #[test] fn it_prints_correct_value() { let mut cell = Cell { state: 1, }; assert_eq!(cell.to_string(), "O"); cell.state = 0; assert_eq!(cell.to_string(), "."); } #[test] fn it_returns_next_state() { let cell = Cell { state: 1, }; assert_eq!(cell.next_state(1), 0); assert_eq!(cell.next_state(2), 1); assert_eq!(cell.next_state(3), 1); assert_eq!(cell.next_state(4), 0); } }
#[derive(Debug, PartialEq, Eq, Deserialize, Clone)] pub struct LinkStatus { pub status: String, pub link: String, // URL } #[derive(Debug, PartialEq, Eq, Deserialize, Clone)] pub struct ScreenNameInfo { #[serde(rename="type")] pub kind: String, pub object_id: Id, }
pub struct MFCC { n_mfcc: u32, n_fft: u32, stride: u32, n_mels: u32 } impl MFCC { pub fn new(n_mfcc: u32, n_fft: u32, stride: u32, n_mels: u32) -> MFCC { MFCC { n_mfcc, n_fft, stride, n_mels } } pub fn transform(v :&Vec<i16>) -> Vec<Vec<f32>> { todo!() } }
use crate::{ i8080::{error::EmulateError, Result, I8080, Register}, instruction::{InstructionData, Opcode}, io::IO, }; impl I8080 { pub(crate) fn out<U: IO>(&mut self, data: InstructionData, io: &mut U) -> Result<()> { if let Some(port) = data.first() { io.write_port(port, self.a); } else { return Err(EmulateError::InvalidInstructionData { opcode: Opcode::OUT, data, }); } Ok(()) } pub(crate) fn input<U: IO>(&mut self, data: InstructionData, io: &mut U) -> Result<()> { if let Some(port) = data.first() { self.set_8bit_register(Register::A, io.read_port(port)); } else { return Err(EmulateError::InvalidInstructionData { opcode: Opcode::IN, data, }); } Ok(()) } }
fn main() { println!("Hello, world!") tuples(); structs(); tuple_structs_new_types(); enums(); } fn tuples() { let x = (1i, "hello"); let x2: (int, &str) = (1, "hello"); println!("{}", x); println!("{}", x2); let (a, b, c) = (1i, 2i, 3i); // Pattern matching println!("a is {}, b is {}, c is {}.", a, b, c); let mut left = (1i, 2i); let right = (2i, 3i); left = right; // Assignment of one tuple into another, if they share types. println!("Left is {}.", left); let x3 = (1i, 2i, 3i); let y3 = (2i, 2i, 4i); if x3 == y3 { println!("yes!"); } else { println!("no!"); } let (x4, y4) = next_two(5i); println!("x = {}, y = {}", x4, y4); } fn next_two(x: int) -> (int, int) { (x + 1, x + 2) } fn structs() { let origin = Point { x: 0, y: 0 }; println!("The origin is at ({}, {}).", origin.x, origin.y); let mut mutable_point = Point { x: 0, y: 0 }; mutable_point.x = 5; println!("The mutable_point is at ({}, {}).", mutable_point.x, mutable_point.y); } struct Point { x: int, y: int } fn tuple_structs_new_types() { let black = Color(0, 0, 0); let origin = Point3d(0, 0, 0); let length = Inches(10); // Cool way of doing "type synonyms" (in essence). let Inches(integer_length) = length; println!("The length is {} inches.", integer_length); } struct Color(int, int, int); struct Point3d(int, int, int); struct Inches(int); fn enums() { let x = 5i; let y = 10i; let ordering = cmp(x, y); if ordering == Less { println!("Less"); } else if ordering == Greater { println!("Greater"); } else { println!("Equal"); } let optional_x = Value(5); let optional_y = Missing; match optional_x { Value(n) => println!("x is {:d}", n), Missing => println!("x is missing!") } match optional_y { Value(n) => println!("y is {:d}", n), Missing => println!("y is missing!") } } // Provided by the standard library: // enum Ordering { // Less, // Equal, // Greater // } fn cmp(a: int, b: int) -> Ordering { if a < b { Less } else if a > b { Greater } else { Equal } } enum OptionalInt { Value(int), Missing }
use async_trait::async_trait; use futures_util::{ future::{self, Either}, stream::StreamExt, }; use mpsc::{Receiver, Sender, UnboundedReceiver, UnboundedSender}; use tokio::sync::mpsc; use tracing::{error, info}; use mqtt3::{ proto::{Publication, QoS}, PublishHandle, ReceivedPublication, }; use trc_client::TrcClient; use crate::{MessageTesterError, BACKWARDS_TOPIC}; #[derive(Debug, Clone)] pub struct MessageChannelShutdownHandle(Sender<()>); impl MessageChannelShutdownHandle { pub fn new(sender: Sender<()>) -> Self { Self(sender) } pub async fn shutdown(mut self) -> Result<(), MessageTesterError> { self.0 .send(()) .await .map_err(MessageTesterError::SendShutdownSignal) } } /// Responsible for receiving publications and taking some action. #[async_trait] pub trait MessageHandler { /// Starts handling messages sent to the handler async fn handle(&mut self, publication: ReceivedPublication) -> Result<(), MessageTesterError>; } /// Responsible for receiving publications and reporting result to the Test Result Coordinator. pub struct ReportResultMessageHandler { reporting_client: TrcClient, } impl ReportResultMessageHandler { pub fn new(reporting_client: TrcClient) -> Self { Self { reporting_client } } } #[async_trait] impl MessageHandler for ReportResultMessageHandler { async fn handle( &mut self, received_publication: ReceivedPublication, ) -> Result<(), MessageTesterError> { info!("should send result to TRC, but not implemented yet"); Ok(()) } } /// Responsible for receiving publications and sending them back to the downstream edge. pub struct RelayingMessageHandler { publish_handle: PublishHandle, } impl RelayingMessageHandler { pub fn new(publish_handle: PublishHandle) -> Self { Self { publish_handle } } } #[async_trait] impl MessageHandler for RelayingMessageHandler { async fn handle( &mut self, received_publication: ReceivedPublication, ) -> Result<(), MessageTesterError> { info!("relaying publication {:?}", received_publication); let new_publication = Publication { topic_name: BACKWARDS_TOPIC.to_string(), qos: QoS::ExactlyOnce, retain: true, payload: received_publication.payload, }; self.publish_handle .publish(new_publication) .await .map_err(MessageTesterError::Publish)?; Ok(()) } } /// Serves as a channel between a mqtt client's received publications and a message handler. /// Exposes a message channel to send messages to a separately running thread that will listen /// for incoming messages and handle them according to custom message handler. pub struct MessageChannel<H: ?Sized + MessageHandler + Send> { publication_sender: UnboundedSender<ReceivedPublication>, publication_receiver: UnboundedReceiver<ReceivedPublication>, shutdown_handle: MessageChannelShutdownHandle, shutdown_recv: Receiver<()>, message_handler: Box<H>, } impl<H> MessageChannel<H> where H: MessageHandler + ?Sized + Send, { pub fn new(message_handler: Box<H>) -> Self { let (publication_sender, publication_receiver) = mpsc::unbounded_channel::<ReceivedPublication>(); let (shutdown_send, shutdown_recv) = mpsc::channel::<()>(1); let shutdown_handle = MessageChannelShutdownHandle::new(shutdown_send); Self { publication_sender, publication_receiver, shutdown_handle, shutdown_recv, message_handler, } } pub async fn run(mut self) -> Result<(), MessageTesterError> { info!("starting message channel"); loop { let received_pub = self.publication_receiver.next(); let shutdown_signal = self.shutdown_recv.next(); match future::select(received_pub, shutdown_signal).await { Either::Left((received_publication, _)) => { if let Some(received_publication) = received_publication { info!("received publication {:?}", received_publication); self.message_handler.handle(received_publication).await?; } else { error!("failed listening for incoming publication"); return Err(MessageTesterError::ListenForIncomingPublications); } } Either::Right((shutdown_signal, _)) => { if let Some(shutdown_signal) = shutdown_signal { info!("received shutdown signal"); return Ok(()); } else { error!("failed listening for shutdown"); return Err(MessageTesterError::ListenForShutdown); } } }; } } pub fn message_channel(&self) -> UnboundedSender<ReceivedPublication> { self.publication_sender.clone() } pub fn shutdown_handle(&self) -> MessageChannelShutdownHandle { self.shutdown_handle.clone() } }
use syn::{ parse_quote, punctuated::Punctuated, token::Comma, visit_mut::VisitMut, Lit, Meta, NestedMeta, }; fn parse_features(features: &NestedMeta) -> Vec<String> { let lit = match features { NestedMeta::Lit(lit) => lit, _ => unimplemented!(), }; let s = match lit { Lit::Str(s) => s, _ => unimplemented!(), }; s.value().split(',').map(str::to_string).collect() } pub(crate) fn transform(input: Punctuated<NestedMeta, Comma>) -> NestedMeta { assert!(input.len() == 2); let features = parse_features(&input[0]); let mut attr = input.into_iter().nth(1).unwrap(); struct Visitor(Vec<String>); impl VisitMut for Visitor { fn visit_meta_mut(&mut self, i: &mut Meta) { // replace instances of `target_feature = "..."` when they match a detected target // feature. if let Meta::NameValue(nv) = i { if nv.path == parse_quote!(target_feature) { if let Lit::Str(s) = &nv.lit { if self.0.contains(&s.value()) { *i = parse_quote! { all() }; } } } } syn::visit_mut::visit_meta_mut(self, i); } } Visitor(features).visit_nested_meta_mut(&mut attr); attr }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Timerx Control Register"] pub timecr: TIMECR, #[doc = "0x04 - Timerx Interrupt Status Register"] pub timeisr: TIMEISR, #[doc = "0x08 - Timerx Interrupt Clear Register"] pub timeicr: TIMEICR, #[doc = "0x0c - TIMxDIER5"] pub timedier5: TIMEDIER5, #[doc = "0x10 - Timerx Counter Register"] pub cnter: CNTER, #[doc = "0x14 - Timerx Period Register"] pub perer: PERER, #[doc = "0x18 - Timerx Repetition Register"] pub reper: REPER, #[doc = "0x1c - Timerx Compare 1 Register"] pub cmp1er: CMP1ER, #[doc = "0x20 - Timerx Compare 1 Compound Register"] pub cmp1cer: CMP1CER, #[doc = "0x24 - Timerx Compare 2 Register"] pub cmp2er: CMP2ER, #[doc = "0x28 - Timerx Compare 3 Register"] pub cmp3er: CMP3ER, #[doc = "0x2c - Timerx Compare 4 Register"] pub cmp4er: CMP4ER, #[doc = "0x30 - Timerx Capture 1 Register"] pub cpt1er: CPT1ER, #[doc = "0x34 - Timerx Capture 2 Register"] pub cpt2er: CPT2ER, #[doc = "0x38 - Timerx Deadtime Register"] pub dter: DTER, #[doc = "0x3c - Timerx Output1 Set Register"] pub sete1r: SETE1R, #[doc = "0x40 - Timerx Output1 Reset Register"] pub rste1r: RSTE1R, #[doc = "0x44 - Timerx Output2 Set Register"] pub sete2r: SETE2R, #[doc = "0x48 - Timerx Output2 Reset Register"] pub rste2r: RSTE2R, #[doc = "0x4c - Timerx External Event Filtering Register 1"] pub eefer1: EEFER1, #[doc = "0x50 - Timerx External Event Filtering Register 2"] pub eefer2: EEFER2, #[doc = "0x54 - TimerA Reset Register"] pub rster: RSTER, #[doc = "0x58 - Timerx Chopper Register"] pub chper: CHPER, #[doc = "0x5c - Timerx Capture 2 Control Register"] pub cpt1ecr: CPT1ECR, #[doc = "0x60 - CPT2xCR"] pub cpt2ecr: CPT2ECR, #[doc = "0x64 - Timerx Output Register"] pub outer: OUTER, #[doc = "0x68 - Timerx Fault Register"] pub flter: FLTER, } #[doc = "TIMECR (rw) register accessor: Timerx Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timecr::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 [`timecr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timecr`] module"] pub type TIMECR = crate::Reg<timecr::TIMECR_SPEC>; #[doc = "Timerx Control Register"] pub mod timecr; #[doc = "TIMEISR (r) register accessor: Timerx Interrupt Status Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timeisr::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timeisr`] module"] pub type TIMEISR = crate::Reg<timeisr::TIMEISR_SPEC>; #[doc = "Timerx Interrupt Status Register"] pub mod timeisr; #[doc = "TIMEICR (w) register accessor: Timerx Interrupt Clear Register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`timeicr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timeicr`] module"] pub type TIMEICR = crate::Reg<timeicr::TIMEICR_SPEC>; #[doc = "Timerx Interrupt Clear Register"] pub mod timeicr; #[doc = "TIMEDIER5 (rw) register accessor: TIMxDIER5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`timedier5::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 [`timedier5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`timedier5`] module"] pub type TIMEDIER5 = crate::Reg<timedier5::TIMEDIER5_SPEC>; #[doc = "TIMxDIER5"] pub mod timedier5; #[doc = "CNTER (rw) register accessor: Timerx Counter Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cnter::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 [`cnter::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cnter`] module"] pub type CNTER = crate::Reg<cnter::CNTER_SPEC>; #[doc = "Timerx Counter Register"] pub mod cnter; #[doc = "PERER (rw) register accessor: Timerx Period Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`perer::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 [`perer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`perer`] module"] pub type PERER = crate::Reg<perer::PERER_SPEC>; #[doc = "Timerx Period Register"] pub mod perer; #[doc = "REPER (rw) register accessor: Timerx Repetition Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`reper::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 [`reper::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`reper`] module"] pub type REPER = crate::Reg<reper::REPER_SPEC>; #[doc = "Timerx Repetition Register"] pub mod reper; #[doc = "CMP1ER (rw) register accessor: Timerx Compare 1 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp1er::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 [`cmp1er::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp1er`] module"] pub type CMP1ER = crate::Reg<cmp1er::CMP1ER_SPEC>; #[doc = "Timerx Compare 1 Register"] pub mod cmp1er; #[doc = "CMP1CER (rw) register accessor: Timerx Compare 1 Compound Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp1cer::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 [`cmp1cer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp1cer`] module"] pub type CMP1CER = crate::Reg<cmp1cer::CMP1CER_SPEC>; #[doc = "Timerx Compare 1 Compound Register"] pub mod cmp1cer; #[doc = "CMP2ER (rw) register accessor: Timerx Compare 2 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp2er::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 [`cmp2er::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp2er`] module"] pub type CMP2ER = crate::Reg<cmp2er::CMP2ER_SPEC>; #[doc = "Timerx Compare 2 Register"] pub mod cmp2er; #[doc = "CMP3ER (rw) register accessor: Timerx Compare 3 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp3er::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 [`cmp3er::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp3er`] module"] pub type CMP3ER = crate::Reg<cmp3er::CMP3ER_SPEC>; #[doc = "Timerx Compare 3 Register"] pub mod cmp3er; #[doc = "CMP4ER (rw) register accessor: Timerx Compare 4 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cmp4er::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 [`cmp4er::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cmp4er`] module"] pub type CMP4ER = crate::Reg<cmp4er::CMP4ER_SPEC>; #[doc = "Timerx Compare 4 Register"] pub mod cmp4er; #[doc = "CPT1ER (r) register accessor: Timerx Capture 1 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt1er::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt1er`] module"] pub type CPT1ER = crate::Reg<cpt1er::CPT1ER_SPEC>; #[doc = "Timerx Capture 1 Register"] pub mod cpt1er; #[doc = "CPT2ER (r) register accessor: Timerx Capture 2 Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt2er::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt2er`] module"] pub type CPT2ER = crate::Reg<cpt2er::CPT2ER_SPEC>; #[doc = "Timerx Capture 2 Register"] pub mod cpt2er; #[doc = "DTER (rw) register accessor: Timerx Deadtime Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dter::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 [`dter::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dter`] module"] pub type DTER = crate::Reg<dter::DTER_SPEC>; #[doc = "Timerx Deadtime Register"] pub mod dter; #[doc = "SETE1R (rw) register accessor: Timerx Output1 Set Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sete1r::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 [`sete1r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sete1r`] module"] pub type SETE1R = crate::Reg<sete1r::SETE1R_SPEC>; #[doc = "Timerx Output1 Set Register"] pub mod sete1r; #[doc = "RSTE1R (rw) register accessor: Timerx Output1 Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rste1r::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 [`rste1r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rste1r`] module"] pub type RSTE1R = crate::Reg<rste1r::RSTE1R_SPEC>; #[doc = "Timerx Output1 Reset Register"] pub mod rste1r; #[doc = "SETE2R (rw) register accessor: Timerx Output2 Set Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sete2r::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 [`sete2r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sete2r`] module"] pub type SETE2R = crate::Reg<sete2r::SETE2R_SPEC>; #[doc = "Timerx Output2 Set Register"] pub mod sete2r; #[doc = "RSTE2R (rw) register accessor: Timerx Output2 Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rste2r::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 [`rste2r::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rste2r`] module"] pub type RSTE2R = crate::Reg<rste2r::RSTE2R_SPEC>; #[doc = "Timerx Output2 Reset Register"] pub mod rste2r; #[doc = "EEFER1 (rw) register accessor: Timerx External Event Filtering Register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eefer1::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 [`eefer1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eefer1`] module"] pub type EEFER1 = crate::Reg<eefer1::EEFER1_SPEC>; #[doc = "Timerx External Event Filtering Register 1"] pub mod eefer1; #[doc = "EEFER2 (rw) register accessor: Timerx External Event Filtering Register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`eefer2::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 [`eefer2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`eefer2`] module"] pub type EEFER2 = crate::Reg<eefer2::EEFER2_SPEC>; #[doc = "Timerx External Event Filtering Register 2"] pub mod eefer2; #[doc = "RSTER (rw) register accessor: TimerA Reset Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rster::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 [`rster::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rster`] module"] pub type RSTER = crate::Reg<rster::RSTER_SPEC>; #[doc = "TimerA Reset Register"] pub mod rster; #[doc = "CHPER (rw) register accessor: Timerx Chopper Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`chper::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 [`chper::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`chper`] module"] pub type CHPER = crate::Reg<chper::CHPER_SPEC>; #[doc = "Timerx Chopper Register"] pub mod chper; #[doc = "CPT1ECR (rw) register accessor: Timerx Capture 2 Control Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt1ecr::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 [`cpt1ecr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt1ecr`] module"] pub type CPT1ECR = crate::Reg<cpt1ecr::CPT1ECR_SPEC>; #[doc = "Timerx Capture 2 Control Register"] pub mod cpt1ecr; #[doc = "CPT2ECR (rw) register accessor: CPT2xCR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cpt2ecr::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 [`cpt2ecr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cpt2ecr`] module"] pub type CPT2ECR = crate::Reg<cpt2ecr::CPT2ECR_SPEC>; #[doc = "CPT2xCR"] pub mod cpt2ecr; #[doc = "OUTER (rw) register accessor: Timerx Output Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`outer::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 [`outer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`outer`] module"] pub type OUTER = crate::Reg<outer::OUTER_SPEC>; #[doc = "Timerx Output Register"] pub mod outer; #[doc = "FLTER (rw) register accessor: Timerx Fault Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`flter::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 [`flter::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`flter`] module"] pub type FLTER = crate::Reg<flter::FLTER_SPEC>; #[doc = "Timerx Fault Register"] pub mod flter;
pub struct Request { pub method: String, pub path: String, } impl Request {}
use ring::constant_time::verify_slices_are_equal; use ring::{hmac, signature}; use crate::algorithms::Algorithm; use crate::decoding::{DecodingKey, DecodingKeyKind}; use crate::encoding::EncodingKey; use crate::errors::Result; use crate::serialization::{b64_decode, b64_encode}; pub(crate) mod ecdsa; pub(crate) mod eddsa; pub(crate) mod rsa; /// The actual HS signing + encoding /// Could be in its own file to match RSA/EC but it's 2 lines... pub(crate) fn sign_hmac(alg: hmac::Algorithm, key: &[u8], message: &[u8]) -> String { let digest = hmac::sign(&hmac::Key::new(alg, key), message); b64_encode(digest) } /// Take the payload of a JWT, sign it using the algorithm given and return /// the base64 url safe encoded of the result. /// /// If you just want to encode a JWT, use `encode` instead. pub fn sign(message: &[u8], key: &EncodingKey, algorithm: Algorithm) -> Result<String> { match algorithm { Algorithm::HS256 => Ok(sign_hmac(hmac::HMAC_SHA256, key.inner(), message)), Algorithm::HS384 => Ok(sign_hmac(hmac::HMAC_SHA384, key.inner(), message)), Algorithm::HS512 => Ok(sign_hmac(hmac::HMAC_SHA512, key.inner(), message)), Algorithm::ES256 | Algorithm::ES384 => { ecdsa::sign(ecdsa::alg_to_ec_signing(algorithm), key.inner(), message) } Algorithm::EdDSA => eddsa::sign(key.inner(), message), Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 | Algorithm::PS256 | Algorithm::PS384 | Algorithm::PS512 => rsa::sign(rsa::alg_to_rsa_signing(algorithm), key.inner(), message), } } /// See Ring docs for more details fn verify_ring( alg: &'static dyn signature::VerificationAlgorithm, signature: &str, message: &[u8], key: &[u8], ) -> Result<bool> { let signature_bytes = b64_decode(signature)?; let public_key = signature::UnparsedPublicKey::new(alg, key); let res = public_key.verify(message, &signature_bytes); Ok(res.is_ok()) } /// Compares the signature given with a re-computed signature for HMAC or using the public key /// for RSA/EC. /// /// If you just want to decode a JWT, use `decode` instead. /// /// `signature` is the signature part of a jwt (text after the second '.') /// /// `message` is base64(header) + "." + base64(claims) pub fn verify( signature: &str, message: &[u8], key: &DecodingKey, algorithm: Algorithm, ) -> Result<bool> { match algorithm { Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => { // we just re-sign the message with the key and compare if they are equal let signed = sign(message, &EncodingKey::from_secret(key.as_bytes()), algorithm)?; Ok(verify_slices_are_equal(signature.as_ref(), signed.as_ref()).is_ok()) } Algorithm::ES256 | Algorithm::ES384 => verify_ring( ecdsa::alg_to_ec_verification(algorithm), signature, message, key.as_bytes(), ), Algorithm::EdDSA => verify_ring( eddsa::alg_to_ec_verification(algorithm), signature, message, key.as_bytes(), ), Algorithm::RS256 | Algorithm::RS384 | Algorithm::RS512 | Algorithm::PS256 | Algorithm::PS384 | Algorithm::PS512 => { let alg = rsa::alg_to_rsa_parameters(algorithm); match &key.kind { DecodingKeyKind::SecretOrDer(bytes) => verify_ring(alg, signature, message, bytes), DecodingKeyKind::RsaModulusExponent { n, e } => { rsa::verify_from_components(alg, signature, message, (n, e)) } } } } }
#![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)] RoleAssignments_CheckPrincipalAccess(#[from] role_assignments::check_principal_access::Error), #[error(transparent)] RoleDefinitions_ListRoleDefinitions(#[from] role_definitions::list_role_definitions::Error), #[error(transparent)] RoleDefinitions_GetRoleDefinitionById(#[from] role_definitions::get_role_definition_by_id::Error), #[error(transparent)] RoleDefinitions_ListScopes(#[from] role_definitions::list_scopes::Error), #[error(transparent)] RoleAssignments_ListRoleAssignments(#[from] role_assignments::list_role_assignments::Error), #[error(transparent)] RoleAssignments_GetRoleAssignmentById(#[from] role_assignments::get_role_assignment_by_id::Error), #[error(transparent)] RoleAssignments_CreateRoleAssignment(#[from] role_assignments::create_role_assignment::Error), #[error(transparent)] RoleAssignments_DeleteRoleAssignmentById(#[from] role_assignments::delete_role_assignment_by_id::Error), } pub mod role_assignments { use super::{models, API_VERSION}; pub async fn check_principal_access( operation_config: &crate::OperationConfig, request: &models::CheckPrincipalAccessRequest, ) -> std::result::Result<models::CheckPrincipalAccessResponse, check_principal_access::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/checkAccessSynapseRbac", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(check_principal_access::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(check_principal_access::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(request).map_err(check_principal_access::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(check_principal_access::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(check_principal_access::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::CheckPrincipalAccessResponse = serde_json::from_slice(rsp_body) .map_err(|source| check_principal_access::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| check_principal_access::Error::DeserializeError(source, rsp_body.clone()))?; Err(check_principal_access::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod check_principal_access { 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::ErrorContract, }, #[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_role_assignments( operation_config: &crate::OperationConfig, role_id: Option<&str>, principal_id: Option<&str>, scope: Option<&str>, x_ms_continuation: Option<&str>, ) -> std::result::Result<models::RoleAssignmentDetailsList, list_role_assignments::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleAssignments", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(list_role_assignments::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_role_assignments::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(role_id) = role_id { url.query_pairs_mut().append_pair("roleId", role_id); } if let Some(principal_id) = principal_id { url.query_pairs_mut().append_pair("principalId", principal_id); } if let Some(scope) = scope { url.query_pairs_mut().append_pair("scope", scope); } if let Some(x_ms_continuation) = x_ms_continuation { req_builder = req_builder.header("x-ms-continuation", x_ms_continuation); } 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_role_assignments::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_role_assignments::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RoleAssignmentDetailsList = serde_json::from_slice(rsp_body) .map_err(|source| list_role_assignments::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| list_role_assignments::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_role_assignments::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_role_assignments { 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::ErrorContract, }, #[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_role_assignment_by_id( operation_config: &crate::OperationConfig, role_assignment_id: &str, ) -> std::result::Result<models::RoleAssignmentDetails, get_role_assignment_by_id::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleAssignments/{}", operation_config.base_path(), role_assignment_id); let mut url = url::Url::parse(url_str).map_err(get_role_assignment_by_id::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_role_assignment_by_id::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_role_assignment_by_id::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_role_assignment_by_id::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RoleAssignmentDetails = serde_json::from_slice(rsp_body) .map_err(|source| get_role_assignment_by_id::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| get_role_assignment_by_id::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_role_assignment_by_id::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_role_assignment_by_id { 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::ErrorContract, }, #[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_role_assignment( operation_config: &crate::OperationConfig, request: &models::RoleAssignmentRequest, role_assignment_id: &str, ) -> std::result::Result<models::RoleAssignmentDetails, create_role_assignment::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleAssignments/{}", operation_config.base_path(), role_assignment_id); let mut url = url::Url::parse(url_str).map_err(create_role_assignment::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_role_assignment::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(request).map_err(create_role_assignment::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_role_assignment::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_role_assignment::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RoleAssignmentDetails = serde_json::from_slice(rsp_body) .map_err(|source| create_role_assignment::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| create_role_assignment::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_role_assignment::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_role_assignment { 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::ErrorContract, }, #[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_role_assignment_by_id( operation_config: &crate::OperationConfig, role_assignment_id: &str, scope: Option<&str>, ) -> std::result::Result<delete_role_assignment_by_id::Response, delete_role_assignment_by_id::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleAssignments/{}", operation_config.base_path(), role_assignment_id); let mut url = url::Url::parse(url_str).map_err(delete_role_assignment_by_id::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_role_assignment_by_id::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(scope) = scope { url.query_pairs_mut().append_pair("scope", scope); } 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_role_assignment_by_id::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_role_assignment_by_id::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => Ok(delete_role_assignment_by_id::Response::Ok200), http::StatusCode::NO_CONTENT => Ok(delete_role_assignment_by_id::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| delete_role_assignment_by_id::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_role_assignment_by_id::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_role_assignment_by_id { 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::ErrorContract, }, #[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 role_definitions { use super::{models, API_VERSION}; pub async fn list_role_definitions( operation_config: &crate::OperationConfig, is_built_in: Option<bool>, scope: Option<&str>, ) -> std::result::Result<models::RoleDefinitionsListResponse, list_role_definitions::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleDefinitions", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(list_role_definitions::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_role_definitions::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(is_built_in) = is_built_in { url.query_pairs_mut().append_pair("isBuiltIn", is_built_in.to_string().as_str()); } if let Some(scope) = scope { url.query_pairs_mut().append_pair("scope", scope); } 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_role_definitions::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_role_definitions::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::RoleDefinitionsListResponse = serde_json::from_slice(rsp_body) .map_err(|source| list_role_definitions::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| list_role_definitions::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_role_definitions::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_role_definitions { 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::ErrorContract, }, #[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_role_definition_by_id( operation_config: &crate::OperationConfig, role_definition_id: &str, ) -> std::result::Result<models::SynapseRoleDefinition, get_role_definition_by_id::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/roleDefinitions/{}", operation_config.base_path(), role_definition_id); let mut url = url::Url::parse(url_str).map_err(get_role_definition_by_id::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_role_definition_by_id::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_role_definition_by_id::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_role_definition_by_id::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::SynapseRoleDefinition = serde_json::from_slice(rsp_body) .map_err(|source| get_role_definition_by_id::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body) .map_err(|source| get_role_definition_by_id::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_role_definition_by_id::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_role_definition_by_id { 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::ErrorContract, }, #[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_scopes(operation_config: &crate::OperationConfig) -> std::result::Result<Vec<String>, list_scopes::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/rbacScopes", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(list_scopes::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_scopes::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_scopes::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_scopes::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: Vec<String> = serde_json::from_slice(rsp_body).map_err(|source| list_scopes::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::ErrorContract = serde_json::from_slice(rsp_body).map_err(|source| list_scopes::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_scopes::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_scopes { 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::ErrorContract, }, #[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), } } }
static FILENAME: &str = "input/data"; fn main() { let data = std::fs::read_to_string(FILENAME).expect("could not read file"); println!("part one: {}", part_one(&data)); } fn part_one(data: &str) -> usize { let pub_key_door = data.lines().next().unwrap().parse::<usize>().unwrap(); let pub_key_card = data.lines().nth(1).unwrap().parse::<usize>().unwrap(); let loop_size = determine_loop_size(pub_key_door); (0..loop_size).fold(1, |x, _| x * pub_key_card % 20201227) } fn determine_loop_size(pub_key: usize) -> usize { let mut x = 1; let mut loop_size = 0; let sub_no = 7; while x != pub_key { x = x * sub_no % 20201227; loop_size += 1; } loop_size } mod tests { #[test] fn test_part_one() { let data = std::fs::read_to_string(super::FILENAME).expect("could not read file"); assert_eq!(3015200, super::part_one(&data)); } }
use log::info; use std::fs::remove_dir_all; use std::fs::remove_file; use std::fs::create_dir_all; use std::io; use std::path::Path; pub fn ensure_clean_dir<P>(dir_path: P) where P: AsRef<Path> { let path = dir_path.as_ref(); match remove_dir_all(path) { Ok(_) => info!("removed dir: {}", path.display()), Err(_) => info!("unable to delete dir: {}", path.display()), } } pub fn ensure_new_dir<P>(path: P) -> Result<(),io::Error> where P: AsRef<Path> { let dir_path = path.as_ref(); ensure_clean_dir(dir_path); create_dir_all(dir_path) } // remove existing file pub fn ensure_clean_file<P>(path: P) where P: AsRef<Path> { let log_path = path.as_ref(); if let Ok(_) = remove_file(log_path) { info!("remove existing file: {}", log_path.display()); } else { info!("there was no existing file: {}", log_path.display()); } }
use crate::{ assets::level::{LevelAsset, LevelData, LevelObject}, components::{animal_kind::AnimalKind, item_kind::ItemKind}, states::menu::MenuState, ui::screens::gui::{GuiProps, GuiRemoteProps}, }; use oxygengine::{prelude::*, user_interface::raui::core::widget::WidgetId}; use std::str::FromStr; const CELL_SIZE: Scalar = 128.0; #[derive(Debug)] pub struct GameState { level_path: String, animal: AnimalKind, ready: bool, } impl GameState { pub fn new(level_path: String, animal: AnimalKind) -> Self { Self { level_path, animal, ready: false, } } fn initialize(&self, universe: &mut Universe) -> Result<bool, StateChange> { let hierarchy = universe.expect_resource::<Hierarchy>(); let camera = hierarchy.entity_by_name("camera"); let tiles = hierarchy.entity_by_name("tiles"); if let (Some(camera), Some(tiles)) = (camera, tiles) { let data = match self.load_level_data(universe) { Some(data) => data, None => return Err(StateChange::Swap(Box::new(MenuState))), }; if let Ok(mut transform) = universe .world() .query_one::<&mut CompositeTransform>(camera) { if let Some(transform) = transform.get() { transform.set_translation(Vec2::new( data.cols as Scalar * CELL_SIZE * 0.5, data.rows as Scalar * CELL_SIZE * 0.5, )); } } if let Ok(mut renderable) = universe .world() .query_one::<&mut CompositeRenderable>(tiles) { if let Some(renderable) = renderable.get() { renderable.0 = Renderable::Commands(data.build_render_commands(CELL_SIZE)); } } let token = universe .expect_resource::<AppLifeCycle>() .current_state_token(); for (index, cell) in data.cells.iter().enumerate() { let col = index % data.cols; let row = index / data.cols; match cell.object { LevelObject::Star => Self::create_item( &mut universe.world_mut(), col, row, ItemKind::Star, token, ), LevelObject::Shield => Self::create_item( &mut universe.world_mut(), col, row, ItemKind::Shield, token, ), LevelObject::PlayerStart => { Self::create_player(&mut universe.world_mut(), col, row, self.animal, token) } _ => {} } } if let Some(app) = universe .expect_resource_mut::<UserInterface>() .application_mut("gui") { let binding = GuiRemoteProps::new_bound( GuiProps { steps: 42, collected_stars: 2, collected_shields: 3, }, app.change_notifier(), ); app.send_message(&WidgetId::from_str("gui:gui").unwrap(), binding); } Ok(true) } else { Ok(false) } } fn load_level_data(&self, universe: &Universe) -> Option<LevelData> { let assets = universe.expect_resource::<AssetsDatabase>(); if let Some(asset) = assets.asset_by_path(&self.level_path) { if let Some(asset) = asset.get::<YamlAsset>() { if let Ok(asset) = asset.deserialize::<LevelAsset>() { match asset.build_data() { Ok(data) => return Some(data), Err(error) => oxygengine::error!( "* Level data can't be built from asset: {}\nError: {:?}", self.level_path, error ), } } else { oxygengine::error!("* Level asset can't be deserialized: {}", self.level_path); } } else { oxygengine::error!("* Level asset is not YAML: {}", self.level_path); } } else { oxygengine::error!("* Level asset is not loaded: {}", self.level_path); } None } fn create_item(world: &mut World, col: usize, row: usize, item: ItemKind, token: StateToken) { let image = item.build_image(CELL_SIZE); let x = (col as Scalar + 0.5) * CELL_SIZE; let y = (row as Scalar + 0.5) * CELL_SIZE; world.spawn(( Tag("world".into()), CompositeRenderable(image.into()), CompositeTransform::translation([x, y].into()), item, NonPersistent(token), )); } fn create_player( world: &mut World, col: usize, row: usize, animal: AnimalKind, token: StateToken, ) { let image = animal.build_image(CELL_SIZE); let x = (col as Scalar + 0.5) * CELL_SIZE; let y = (row as Scalar + 0.5) * CELL_SIZE; world.spawn(( Tag("world".into()), CompositeRenderable(image.into()), CompositeTransform::translation([x, y].into()), animal, NonPersistent(token), )); } } impl State for GameState { fn on_enter(&mut self, universe: &mut Universe) { self.ready = false; universe .expect_resource_mut::<PrefabManager>() .instantiate("level-scene", universe) .expect("Cannot instantiate level scene"); } fn on_process(&mut self, universe: &mut Universe) -> StateChange { if !self.ready { self.ready = match self.initialize(universe) { Ok(ready) => ready, Err(change) => return change, } } StateChange::None } }
use crate::html::{Attribute, EventListener, EventToMessage}; use std::default::Default; pub fn on_click<Msg: Clone + 'static>(message: Msg) -> Attribute<Msg> { Attribute::Event(EventListener { type_: "click".to_owned(), to_message: EventToMessage::StaticMsg(message), stop_propagation: false, prevent_default: false, js_closure: Default::default(), }) } // pub fn on_double_click<Msg: Clone + 'static>(message: Msg) -> Attribute<Msg> { // Attribute::Event(EventListener { // type_: "dblclick".to_owned(), // to_message: EventToMessage::StaticMsg(message), // stop_propagation: false, // prevent_default: false, // js_closure: Default::default(), // }) // } // pub fn on_blur<Msg: Clone + 'static>(message: Msg) -> Attribute<Msg> { // Attribute::Event(EventListener { // type_: "blur".to_owned(), // to_message: EventToMessage::StaticMsg(message), // stop_propagation: false, // prevent_default: false, // js_closure: Default::default(), // }) // } // // TODO: Ensure that when we start using animationFrame, on_input gets special treatement // pub fn on_input<Msg: 'static>(message: fn(String) -> Msg) -> Attribute<Msg> { // Attribute::Event(EventListener { // type_: "input".to_owned(), // to_message: EventToMessage::Input(message), // stop_propagation: true, // prevent_default: false, // js_closure: Default::default(), // }) // }
use tokio::sync::{mpsc, Mutex}; use std::{io, error::Error, net::SocketAddr}; use tokio::net::TcpStream; use super::super::utils::{Rx, Tx, Shared}; use std::sync::Arc; use tokio_util::codec::{Framed, LinesCodec}; pub struct Peer { name: String, pswd: String, lines: Framed<TcpStream, LinesCodec>, pub rx: Rx, } impl Peer { pub async fn new(name: String, pswd: String, state: Arc<Mutex<Shared>>, lines: Framed<TcpStream, LinesCodec>) -> io::Result<Peer> { let addr = lines.get_ref().peer_addr()?; //let addr = stream.peer_addr().expect("Failed to get socket address from that TCP stream"); let (tx, rx) = mpsc::unbounded_channel(); let ref_name = name.as_str(); { let mut state = state.lock().await; state.peers.insert(addr, tx); state.name.insert(ref_name.to_string(), addr); } Ok( Peer { name: ref_name.to_string(), pswd, lines, rx } ) } }
#[macro_use] mod macros; #[derive(Parser)] #[grammar = "parser/att.pest"] pub struct Parser; // impl AsmParser for AttParser { // fn parse_asm(s: &str) -> AsmProgram<'_> { // AttParser::parse(Rule::program, s) // .map(|pairs| { // pairs // .into_iter() // .flat_map(|pair| match pair.as_rule() { // Rule::EOI => None, // Rule::labeldecl => { // let ident = pair.into_inner().next().unwrap().as_str(); // Some(Line::from(Label::new(ident.to_string()))) // } // Rule::instruction => { // let mut inner = pair.into_inner(); // let opname = inner.next().unwrap().as_str(); // let args = inner.flat_map(|p| p.into_inner().next()).map(|pair| { // match pair.as_rule() { // Rule::register => { // let name = pair.into_inner().next().unwrap(); // Arg::Register(Register::new(name.as_str())) // } // Rule::literal => { // let digits = pair.into_inner().next().unwrap(); // let val = match digits.as_rule() { // Rule::hexnumber => { // usize::from_str_radix(digits.as_str(), 16).unwrap() // } // Rule::number => { // usize::from_str_radix(digits.as_str(), 10).unwrap() // } // _ => unreachable!(), // }; // Arg::Literal(Literal::new(val)) // } // Rule::label => { // let name = pair.into_inner().next().unwrap(); // Arg::Label(Label::new(name.as_str())) // } // _ => unreachable!(), // } // }); // Some(Line::from(Instruction::with_args(opname, args))) // } // _ => unreachable!(), // }) // .collect() // }) // .unwrap_or_else(|e| panic!("{}", e)) // } // }
use std::collections::HashMap; use nu_ansi_term::Style; use nu_protocol::{Config, FooterMode, TrimStrategy}; use tabled::{ builder::Builder, formatting_settings::AlignmentStrategy, object::{Cell, Columns, Rows, Segment}, papergrid, style::Color, Alignment, AlignmentHorizontal, Modify, ModifyObject, TableOption, Width, }; use crate::{table_theme::TableTheme, width_control::maybe_truncate_columns, StyledString}; /// Table represent a table view. #[derive(Debug)] pub struct Table { headers: Option<Vec<StyledString>>, data: Vec<Vec<StyledString>>, theme: TableTheme, } #[derive(Debug)] pub struct Alignments { data: AlignmentHorizontal, index: AlignmentHorizontal, header: AlignmentHorizontal, } impl Default for Alignments { fn default() -> Self { Self { data: AlignmentHorizontal::Center, index: AlignmentHorizontal::Right, header: AlignmentHorizontal::Center, } } } impl Table { /// Creates a [Table] instance. /// /// If `headers.is_empty` then no headers will be rendered. pub fn new( headers: Vec<StyledString>, data: Vec<Vec<StyledString>>, theme: TableTheme, ) -> Table { let headers = if headers.is_empty() { None } else { Some(headers) }; Table { headers, data, theme, } } /// Draws a trable on a String. /// /// It returns None in case where table cannot be fit to a terminal width. pub fn draw_table( &self, config: &Config, color_hm: &HashMap<String, Style>, alignments: Alignments, termwidth: usize, ) -> Option<String> { draw_table(self, config, color_hm, alignments, termwidth) } } fn draw_table( table: &Table, config: &Config, color_hm: &HashMap<String, Style>, alignments: Alignments, termwidth: usize, ) -> Option<String> { let mut headers = colorize_headers(table.headers.as_deref()); let mut data = colorize_data(&table.data, table.headers.as_ref().map_or(0, |h| h.len())); let count_columns = table_fix_lengths(headers.as_mut(), &mut data); let is_empty = maybe_truncate_columns(&mut headers, &mut data, count_columns, termwidth); if is_empty { return None; } let table_data = &table.data; let theme = &table.theme; let with_header = headers.is_some(); let with_footer = with_header && need_footer(config, data.len() as u64); let with_index = !config.disable_table_indexes; let table = build_table(data, headers, with_footer); let table = load_theme(table, color_hm, theme, with_footer, with_header); let table = align_table( table, alignments, with_index, with_header, with_footer, table_data, ); let table = table_trim_columns(table, termwidth, &config.trim_strategy); let table = print_table(table, config); if table_width(&table) > termwidth { None } else { Some(table) } } fn print_table(table: tabled::Table, config: &Config) -> String { let output = table.to_string(); // the atty is for when people do ls from vim, there should be no coloring there if !config.use_ansi_coloring || !atty::is(atty::Stream::Stdout) { // Draw the table without ansi colors match strip_ansi_escapes::strip(&output) { Ok(bytes) => String::from_utf8_lossy(&bytes).to_string(), Err(_) => output, // we did our best; so return at least something } } else { // Draw the table with ansi colors output } } fn table_width(table: &str) -> usize { table.lines().next().map_or(0, papergrid::string_width) } fn colorize_data(table_data: &[Vec<StyledString>], count_columns: usize) -> Vec<Vec<String>> { let mut data = vec![Vec::with_capacity(count_columns); table_data.len()]; for (row, row_data) in table_data.iter().enumerate() { for cell in row_data { let colored_text = cell .style .color_style .as_ref() .map(|color| color.paint(&cell.contents).to_string()) .unwrap_or_else(|| cell.contents.clone()); data[row].push(colored_text) } } data } fn colorize_headers(headers: Option<&[StyledString]>) -> Option<Vec<String>> { headers.map(|table_headers| { let mut headers = Vec::with_capacity(table_headers.len()); for cell in table_headers { let colored_text = cell .style .color_style .as_ref() .map(|color| color.paint(&cell.contents).to_string()) .unwrap_or_else(|| cell.contents.clone()); headers.push(colored_text) } headers }) } fn build_table( data: Vec<Vec<String>>, headers: Option<Vec<String>>, need_footer: bool, ) -> tabled::Table { let mut builder = Builder::from(data); if let Some(headers) = headers { builder.set_columns(headers.clone()); if need_footer { builder.add_record(headers); } } builder.build() } fn align_table( mut table: tabled::Table, alignments: Alignments, with_index: bool, with_header: bool, with_footer: bool, data: &[Vec<StyledString>], ) -> tabled::Table { table = table.with( Modify::new(Segment::all()) .with(Alignment::Horizontal(alignments.data)) .with(AlignmentStrategy::PerLine), ); if with_header { let alignment = Alignment::Horizontal(alignments.header); if with_footer { table = table.with(Modify::new(Rows::last()).with(alignment.clone())); } table = table.with(Modify::new(Rows::first()).with(alignment)); } if with_index { table = table.with(Modify::new(Columns::first()).with(Alignment::Horizontal(alignments.index))); } table = override_alignments(table, data, with_header, with_index, alignments); table } fn override_alignments( mut table: tabled::Table, data: &[Vec<StyledString>], header_present: bool, index_present: bool, alignments: Alignments, ) -> tabled::Table { let offset = if header_present { 1 } else { 0 }; for (row, rows) in data.iter().enumerate() { for (col, s) in rows.iter().enumerate() { if index_present && col == 0 && s.style.alignment == alignments.index { continue; } if s.style.alignment == alignments.data { continue; } table = table.with( Cell(row + offset, col) .modify() .with(Alignment::Horizontal(s.style.alignment)), ); } } table } fn load_theme( mut table: tabled::Table, color_hm: &HashMap<String, Style>, theme: &TableTheme, with_footer: bool, with_header: bool, ) -> tabled::Table { let mut theme = theme.theme.clone(); if !with_header { theme.set_lines(HashMap::default()); } table = table.with(theme); if let Some(color) = color_hm.get("separator") { let color = color.paint(" ").to_string(); if let Ok(color) = Color::try_from(color) { table = table.with(color); } } if with_footer { table = table.with(FooterStyle).with( Modify::new(Rows::last()) .with(Alignment::center()) .with(AlignmentStrategy::PerCell), ); } table } fn need_footer(config: &Config, count_records: u64) -> bool { matches!(config.footer_mode, FooterMode::RowCount(limit) if count_records > limit) || matches!(config.footer_mode, FooterMode::Always) } struct FooterStyle; impl TableOption for FooterStyle { fn change(&mut self, grid: &mut papergrid::Grid) { if grid.count_columns() == 0 || grid.count_rows() == 0 { return; } if let Some(line) = grid.clone().get_split_line(1) { grid.set_split_line(grid.count_rows() - 1, line.clone()); } } } fn table_trim_columns( table: tabled::Table, termwidth: usize, trim_strategy: &TrimStrategy, ) -> tabled::Table { table.with(&TrimStrategyModifier { termwidth, trim_strategy, }) } pub struct TrimStrategyModifier<'a> { termwidth: usize, trim_strategy: &'a TrimStrategy, } impl tabled::TableOption for &TrimStrategyModifier<'_> { fn change(&mut self, grid: &mut papergrid::Grid) { match self.trim_strategy { TrimStrategy::Wrap { try_to_keep_words } => { let mut w = Width::wrap(self.termwidth).priority::<tabled::width::PriorityMax>(); if *try_to_keep_words { w = w.keep_words(); } w.change(grid) } TrimStrategy::Truncate { suffix } => { let mut w = Width::truncate(self.termwidth).priority::<tabled::width::PriorityMax>(); if let Some(suffix) = suffix { w = w.suffix(suffix).suffix_try_color(true); } w.change(grid); } }; } } fn table_fix_lengths(headers: Option<&mut Vec<String>>, data: &mut [Vec<String>]) -> usize { let length = table_find_max_length(headers.as_deref(), data); if let Some(headers) = headers { headers.extend(std::iter::repeat(String::default()).take(length - headers.len())); } for row in data { row.extend(std::iter::repeat(String::default()).take(length - row.len())); } length } fn table_find_max_length<T>(headers: Option<&Vec<T>>, data: &[Vec<T>]) -> usize { let mut length = headers.map_or(0, |h| h.len()); for row in data { length = std::cmp::max(length, row.len()); } length }
//! rust-saber allows writing mods for the Oculus Quest version of Beat Saber in //! Rust. //! //! # Examples //! ```rust,no_run //! #[repr(C)] //! #[derive(Default)] //! pub struct Color { //! pub r: f32, //! pub g: f32, //! pub b: f32, //! pub a: f32, //! } //! //! #[rust_saber::hook(0x12DC59C, "example")] //! pub unsafe fn get_color(orig: GetColorFn, this: *mut std::ffi::c_void) -> Color { //! let orig_color = unsafe { orig(this) }; //! Color { //! r: 1.0, //! g: orig_color.g, //! b: orig_color.b, //! a: orig_color.a, //! } //! } //! ``` //! //! The full version of this example can be found at //! <https://github.com/leo60228/rust-saber/tree/master/sample_mod>. use lazy_static::lazy_static; use log::*; use std::env; use std::ffi::CString; use std::sync::Once; #[doc(inline)] pub use rust_saber_macros::hook; static INIT: Once = Once::new(); /// This must be called once with the name of your mod by your program for /// rust-saber to work properly. Currently, this is called automatically by /// every hook. In the future, there may be more specific guarantees about what /// happens when this is not called. pub fn init_once(name: &'static str) { INIT.call_once(move || { #[cfg(target_os = "android")] android_logger::init_once( android_logger::Config::default() .with_tag(name) .with_min_level(Level::Trace), ); env::set_var("RUST_BACKTRACE", "1"); log_panics::init(); info!("{} initialized!", name); }); } lazy_static! { static ref BASE_ADDR: u64 = base_addr("/data/app/com.beatgames.beatsaber-1/lib/arm/libil2cpp.so"); } /// Get the base address of any .so file loaded into the current process. /// /// # Examples /// ```rust,no_run /// # use lazy_static::lazy_static; /// lazy_static! { /// static ref BASE_ADDR: u64 = base_addr("/data/app/com.beatgames.beatsaber-1/lib/arm/libil2cpp.so"); /// } /// ``` /// /// # Panics /// This function will panic if the .so is not loaded. pub fn base_addr(so_path: &str) -> u64 { let cstring = CString::new(so_path).unwrap(); let handle = unsafe { libc::dlopen(cstring.as_ptr(), libc::RTLD_LOCAL | libc::RTLD_LAZY) }; if handle.is_null() { 0 } else { let maps = proc_maps::get_process_maps(unsafe { libc::getpid() }).unwrap(); let map = maps .iter() .find(|e| { e.filename() .as_ref() .map(|e| e.ends_with(so_path)) .unwrap_or(false) }) .expect("Can't find base address in mappings!"); map.start() as u64 } } /// Get an address relative to libil2cpp.so. pub fn bs_offset(offset: u32) -> u64 { *BASE_ADDR + (offset as u64) } #[repr(C)] #[allow(dead_code)] enum Ele7enStatus { ErrorUnknown = -1, Ok = 0, ErrorNotInitialized, ErrorNotExecutable, ErrorNotRegistered, ErrorNotHooked, ErrorAlreadyRegistered, ErrorAlreadyHooked, ErrorSoNotFound, ErrorFunctionNotFound, } #[cfg(target_os = "android")] extern "C" { fn registerInlineHook(target: u32, new: u32, orig: *mut *mut u32) -> Ele7enStatus; fn inlineHook(target: u32) -> Ele7enStatus; } /// Hook the function at addr, using the function at func as a replacement. This /// should not be used directly, use the hook attribute instead. /// /// # Unsafety /// This can cause unsafety if either function is not a valid address, or if /// they have different signatures. pub unsafe fn hook(func: u32, addr: u32) -> *mut () { trace!("0x{:x} -> 0x{:x}", addr, func); let mut ptr: *mut u32 = std::ptr::null_mut(); let offset = bs_offset(addr) as u32; #[cfg(target_os = "android")] registerInlineHook(offset, func, &mut ptr as *mut *mut u32); #[cfg(target_os = "android")] inlineHook(offset); ptr as *mut () }
use std::path::PathBuf; use chrono::{DateTime, NaiveTime, Utc}; use include_dir::File; use markdown::{ mdast::{Node, Root}, to_mdast, ParseOptions, }; use miette::{Context, IntoDiagnostic, Result}; use serde::Deserialize; use crate::{ http_server::pages::blog::md::{IntoHtml, IntoPlainText}, AppState, }; use self::{ blog::{LinkTo, PostMarkdown}, date::PostedOn, title::Title, }; pub(crate) mod blog; pub(crate) mod til; pub(crate) mod date; pub(crate) mod title; #[derive(Debug, Clone)] pub(crate) struct Post<FrontmatterType> { pub(crate) frontmatter: FrontmatterType, pub(crate) ast: MarkdownAst, pub(crate) path: PathBuf, } #[derive(Clone, Debug)] pub struct MarkdownAst(pub(crate) Root); impl MarkdownAst { pub fn from_file(file: &File) -> Result<Self> { let contents = file.contents(); let contents = std::str::from_utf8(contents) .into_diagnostic() .wrap_err("File is not UTF8")?; Self::from_str(contents) } pub fn from_str(contents: &str) -> Result<Self> { let mut options: ParseOptions = Default::default(); options.constructs.gfm_footnote_definition = true; options.constructs.frontmatter = true; match to_mdast(contents, &options) { Ok(Node::Root(ast)) => Ok(Self(ast)), Ok(_) => Err(miette::miette!("Should be a root node")), Err(e) => Err(miette::miette!("Could not make AST. Inner Error: {}", e)), } } fn frontmatter_yml(&self) -> Result<&str> { let children = &self.0.children; let Some(Node::Yaml(frontmatter)) = children.get(0) else { return Err(miette::miette!("Should have a first child with YAML Frontmatter")) }; Ok(&frontmatter.value) } pub fn frontmatter<T>(&self) -> Result<T> where T: for<'de> Deserialize<'de>, { let yaml = self.frontmatter_yml()?; serde_yaml::from_str(yaml) .into_diagnostic() .wrap_err("Frontmatter should be valid YAML") } } impl IntoHtml for MarkdownAst { fn into_html(self, state: &AppState) -> maud::Markup { self.0.into_html(state) } } impl<FrontMatter> Post<FrontMatter> { fn short_description(&self) -> Option<String> { let contents = self.ast.0.plain_text(); Some(contents.chars().take(100).collect()) } } pub(crate) trait ToRssItem { fn to_rss_item(&self, state: &AppState) -> rss::Item; } impl<FrontMatter> ToRssItem for Post<FrontMatter> where FrontMatter: PostedOn + Title, Post<FrontMatter>: LinkTo, { fn to_rss_item(&self, state: &AppState) -> rss::Item { let link = self.absolute_link(&state.app); let posted_on: DateTime<Utc> = self.posted_on().and_time(NaiveTime::MIN).and_utc(); let formatted_date = posted_on.to_rfc2822(); rss::ItemBuilder::default() .title(Some(self.title().to_string())) .link(Some(link)) .description(self.short_description()) .pub_date(Some(formatted_date)) .content(Some(self.markdown().ast.0.into_html(state).into_string())) .build() } } impl<FrontMatter> Post<FrontMatter> where FrontMatter: PostedOn + Title, { pub(crate) fn markdown(&self) -> PostMarkdown { PostMarkdown { title: self.title().to_string(), date: self.posted_on().to_string(), ast: self.ast.clone(), } } }
pub mod caves; pub mod cities; pub mod misc; pub mod routes; use std::collections::HashMap; #[derive(Clone)] pub struct Location<'a> { boundaries: Vec<Coordinates>, entries: HashMap<u8, Coordinates>, pub motto: Option<&'a str>, pub name: Option<&'a str>, portals: HashMap<Coordinates, Portal>, pub sprite: &'a str, } impl<'a> Location<'a> { pub fn within_boundaries(self, position: Coordinates) -> bool { // Assume by default that it is within the boundaries. let mut within = true; for boundary in &self.boundaries { if boundary.x == position.x && boundary.y == position.y { within = false; break; } } within } pub fn get_entry_coords_by_id<'g>(&'g self, id: u8) -> Option<&'g Coordinates> { self.entries.get(&id) } pub fn get_portal_by_coordinates(&self, coords: Coordinates) -> Option<&Portal> { match self.portals.get(&c![coords.x, coords.y]) { Some(portal) => Some(portal), None => None } } } // The Eq, Hash, and PartialEq traits must be derived to be used in HashMap // indexes. #[derive(Clone, Eq, Hash, PartialEq, RustcDecodable, RustcEncodable)] pub struct Coordinates { pub x: u16, pub y: u16, } impl Coordinates { pub fn new(x: u16, y: u16) -> Coordinates { Coordinates { x: x, y: y, } } pub fn pair(self) -> (u16, u16) { (self.x, self.y) } } #[derive(Clone)] pub struct Portal { pub entry_id: u8, pub location_id: u16, } impl Portal { pub fn new(entry_id: u8, location_id: u16) -> Portal { Portal { entry_id: entry_id, location_id: location_id, } } } /// Compiled list of locations: /// /// - 0000: cities::littleroot_town::primary /// - 0001: cities::littleroot_town::laboratory /// - 0002: cities::littleroot_town::left_house_f1 /// - 0003: cities::littleroot_town::right_house_f1 /// - 0004: cities::littleroot_town::left_house_f2 /// - 0005: cities::littleroot_town::right_house_f2 pub fn all<'a>() -> HashMap<u16, Location<'a>> { let mut locations: HashMap<u16, Location> = HashMap::new(); for (key, val) in cities::all().iter() { locations.insert(key.clone(), val.clone()); } locations } pub fn get_by_id<'a>(id: u16) -> Option<Location<'a>> { let all = &all(); match all.get(&id) { Some(location) => Some(location.clone()), None => None, } }
////// chapter 3 "using functions and control structures" ////// program section: ////// main function // fn main() { let dead = false; let health = 48; if dead { println!("game over!"); return; } else { println!("prepare to fight!"); } if health >= 50 { println!("continue to fight!"); } else if health >= 20 { println!("stop the battle and gain strength!"); } else { println!("hide and try to recover!"); } }
use core::fmt::Debug; use downcast_rs::{Downcast, impl_downcast}; use crate::types::{Vec3, Mat3, EntityHandle}; /// A way to quickly determine collider type. #[derive(PartialEq, Eq)] pub enum ColliderType { /// For the [crate::NullCollider]. NULL, /// For the [crate::SphereCollider]. SPHERE, /// For the [crate::PlaneCollider]. PLANE, /// For the [crate::MeshCollider]. MESH, /// For the [crate::AlignedBox]. ALIGNED_BOX, } /// The internal representation of an arbitrary collider. /// This generally will have NO data hiding to keep things simple. pub trait InternalCollider : Downcast + Debug { /// The specific type. fn get_type(&self) -> ColliderType; /// Sets the entity this is attached to. fn set_entity(&mut self, handle : Option<EntityHandle>) -> Option<EntityHandle>; /// Retrieves the stored entity handle that this is attached to. fn get_entity(&mut self) -> Option<EntityHandle>; /// Gets the center of mass for this collider in it's owning entity's local space. fn get_local_center_of_mass(&self) -> Vec3; /// Gets the mass of this collider. Must not be negative. fn get_mass(&self) -> f32; /// Gets the moment of inertia tensor about the center of mass. /// /// This is oriented according to the owning entity's local space. fn get_moment_of_inertia_tensor(&self) -> Mat3; /// Gets the coefficient of restitution for this instance. fn get_restitution_coefficient(&self) -> f32; /// Gets the friction ratio threshold used to decide whether to use static or dynamic friction. fn get_friction_threshold(&self) -> f32; /// Gets the static friction coefficient. fn get_static_friction_coefficient(&self) -> f32; /// Gets the dynamic friction coefficient. fn get_dynamic_friction_coefficient(&self) -> f32; } impl dyn InternalCollider { // Nothing for now. } impl_downcast!(InternalCollider); /// The generic public representation of an arbitrary collider. pub trait Collider : Downcast + Debug { /// The specific type. fn get_type(&self) -> ColliderType; /// Gets the entity this is linked to (if there is one). /// /// This is read-only. To link things together, use PhysicsSystem.link_collider(). fn get_entity(&self) -> Option<EntityHandle>; /// Gets the center of mass for this collider in it's owning entity's local space. fn get_center_of_mass(&self) -> Vec3; } impl dyn Collider { // Nothing for now. } impl_downcast!(Collider);
use super::Messages; use common::async_trait::async_trait; use models::{server::UdpTuple, transport::TransportMsg}; use sip_server::{Error, SipManager, TransportLayer}; use std::any::Any; use std::sync::{Arc, Weak}; use tokio::sync::Mutex; #[derive(Debug)] pub struct TransportSnitch { sip_manager: Weak<SipManager>, pub messages: Messages, } #[async_trait] impl TransportLayer for TransportSnitch { fn new(sip_manager: Weak<SipManager>) -> Result<Self, Error> { Ok(Self { sip_manager: sip_manager.clone(), messages: Default::default(), }) } async fn process_incoming_message(&self, _: UdpTuple) -> Result<(), Error> { Ok(()) } async fn send(&self, msg: TransportMsg) -> Result<(), Error> { self.messages.push(msg).await; Ok(()) } async fn run(&self) {} fn as_any(&self) -> &dyn Any { self } } #[derive(Debug)] pub struct TransportErrorSnitch { sip_manager: Weak<SipManager>, fail_switch: Mutex<bool>, pub messages: Messages, } #[async_trait] impl TransportLayer for TransportErrorSnitch { fn new(sip_manager: Weak<SipManager>) -> Result<Self, Error> { Ok(Self { sip_manager: sip_manager.clone(), fail_switch: Mutex::new(true), messages: Default::default(), }) } async fn process_incoming_message(&self, _: UdpTuple) -> Result<(), Error> { match *self.fail_switch.lock().await { true => Err("this is just a snitch".into()), false => Ok(()), } } async fn send(&self, msg: TransportMsg) -> Result<(), Error> { match *self.fail_switch.lock().await { true => Err("this is just a snitch".into()), false => { self.messages.push(msg).await; Ok(()) } } } async fn run(&self) {} fn as_any(&self) -> &dyn Any { self } } impl TransportErrorSnitch { pub async fn turn_fail_switch_off(&self) { let mut switch = self.fail_switch.lock().await; *switch = false; } pub async fn turn_fail_switch_on(&self) { let mut switch = self.fail_switch.lock().await; *switch = true; } } #[derive(Debug)] pub struct TransportPanic; #[async_trait] impl TransportLayer for TransportPanic { fn new(sip_manager: Weak<SipManager>) -> Result<Self, Error> { Ok(Self) } async fn process_incoming_message(&self, _: UdpTuple) -> Result<(), Error> { p!(self) } async fn send(&self, msg: TransportMsg) -> Result<(), Error> { p!(self) } async fn run(&self) {} fn as_any(&self) -> &dyn Any { self } }
#[doc = "Reader of register RXOICR"] pub type R = crate::R<u32, super::RXOICR>; #[doc = "Reader of field `RXOICR`"] pub type RXOICR_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - Clear-on-read receive FIFO overflow interrupt"] #[inline(always)] pub fn rxoicr(&self) -> RXOICR_R { RXOICR_R::new((self.bits & 0x01) != 0) } }
/** All Windows C API Interface Binding Here. **/ /** <summary>Cursor Functions</summary> **/ pub mod Cursor; /** <summary>Device Context Functions</summary> **/ pub mod DeviceContext; /** <summary>Dialog Box Functions</summary> **/ pub mod DialogBox; /** <summary>Dynamic-Link Library Functions</summary> **/ pub mod DLL; /** <summary>Icon Functions</summary> **/ pub mod Icon; /** <summary>Message Functions</summary> **/ pub mod Message; /** <summary>Multimedia Functions</summary> **/ pub mod Multimedia; /** <summary>Window Functions</summary> **/ pub mod Window; /** <summary>Window Class Functions</summary> **/ pub mod WindowClass; /** <summary>Window Procedure Functions</summary> **/ pub mod WindowProcedure;
use { crate::Error, std::{convert::TryFrom, fmt}, }; #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Schema<'a> { pub items: Vec<Item<'a>>, } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Item<'a> { Enum(Enum<'a>), Table(Table<'a>), } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Enum<'a> { pub name: &'a str, pub not_exists: bool, pub variants: Vec<&'a str>, } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Table<'a> { pub name: &'a str, pub not_exists: bool, pub columns: Vec<Column<'a>>, pub primary_keys: Vec<&'a str>, pub foreign_keys: Vec<ForeignKey<'a>>, pub unique_keys: Vec<&'a str>, } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct Column<'a> { pub name: &'a str, pub typ: Types<'a>, pub null: bool, pub default: ColumnDefault<'a>, } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Types<'a> { Boolean, // Text Char, Varchar, Text, // Numbers Number, SmallInt, MediumInt, BigInt, Int, Serial, // Floats Float, Real, Numeric, Decimal, // Date/Time DateTime, Raw(&'a str), } impl<'a> Types<'a> { pub(crate) fn from_str(s: &str) -> Types<'_> { match s { "bigInt" => Types::BigInt, "bool" | "boolean" => Types::Boolean, "char" => Types::Char, "dateTime" => Types::DateTime, "decimal" => Types::Decimal, "float" => Types::Float, "int" => Types::Int, "mediumInt" => Types::MediumInt, "number" => Types::Number, "numeric" => Types::Numeric, "real" => Types::Real, "serial" => Types::Serial, "smallInt" => Types::SmallInt, "text" => Types::Text, "varchar" => Types::Varchar, t => Types::Raw(t), } } } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum ColumnDefault<'a> { None, Now, Null, Raw(&'a str), } impl<'a> Default for ColumnDefault<'a> { fn default() -> Self { ColumnDefault::None } } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub struct ForeignKey<'a> { pub local: &'a str, pub table: &'a str, pub foreign: &'a str, pub delete: Action, pub update: Action, } #[derive(Clone, Debug, Hash, PartialOrd, Ord, PartialEq, Eq)] pub enum Action { NoAction, Restrict, SetNull, SetDefault, Cascade, } impl Default for Action { fn default() -> Self { Action::NoAction } } impl<'s> TryFrom<&'s str> for Action { type Error = Error; fn try_from(value: &'s str) -> Result<Self, Self::Error> { match value { "no action" => Ok(Action::NoAction), "restrict" => Ok(Action::Restrict), "set null" => Ok(Action::SetNull), "set default" => Ok(Action::SetDefault), "cascade" => Ok(Action::Cascade), t => Err(Error::InvalidAction(t.to_string())), } } } impl fmt::Display for Action { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { Action::NoAction => "NO ACTION", Action::Restrict => "RESTRICT", Action::SetNull => "SET NULL", Action::SetDefault => "SET DEFAULT", Action::Cascade => "CASCADE", } )?; Ok(()) } } pub(crate) struct ColumnPartial<'a> { pub name: &'a str, pub typ: Types<'a>, pub null: bool, } pub(crate) enum Modifier<'p> { Default { value: &'p str, }, DefaultDateTime, DefaultNull, PrimaryKey, Reference { table: &'p str, column: &'p str, delete: Action, update: Action, }, Unique, }
use super::Filter; use crate::economy::Monetary; use binance_async::model::OrderRequest; pub struct PriceFilter { min_price: Monetary, max_price: Monetary, tick_size: Monetary } impl Filter for PriceFilter { fn apply(&self, mut input: OrderRequest) -> Result<OrderRequest, ()> { if input.price < self.min_price { return Err(()); } if input.price > self.max_price { return Err(()); } input.price = self.min_price + ((input.price - self.min_price) / self.tick_size).round() * self.tick_size; debug_assert!((input.price - self.min_price) % self.tick_size == 0.0); Ok(input) } }
// TODO: Are we able to convert Html<A> to Html<B>? use std::any::Any; use std::cell::RefCell; use std::cmp::PartialEq; use std::fmt::{self, Debug}; use std::rc::Rc; #[derive(Clone, Debug)] pub struct HtmlTag<Msg> { pub tag: String, pub attrs: Vec<Attribute<Msg>>, pub children: Vec<Html<Msg>>, } impl<Msg> HtmlTag<Msg> { pub fn key(&self) -> Option<&str> { for attr in &self.attrs { if let Attribute::Key(ref key) = attr { return Some(key); } } None } } #[derive(Clone, Debug)] pub enum Html<Msg> { Tag(HtmlTag<Msg>), Text(String), } impl<Msg> HtmlTag<Msg> { pub fn to_html_text(&self, indent: u32) -> String { let indent_s = " ".repeat(indent as usize); if self.children.is_empty() { return format!("{}<{} />", indent_s, self.tag); } let children = self .children .iter() .map(|child| child.to_html_text(indent + 1)) .collect::<Vec<_>>() .join("\n");; format!( "{}<{}>\n{}\n{}</{}>", indent_s, self.tag, children, indent_s, self.tag, ) } } impl<Msg> Html<Msg> { pub fn to_html_text(&self, indent: u32) -> String { let indent_s = " ".repeat(indent as usize); match self { Html::Text(text) => format!("{}{}", indent_s, text), Html::Tag(tag) => tag.to_html_text(indent), } } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum PropertyValue { String(String), Bool(bool), } #[derive(Clone, Default)] pub struct JsClosure(pub Rc<RefCell<Option<wasm_bindgen::closure::Closure<Fn(web_sys::Event)>>>>); impl Debug for JsClosure { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.0.borrow().is_some() { write!(f, "HAS A CLOSURE") } else { write!(f, "NO CLOSURE") } } } impl PartialEq for JsClosure { fn eq(&self, _: &JsClosure) -> bool { // This is not good enough to implent Eq, i think // And its a bit weird. But it's to ignore this in the Attribute enum true } } #[derive(Clone, Debug, PartialEq)] pub enum Attribute<Msg> { // Event where the message depends on the event data Event { js_closure: JsClosure, type_: String, stop_propagation: bool, prevent_default: bool, to_message: EventToMessage<Msg>, }, // TODO: Value should be JsValue or something like that, not String Property(&'static str, PropertyValue), Style(String, String), Key(String), } impl<Msg> Attribute<Msg> { pub fn is_event(&self) -> bool { match self { Attribute::Event { .. } => true, _ => false, } } /// Panics if self is not an event pub fn get_js_closure(&self) -> JsClosure { match self { Attribute::Event { js_closure, .. } => js_closure.clone(), _ => panic!("get_js_closure called with something that is not an event"), } } /// Panics if self is not an event pub fn set_js_closure(&self, closure: wasm_bindgen::closure::Closure<Fn(web_sys::Event)>) { match self { Attribute::Event { js_closure, .. } => { let ret = js_closure.0.replace(Some(closure)); if ret.is_some() { console_log!("set_js_closure called, but event did already have a closure???"); } } _ => panic!("set_js_closure called with something that is not an event"), } } } pub trait EventClosure<Input, Msg>: Debug { fn call_ish(&self, input: Input) -> Msg; fn eq_rc(&self, other: &Rc<EventClosure<Input, Msg>>) -> bool; } #[derive(Debug)] pub struct EventClosureImpl<Input, Data, Msg> { data: Data, func: fn(Data, Input) -> Msg, } impl<Input, Data, Msg> EventClosureImpl<Input, Data, Msg> { pub fn new(data: Data, func: fn(Data, Input) -> Msg) -> Self { Self { data, func } } } impl<Input: Debug + 'static, Data: PartialEq + Debug + Clone + 'static, Msg: Debug + 'static> EventClosure<Input, Msg> for EventClosureImpl<Input, Data, Msg> { fn call_ish(&self, input: Input) -> Msg { (self.func)(self.data.clone(), input) } fn eq_rc(&self, other: &Rc<EventClosure<Input, Msg>>) -> bool { let other = other as &Any; if let Some(other_down) = other.downcast_ref::<EventClosureImpl<Input, Data, Msg>>() { self.data == other_down.data && self.func == other_down.func } else { false } } } #[derive(Clone, Debug)] pub struct RcEventClosure<Input, Msg>(pub Rc<EventClosure<Input, Msg>>); impl<Input, Msg> PartialEq for RcEventClosure<Input, Msg> { fn eq(&self, other: &RcEventClosure<Input, Msg>) -> bool { self.0.eq_rc(&other.0) } } #[derive(Clone, Debug, PartialEq)] pub enum EventToMessage<Msg> { StaticMsg(Msg), Input(fn(String) -> Msg), InputWithClosure(RcEventClosure<String, Msg>), WithFilter { msg: Msg, filter: fn(web_sys::Event) -> bool, }, } macro_rules! create_node { ($x:ident) => { pub fn $x<Msg: Clone>(attrs: &[Attribute<Msg>], children: &[Html<Msg>]) -> Html<Msg> { Html::Tag(HtmlTag { tag: stringify!($x).to_owned(), children: children.to_vec(), attrs: attrs.to_vec(), }) } }; } create_node!(div); create_node!(button); create_node!(section); create_node!(header); create_node!(h1); create_node!(h2); create_node!(h3); create_node!(h4); create_node!(input); create_node!(label); create_node!(ul); create_node!(li); create_node!(footer); create_node!(span); create_node!(strong); create_node!(a); create_node!(p); pub fn text<Msg>(inner: &str) -> Html<Msg> { Html::Text(inner.to_owned()) }
//! Responsible for drawing all graphics to the window. use graphics::character::CharacterCache; use graphics::color::hex; use graphics::types::Color; use graphics::{Context, Graphics}; use rand::seq::SliceRandom; use crate::common::{ ButtonInteraction, Cell, BOARD_SIZE, DIMENSIONS_CHOICES, IMAGE_NAMES, IMAGE_PRE, }; use crate::NonogramController; #[derive(Default)] /// Stores nonogram view settings. pub struct NonogramViewSettings { /// X and Y coordinates of nonogram board relative to top left corner of the window. pub position: [f64; 2], /// Overall size value of nonogram board. This ends up being used in an equation which determines /// the width and height of the board based on how many rows and columns it has. pub size: f64, /// [width, height] of nonogram board. pub board_dimensions: [f64; 2], /// [columns, rows] in nonogram board. pub cell_dimensions: [usize; 2], /// Both the width and height of a single cell in the nonogram board. pub cell_size: f64, /// [width, height] of nonogram board when displayed during win screen. pub win_board_dimensions: [f64; 2], /// Both the width and height of a single cell in the nonogram board displayed during win screen. pub win_cell_size: f64, /// Nonogram board color. Determines color of unfilled cell in nonogram board. pub background_color: Color, /// Color of overall nonogram board edge. pub board_edge_color: Color, /// Color of edges separating every 5 cells in nonogram board. pub section_edge_color: Color, /// Color of individual nonogram board cell edge. pub cell_edge_color: Color, /// Thickness of nonogram board edge. pub board_edge_radius: f64, /// Thickness of edges separating every 5 cells in nonogram board. pub section_edge_radius: f64, /// Thickness of edges of each individual board cell. pub cell_edge_radius: f64, /// Edge color of selected board cell. pub selected_cell_border_color: Color, /// Round radius of selected board cell's edge. pub selected_cell_border_round_radius: f64, /// Radius of selected cell's edge. pub selected_cell_border_radius: f64, /// Background color of filled cell. pub filled_cell_background_color: Color, /// Background color of marked cell. pub marked_cell_background_color: Color, /// General color of basically all text in the game. pub text_color: Color, /// Location and size of unselected dimensions dropdown menu box. /// /// Format: [x, y, width, height] pub dimensions_dropdown_menu_box: [f64; 4], /// Location and size of selected dimensions dropdown menu box. /// /// Format: [x, y, width, height] pub dimensions_dropdown_menu_select_background: [f64; 4], /// Location and size of win stats box. /// /// Format: [x, y, width, height] pub win_box_rect: [f64; 4], /// Location and size of restart button in main game screen. /// /// Format: [x, y, width, height] pub restart_box: [f64; 4], /// Location and size of new game button on win screen. /// /// Format: [x, y, width, height] pub new_game_box: [f64; 4], /// Randomly generated win critique of user's winning game board. pub win_critique: String, } /// Implementation for NonogramViewSettings. impl NonogramViewSettings { /// Creates new nonogram view settings. pub fn new(new_cell_dimensions: [usize; 2]) -> NonogramViewSettings { let mut view_settings = NonogramViewSettings { position: [300.0, 240.0], size: BOARD_SIZE, board_dimensions: [0.0; 2], cell_dimensions: [new_cell_dimensions[0], new_cell_dimensions[1]], cell_size: 0.0, win_board_dimensions: [0.0, 240.0], win_cell_size: 0.0, background_color: hex("f7f5f6"), board_edge_color: hex("cccccc"), section_edge_color: hex("34af4a"), cell_edge_color: hex("cccccc"), board_edge_radius: 2.0, section_edge_radius: 2.0, cell_edge_radius: 2.0, selected_cell_border_color: hex("5adbfd"), selected_cell_border_round_radius: 2.0, selected_cell_border_radius: 2.0, filled_cell_background_color: hex("353235"), marked_cell_background_color: hex("f77b00"), text_color: hex("ffffff"), dimensions_dropdown_menu_box: [300.0, 10.0, 100.0, 30.0], dimensions_dropdown_menu_select_background: [0.0; 4], win_box_rect: [600.0, 500.0, 250.0, 200.0], restart_box: [450.0, 10.0, 100.0, 30.0], new_game_box: [450.0, 10.0, 100.0, 30.0], win_critique: "".to_string(), }; view_settings.init_new(); view_settings } /// Only called when a new `NonogramViewSettings` object is created. /// Responsible for initializing all variables that couldn't be initialized in `new()`. fn init_new(&mut self) { // Because the dimensions of the board can vary, we need to initialize the locations of cells based on these dimensions // and the size of the board which is set by the BOARD_SIZE const in common.rs. let cols = self.cell_dimensions[0] as f64; let rows = self.cell_dimensions[1] as f64; self.board_dimensions[0] = (cols / (cols + rows)) * self.size; self.board_dimensions[1] = (rows / (cols + rows)) * self.size; self.cell_size = self.board_dimensions[0] / cols; // A random string that's displayed near an image of the final board upon winning. // Ends up saying something like, "That looks just like Abraham Lincoln!". // // Makes fun of the fact that my version of the nonogram board game uses randomly generated // boards rather than ones that actually form images of things. if let Some(critique_1) = IMAGE_PRE.choose(&mut rand::thread_rng()) { if let Some(critique_2) = IMAGE_NAMES.choose(&mut rand::thread_rng()) { self.win_critique = format!("{} {}{}", critique_1[0], critique_2, critique_1[1]); } } // The board size when it's displayed during the end game screen needs to be a certain height in order to not end up // overlapping the stats box. Everything else from the width of the board to the size of the cells needs to be based around // this maximum height. self.win_cell_size = self.win_board_dimensions[1] / rows; self.win_board_dimensions[0] = self.win_cell_size * cols; // Win box containing stats is center-aligned. self.win_box_rect[0] -= self.win_box_rect[2] / 2.0; self.win_box_rect[1] -= self.win_box_rect[3] / 2.0; // New game box / button at the bottom of the win box is center aligned and located at the very bottom of the win box. self.new_game_box[2] = self.win_box_rect[2]; self.new_game_box[0] = self.win_box_rect[0] + (self.win_box_rect[2] / 2.0) - (self.new_game_box[2] / 2.0); self.new_game_box[1] = self.win_box_rect[1] + self.win_box_rect[3] - self.new_game_box[3]; // Setup dimensions dropdown menu stuff. self.dimensions_dropdown_menu_select_background = self.dimensions_dropdown_menu_box; self.dimensions_dropdown_menu_select_background[3] *= (DIMENSIONS_CHOICES.len() + 3) as f64; } } /// Stores visual information about a nonogram. pub struct NonogramView { /// Stores nonogram view settings. pub settings: NonogramViewSettings, } /// `NonogramView` functionality. impl NonogramView { /// Creates a new nonogram view. pub fn new(settings: NonogramViewSettings) -> NonogramView { NonogramView { settings } } /// Draw everything in the game. /// /// This ends up being responsible for the main game screen's contents or the win screen's contents /// based on the value for `controller.nonogram.end_game_screen`. #[allow(clippy::cognitive_complexity)] pub fn draw<G: Graphics, C>( &self, controller: &NonogramController, glyphs: &mut C, mark_glyphs: &mut C, material_icons_glyphs: &mut C, c: &Context, g: &mut G, ) where C: CharacterCache<Texture = G::Texture>, { use graphics::text::Text; use graphics::{Line, Rectangle, Transformed}; let settings = &self.settings; let total_seconds = controller.nonogram.duration.as_secs(); let total_mins = total_seconds / 60; let total_hrs = total_mins / 60; let rem_seconds = total_seconds - total_mins * 60; let rem_mins = total_mins - total_hrs * 60; // Draw a large transparent rectangle over window. // Last two digits in hex refer to transparency: https://css-tricks.com/8-digit-hex-codes/ // Rectangle::new(hex("000000E6")).draw(window_rect, &c.draw_state, c.transform, g); // Draw win screen. if controller.nonogram.end_game_screen { //if true { Rectangle::new_round(hex("333333"), 10.0).draw( settings.win_box_rect, &c.draw_state, c.transform, g, ); // Randomly generated artist critique of player's winning image. let critique_size = 25; let critique_width = glyphs .width(critique_size, &settings.win_critique) .unwrap_or(0.0); // Cargo fmt makes this this way, and Cargo clippy yells at us about it if we try and do the math // directly in the critique_loc array. This isn't my fault. let critique_x = settings.win_box_rect[0] + (settings.win_box_rect[2] / 2.0) - (critique_width / 2.0); let critique_loc = [critique_x, settings.win_box_rect[1] - 30.0]; Text::new_color(settings.text_color, critique_size) .draw( &settings.win_critique, glyphs, &c.draw_state, c.transform.trans(critique_loc[0], critique_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); let mut stat_row_y = settings.win_box_rect[1] + 30.0; let stat_row_margins = [10.0, 30.0]; let stat_row_x = [ settings.win_box_rect[0] + stat_row_margins[0], settings.win_box_rect[2] + settings.win_box_rect[0] - stat_row_margins[0], ]; // Left-aligned timer title. Text::new_color(settings.text_color, 25) .draw( &"TIME", glyphs, &c.draw_state, c.transform.trans(stat_row_x[0], stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Right-aligned stat indicating what the timer ended on when previous puzzle was solved. let timer_str = format!("{:02}:{:02}:{:02}", total_hrs, rem_mins, rem_seconds); let timer_size = 25; let timer_width = glyphs.width(timer_size, &timer_str).unwrap_or(0.0); Text::new_color(settings.text_color, timer_size) .draw( &timer_str, glyphs, &c.draw_state, c.transform.trans(stat_row_x[1] - timer_width, stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Left-aligned black count title. stat_row_y += stat_row_margins[1]; Text::new_color(settings.text_color, 25) .draw( &"BLACK", glyphs, &c.draw_state, c.transform.trans(stat_row_x[0], stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Right-aligned count of black/filled cells. let black_count_str = format!("{:>8}", controller.nonogram.goal_black); let black_count_size = 25; let black_count_width = glyphs .width(black_count_size, &black_count_str) .unwrap_or(0.0); Text::new_color(settings.text_color, black_count_size) .draw( &black_count_str, glyphs, &c.draw_state, c.transform .trans(stat_row_x[1] - black_count_width, stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // New stat row. stat_row_y += stat_row_margins[1]; // Left-aligned total cell count title. Text::new_color(settings.text_color, 25) .draw( &"TOTAL", glyphs, &c.draw_state, c.transform.trans(stat_row_x[0], stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Right-aligned total count of cells. let total_count = controller.nonogram.dimensions[0] * controller.nonogram.dimensions[1]; let total_count_str = format!("{}", total_count); let total_count_size = 25; let total_count_width = glyphs .width(total_count_size, &total_count_str) .unwrap_or(0.0); Text::new_color(settings.text_color, total_count_size) .draw( &total_count_str, glyphs, &c.draw_state, c.transform .trans(stat_row_x[1] - total_count_width, stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // New stat row. stat_row_y += stat_row_margins[1]; // Left-aligned black_square/total_square ratio title. Text::new_color(settings.text_color, 25) .draw( &"RATIO", glyphs, &c.draw_state, c.transform.trans(stat_row_x[0], stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Right-aligned black_square/total_square ratio title. let black_total_ratio = controller.nonogram.goal_black as f64 / total_count as f64; let black_total_ratio_str = format!("{:.2}", black_total_ratio); let black_total_ratio_size = 25; let black_total_ratio_width = glyphs .width(black_total_ratio_size, &black_total_ratio_str) .unwrap_or(0.0); Text::new_color(settings.text_color, black_total_ratio_size) .draw( &black_total_ratio_str, glyphs, &c.draw_state, c.transform .trans(stat_row_x[1] - black_total_ratio_width, stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // New stat row. stat_row_y += stat_row_margins[1]; // Left-aligned dimensions title. Text::new_color(settings.text_color, 25) .draw( &"DIMENSIONS", glyphs, &c.draw_state, c.transform.trans(stat_row_x[0], stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Right-aligned dimensions. let dimensions_str = format!( "{}x{}", controller.nonogram.dimensions[0], controller.nonogram.dimensions[1] ); let dimensions_size = 25; let dimensions_width = glyphs .width(dimensions_size, &dimensions_str) .unwrap_or(0.0); Text::new_color(settings.text_color, dimensions_size) .draw( &dimensions_str, glyphs, &c.draw_state, c.transform .trans(stat_row_x[1] - dimensions_width, stat_row_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // New game button. match controller.new_game_button { ButtonInteraction::None => { Rectangle::new_round(hex("9e4c41"), 5.0).draw( settings.new_game_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Hover => { Rectangle::new_round(hex("773931"), 5.0).draw( settings.new_game_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Select => { Rectangle::new_round(hex("633029"), 5.0).draw( settings.new_game_box, &c.draw_state, c.transform, g, ); } } // New game button text. let new_game_button_str = "NEW GAME".to_string(); let new_game_button_size = 25; let new_game_button_width = glyphs .width(new_game_button_size, &new_game_button_str) .unwrap_or(0.0); // Cargo fmt made these this way, and Cargo clippy yells at us if we try to do this when creating the // new_game_button_loc array. This isn't my fault. let new_game_button_x = settings.new_game_box[0] + (settings.new_game_box[2] / 2.0) - (new_game_button_width / 2.0); let new_game_button_y = settings.new_game_box[1] + (settings.new_game_box[3] / 2.0) + ((new_game_button_size as f64 * 0.75) / 2.0); let new_game_button_loc = [new_game_button_x, new_game_button_y]; Text::new_color(settings.text_color, new_game_button_size) .draw( &new_game_button_str, glyphs, &c.draw_state, c.transform .trans(new_game_button_loc[0], new_game_button_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw board background. let mut board_rect = [ settings.win_box_rect[0], settings.win_box_rect[1] - 300.0, settings.win_board_dimensions[0], settings.win_board_dimensions[1], ]; board_rect[0] += (settings.win_box_rect[2] / 2.0) - (board_rect[2] / 2.0); Rectangle::new(settings.background_color).draw( board_rect, &c.draw_state, c.transform, g, ); // Draw the game winning image. for col in 0..settings.cell_dimensions[0] { for row in 0..settings.cell_dimensions[1] { let value = controller.nonogram.get([col, row]); let pos = [ col as f64 * settings.win_cell_size, row as f64 * settings.win_cell_size, ]; if value == Cell::Filled { let cell_rect = [ board_rect[0] + pos[0], board_rect[1] + pos[1], settings.win_cell_size, settings.win_cell_size, ]; Rectangle::new(settings.filled_cell_background_color).draw( cell_rect, &c.draw_state, c.transform, g, ); } } } } else { let board_rect = [ settings.position[0], settings.position[1], settings.board_dimensions[0], settings.board_dimensions[1], ]; // Draw board background. Rectangle::new(settings.background_color).draw( board_rect, &c.draw_state, c.transform, g, ); // Draw filled cell background. // We calculate the height of text by multiplying font size by 0.75 in order to convert between pixels and points. let mark_size = (settings.cell_size / 1.5) as u32; let mark_width = mark_glyphs.width(mark_size, &"x").unwrap_or(0.0); let mark_loc = [ (settings.cell_size / 2.0) - (mark_width as f64 / 2.0), (settings.cell_size / 2.0) + ((mark_size as f64 * 0.75) / 2.0), ]; let mark_text = Text::new_color(settings.marked_cell_background_color, mark_size); for col in 0..settings.cell_dimensions[0] { for row in 0..settings.cell_dimensions[1] { let value = controller.nonogram.get([col, row]); let pos = [ col as f64 * settings.cell_size, row as f64 * settings.cell_size, ]; if value == Cell::Filled { let cell_rect = [ settings.position[0] + pos[0], settings.position[1] + pos[1], settings.cell_size, settings.cell_size, ]; Rectangle::new(settings.filled_cell_background_color).draw( cell_rect, &c.draw_state, c.transform, g, ); } else if value == Cell::Marked { mark_text .draw( "x", mark_glyphs, &c.draw_state, c.transform.trans( settings.position[0] + pos[0] + mark_loc[0], settings.position[1] + pos[1] + mark_loc[1], ), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } } } // Draw column and row hint numbers. // We calculate the height of text by multiplying font size by 0.75 in order to convert between pixels and points. let hint_num_size = 15; let hint_reg = Text::new_color(settings.text_color, hint_num_size); let hint_cross = Text::new_color(hex("666666"), hint_num_size); // Draw column hint numbers. // Currently this logic goes through the effort of finding the width of each individual number // in order to try and center all the numbers in a column. This might not be worth the effort, // as it's only really noticeable when the numbers start hitting the double digits. for k in 0..settings.cell_dimensions[0] as usize { let mut num_pos = 0; if controller.nonogram.goal_nums[0][k][0] == 0 { let ch = "0".to_string(); let hint_num_width = glyphs.width(hint_num_size, &ch).unwrap_or(0.0); let col_num_loc = (settings.cell_size / 2.0) - (hint_num_width as f64 / 2.0); let col_hint_x = settings.position[0] + (k as f64 * settings.cell_size) + col_num_loc; let col_hint_y = settings.position[0] - num_pos as f64 * 20.0 - 80.0; if controller.nonogram.current_nums[0][k][0] == 0 { hint_cross .draw( &ch, glyphs, &c.draw_state, c.transform.trans(col_hint_x, col_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } else { hint_reg .draw( &ch, glyphs, &c.draw_state, c.transform.trans(col_hint_x, col_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } } else { for i in (0..controller.nonogram.nums_per[0] as usize).rev() { let hint_val = controller.nonogram.goal_nums[0][k][i]; // Only draw column numbers that aren't 0. if hint_val != 0 { let ch = hint_val.abs().to_string(); let hint_num_width = glyphs.width(hint_num_size, &ch).unwrap_or(0.0); let col_num_loc = (settings.cell_size / 2.0) - (hint_num_width as f64 / 2.0); let col_hint_x = settings.position[0] + (k as f64 * settings.cell_size) + col_num_loc; let col_hint_y = settings.position[0] - num_pos as f64 * 20.0 - 80.0; // Either draw a normal number, or draw a crossout number. if hint_val > 0 { hint_reg .draw( &ch, glyphs, &c.draw_state, c.transform.trans(col_hint_x, col_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } else { hint_cross .draw( &ch, glyphs, &c.draw_state, c.transform.trans(col_hint_x, col_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } num_pos += 1; } } } } // Draw row hint numbers. let row_num_loc = (settings.cell_size / 2.0) + ((hint_num_size as f64 * 0.75) / 2.0); let mut row_hint_y = settings.position[1] + row_num_loc; for k in 0..settings.cell_dimensions[1] as usize { let mut num_pos = 0; if controller.nonogram.goal_nums[1][k][0] == 0 { let row_hint_x = settings.position[0] - num_pos as f64 * 20.0 - 25.0; if controller.nonogram.current_nums[1][k][0] == 0 { hint_cross .draw( &"0", glyphs, &c.draw_state, c.transform.trans(row_hint_x, row_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } else { hint_reg .draw( &"0", glyphs, &c.draw_state, c.transform.trans(row_hint_x, row_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } } else { for i in (0..controller.nonogram.nums_per[1] as usize).rev() { let hint_val = controller.nonogram.goal_nums[1][k][i]; // Only draw row numbers that aren't 0. if hint_val != 0 { let ch = hint_val.abs().to_string(); let row_hint_x = settings.position[0] - num_pos as f64 * 20.0 - 25.0; // Either draw a normal number, or draw a crossout number. if hint_val > 0 { hint_reg .draw( &ch, glyphs, &c.draw_state, c.transform.trans(row_hint_x, row_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } else { hint_cross .draw( &ch, glyphs, &c.draw_state, c.transform.trans(row_hint_x, row_hint_y), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } num_pos += 1; } } } row_hint_y += settings.cell_size; } // Draw cell borders. let cell_edge = Line::new(settings.cell_edge_color, settings.cell_edge_radius); for i in 0..controller.nonogram.dimensions[0] { // Skip lines that are covered by sections. if (i % 5) == 0 { continue; } let x = settings.position[0] + i as f64 / controller.nonogram.dimensions[0] as f64 * settings.cell_size * controller.nonogram.dimensions[0] as f64; let y2 = settings.position[1] + settings.cell_size * controller.nonogram.dimensions[1] as f64; let vline = [x, settings.position[1], x, y2]; cell_edge.draw(vline, &c.draw_state, c.transform, g); } for i in 0..controller.nonogram.dimensions[1] { // Skip lines that are covered by sections. if (i % 5) == 0 { continue; } let y = settings.position[1] + i as f64 / controller.nonogram.dimensions[1] as f64 * settings.cell_size * controller.nonogram.dimensions[1] as f64; let x2 = settings.position[0] + settings.cell_size * controller.nonogram.dimensions[0] as f64; let hline = [settings.position[0], y, x2, y]; cell_edge.draw(hline, &c.draw_state, c.transform, g); } // Draw section borders. let section_edge = Line::new(settings.section_edge_color, settings.section_edge_radius); for i in 1..(controller.nonogram.dimensions[0] / 5) { // Set up coordinates. let x = settings.position[0] + i as f64 / (controller.nonogram.dimensions[0] / 5) as f64 * settings.cell_size * controller.nonogram.dimensions[0] as f64; let y2 = settings.position[1] + settings.cell_size * controller.nonogram.dimensions[1] as f64; let vline = [x, settings.position[1], x, y2]; section_edge.draw(vline, &c.draw_state, c.transform, g); } for i in 1..(controller.nonogram.dimensions[1] / 5) { // Set up coordinates. let y = settings.position[1] + i as f64 / (controller.nonogram.dimensions[1] / 5) as f64 * settings.cell_size * controller.nonogram.dimensions[1] as f64; let x2 = settings.position[0] + settings.cell_size * controller.nonogram.dimensions[0] as f64; let hline = [settings.position[0], y, x2, y]; section_edge.draw(hline, &c.draw_state, c.transform, g); } // Draw board edge. Rectangle::new_border(settings.board_edge_color, settings.board_edge_radius).draw( board_rect, &c.draw_state, c.transform, g, ); // Draw info box. let info_box_rect = [20.0, 70.0, 250.0, 150.0]; Rectangle::new_round(hex("333333"), 10.0).draw( info_box_rect, &c.draw_state, c.transform, g, ); // Draw nonogram title. let nonogram_title_str = "NONOGRAM".to_string(); let nonogram_title_size = 25; let nonogram_title_width = glyphs .width(nonogram_title_size, &nonogram_title_str) .unwrap_or(0.0); let nonogram_title_loc = [ info_box_rect[0] + (info_box_rect[2] / 2.0) - (nonogram_title_width / 2.0), 60.0, ]; Text::new_color(settings.text_color, nonogram_title_size) .draw( &nonogram_title_str, glyphs, &c.draw_state, c.transform .trans(nonogram_title_loc[0], nonogram_title_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw progress title. let progress_title_str = "PROGRESS".to_string(); let progress_title_size = 12; let progress_title_width = glyphs .width(progress_title_size, &progress_title_str) .unwrap_or(0.0); let progress_title_loc = [ info_box_rect[0] + (info_box_rect[2] / 2.0) - (progress_title_width / 2.0), 95.0, ]; Text::new_color(settings.text_color, progress_title_size) .draw( &progress_title_str, glyphs, &c.draw_state, c.transform .trans(progress_title_loc[0], progress_title_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw progress. let progress_str = format!( "{} / {} ({:.2}%)", controller.nonogram.count_black, controller.nonogram.goal_black, (controller.nonogram.count_black as f32 / controller.nonogram.goal_black as f32) * 100.0 ); let progress_size = 25; let progress_width = glyphs.width(progress_size, &progress_str).unwrap_or(0.0); let progress_loc = [ info_box_rect[0] + (info_box_rect[2] / 2.0) - (progress_width / 2.0), 120.0, ]; Text::new_color(settings.text_color, progress_size) .draw( &progress_str, glyphs, &c.draw_state, c.transform.trans(progress_loc[0], progress_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw timer title. let timer_title_str = "TIMER".to_string(); let timer_title_size = 12; let timer_title_width = glyphs .width(timer_title_size, &timer_title_str) .unwrap_or(0.0); let timer_title_loc = [ info_box_rect[0] + (info_box_rect[2] / 2.0) - (timer_title_width / 2.0), 160.0, ]; Text::new_color(settings.text_color, timer_title_size) .draw( &timer_title_str, glyphs, &c.draw_state, c.transform.trans(timer_title_loc[0], timer_title_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw timer. let timer_str = format!("{:02}:{:02}:{:02}", total_hrs, rem_mins, rem_seconds); let timer_size = 50; // Unlike with the other drawn text, we don't use the actual string here, // because we don't want it to keep changing its location subtly for every // second that passes. let timer_width = glyphs.width(timer_size, &"00:00:00").unwrap_or(0.0); let timer_loc = [ info_box_rect[0] + (info_box_rect[2] / 2.0) - (timer_width / 2.0), 200.0, ]; Text::new_color(settings.text_color, timer_size) .draw( &timer_str, glyphs, &c.draw_state, c.transform.trans(timer_loc[0], timer_loc[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw selected cell border. if let Some(ind) = controller.nonogram.selected_cell { let pos = [ ind[0] as f64 * settings.cell_size, ind[1] as f64 * settings.cell_size, ]; let cell_rect = [ settings.position[0] + pos[0], settings.position[1] + pos[1], settings.cell_size, settings.cell_size, ]; Rectangle::new_round_border( settings.selected_cell_border_color, settings.selected_cell_border_round_radius, settings.selected_cell_border_radius, ) .draw(cell_rect, &c.draw_state, c.transform, g); } // Dropdown size selection menu. let dimensions_size = 25; let dimensions_pos = [ settings.dimensions_dropdown_menu_box[0] + 5.0, settings.dimensions_dropdown_menu_box[1] + (settings.dimensions_dropdown_menu_box[3] / 2.0) + ((dimensions_size as f64 * 0.75) / 2.0), ]; match controller.dimensions_dropdown_menu { ButtonInteraction::None => { Rectangle::new_round(hex("333333"), 5.0).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform, g, ); Rectangle::new_round_border(hex("333333"), 5.0, 2.0).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Hover => { Rectangle::new_round(hex("2D2D2D"), 5.0).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform, g, ); Rectangle::new_round_border(hex("2D2D2D"), 5.0, 2.0).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Select => { Rectangle::new_round(hex("333333"), 5.0).draw( settings.dimensions_dropdown_menu_select_background, &c.draw_state, c.transform, g, ); Rectangle::new_round_border(hex("2D2D2D"), 5.0, 2.0).draw( settings.dimensions_dropdown_menu_select_background, &c.draw_state, c.transform, g, ); Rectangle::new_round(hex("2D2D2D"), 5.0).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform, g, ); for (it, value) in DIMENSIONS_CHOICES.iter().enumerate() { if controller.dimensions_dropdown_options.0 == it { match controller.dimensions_dropdown_options.1 { ButtonInteraction::None => (), ButtonInteraction::Hover => { Rectangle::new(hex("222222")).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform.trans(0.0, dimensions_pos[1] * (it + 1) as f64), g, ); } ButtonInteraction::Select => { Rectangle::new(hex("333333")).draw( settings.dimensions_dropdown_menu_box, &c.draw_state, c.transform.trans(0.0, dimensions_pos[1] * (it + 1) as f64), g, ); } } } let dimensions_str = format!("{}x{}", value[0], value[1]); Text::new_color(settings.text_color, dimensions_size) .draw( &dimensions_str, glyphs, &c.draw_state, c.transform .trans(dimensions_pos[0], dimensions_pos[1] * (it + 2) as f64), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } } } let dimensions_str = format!( "{}x{}", controller.nonogram.next_dimensions[0], controller.nonogram.next_dimensions[1] ); let dimensions_size = 25; Text::new_color(settings.text_color, dimensions_size) .draw( &dimensions_str, glyphs, &c.draw_state, c.transform.trans(dimensions_pos[0], dimensions_pos[1]), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Draw dropdown arrow. // Reference for Material Icons: https://material.io/resources/icons/?style=baseline // Reference for unicode character codes: https://github.com/google/material-design-icons/blob/master/iconfont/codepoints let dimensions_dropdown_arrow_str = "\u{e5c5}".to_string(); let dimensions_dropdown_arrow_size = 25; let dimensions_dropdown_arrow_width = material_icons_glyphs .width( dimensions_dropdown_arrow_size, &dimensions_dropdown_arrow_str, ) .unwrap_or(0.0); Text::new_color(settings.text_color, dimensions_dropdown_arrow_size) .draw( &dimensions_dropdown_arrow_str, material_icons_glyphs, &c.draw_state, c.transform.trans( settings.dimensions_dropdown_menu_box[0] + settings.dimensions_dropdown_menu_box[2] - dimensions_dropdown_arrow_width, settings.dimensions_dropdown_menu_box[1] + (settings.dimensions_dropdown_menu_box[3] / 2.0) + (dimensions_dropdown_arrow_size as f64 * 0.75), ), g, ) .unwrap_or_else(|_| panic!("text draw failed")); // Restart game button. match controller.restart_button { ButtonInteraction::None => { Rectangle::new_round(hex("9e4c41"), 5.0).draw( settings.restart_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Hover => { Rectangle::new_round(hex("773931"), 5.0).draw( settings.restart_box, &c.draw_state, c.transform, g, ); } ButtonInteraction::Select => { Rectangle::new_round(hex("633029"), 5.0).draw( settings.restart_box, &c.draw_state, c.transform, g, ); } } let restart_str = "RESTART".to_string(); let restart_size = 25; Text::new_color(settings.text_color, restart_size) .draw( &restart_str, glyphs, &c.draw_state, c.transform.trans( settings.restart_box[0] + 5.0, settings.restart_box[1] + (settings.restart_box[3] / 2.0) + ((restart_size as f64 * 0.75) / 2.0), ), g, ) .unwrap_or_else(|_| panic!("text draw failed")); } } }
impl Solution { pub fn title_to_number(column_title: String) -> i32 { let (mut res,mut n) = (0,column_title.len()); for i in 0..n{ res = res * 26 + (column_title.as_bytes()[i] - b'A' + 1) as i32; } res } }
extern crate openssl; extern crate base64; extern crate hex; mod hex_to_base64; mod fixed_xor; mod single_byte_xor_cipher; mod repeating_key_xor; #[cfg(test)] mod challenges { mod set_1 { use base64; use openssl; use hex; use hex_to_base64::hex_to_base64; use fixed_xor::fixed_xor; use single_byte_xor_cipher; use repeating_key_xor::{self, hamming_distance}; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; use std::collections::HashSet; #[test] fn challenge_1() { assert_eq!(hex_to_base64("49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"), "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t") } #[test] fn challenge_2() { assert_eq!(fixed_xor("1c0111001f010100061a024b53535009181c", "686974207468652062756c6c277320657965"), "746865206b696420646f6e277420706c6179".to_owned()); } #[test] fn challenge_3() { assert_eq!(single_byte_xor_cipher::decode("1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736").1, "Cooking MC\'s like a pound of bacon".to_owned()); } #[test] fn challenge_4() { let mut file = File::open("4.txt").unwrap(); let mut reader = BufReader::new(file); let mut highest = (0.0, String::new()); let mut buf = String::new(); while reader.read_line(&mut buf).unwrap() != 0 { let solution = single_byte_xor_cipher::decode(&buf.replace("\n", "")); buf.clear(); if solution.0 > highest.0 { highest = solution; } } assert_eq!(highest.1, "Now that the party is jumping\n".to_owned()); } #[test] fn challenge_5() { assert_eq!(repeating_key_xor::encode("Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal", "ICE"), "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f".to_owned()); } #[test] fn challenge_6() { assert_eq!(hamming_distance("this is a test", "wokka wokka!!!"), 37); //let strings = single_byte_xor_cipher::to_hex_bytes("0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f").iter().fold(String::new(), |mut acc, b| { //acc.push(*b as char); //acc //}); //assert_eq!(repeating_key_xor::decode(&strings.as_str()).0, "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal".to_owned()); let mut file = File::open("6.txt").unwrap(); let mut buf = String::new(); file.read_to_string(&mut buf).unwrap(); let buf = buf.replace("\n", ""); let data = base64::decode(&buf).unwrap(); assert_eq!(repeating_key_xor::decode(&data).1, "Terminator X: Bring the noise".to_owned()); } #[test] fn challenge_7() { let mut file = File::open("7.txt").unwrap(); let mut buf = String::new(); file.read_to_string(&mut buf); let buf = buf.replace("\n", ""); let data = base64::decode(&buf).unwrap(); let cipher = openssl::symm::Cipher::aes_128_ecb(); let key = "YELLOW SUBMARINE"; let text = String::from_utf8(openssl::symm::decrypt(cipher, key.as_bytes(), None, &data).unwrap()).unwrap(); assert!(text.starts_with("I\'m back and I\'m ringin\' the bell \nA rockin\' on the mike while the fly girls yell")); } #[test] fn challenge_8() { let mut file = File::open("8.txt").unwrap(); let mut buf = String::new(); let mut candidates = vec![]; file.read_to_string(&mut buf); for line in buf.lines() { let mut set = HashSet::new(); let mut i = 0; while i < line.len() - 4 { set.insert(line[i..i + 3].to_owned()); i += 4; } if set.len() < (line.len() / 4 - 10) { candidates.push((line, set.len())); } //println!("...{}: {}, {}", line.replacen(|_| true, "", line.len() - 20), set.len(), line.len() / 4); } assert_eq!(candidates[0].1, 55); } } }
use crate::util; use std::u8::MAX as U8_MAX; pub fn is_valid_password(candidate: u32, range_start: u32, range_end: u32) -> bool { let num_digits = util::number_of_digits(candidate as f64) as u32; assert!(num_digits == 6); assert!(candidate >= range_start && candidate <= range_end); let mut successful_candidate = true; let mut adjacent_sequence = String::new(); let mut found_a_sequence_of_exactly_two_digits = false; let mut last_number = U8_MAX; for i in 0..=num_digits { let digit = util::digit_at_index(num_digits - i, candidate); if last_number == U8_MAX { adjacent_sequence.push(digit as char); } else if digit < last_number { successful_candidate = false; break; } else if digit == last_number { adjacent_sequence.push(digit as char); } else { found_a_sequence_of_exactly_two_digits |= adjacent_sequence.len() == 2; adjacent_sequence = String::new(); adjacent_sequence.push(digit as char); } last_number = digit; } found_a_sequence_of_exactly_two_digits |= adjacent_sequence.len() == 2; if successful_candidate && found_a_sequence_of_exactly_two_digits { return true; } false } #[cfg(test)] mod tests { use super::*; use crate::util; fn parse(input: &str) -> (u32, u32) { let range: Vec<u32> = input.split("-").take(2).map(str_to_u32).collect(); (range[0], range[1]) } fn str_to_u32(string: &str) -> u32 { string.parse::<u32>().unwrap() } #[test] fn test_advent_puzzle() { let range_str: String = util::load_input_file("day04.txt").unwrap(); let (start, end) = parse(&range_str); let possibilities_count = (start..end) .filter(|num| is_valid_password(*num, start, end)) .count(); assert_eq!(possibilities_count, 1196); } #[test] fn smoke_simple_program_1() { assert!(is_valid_password(112233, 112233, 112233)); } #[test] fn smoke_simple_program_2() { assert!(!is_valid_password(123444, 123444, 123444)); } #[test] fn smoke_simple_program_3() { assert!(is_valid_password(111122, 111122, 111122)); } }
use bellman::{gadgets::Assignment, groth16, Circuit, ConstraintSystem, SynthesisError}; use bls12_381::Bls12; use bls12_381::Scalar; use ff::{Field, PrimeField}; use rand::rngs::OsRng; use std::ops::{AddAssign, MulAssign, SubAssign}; use std::time::Instant; use crate::error::Result; pub struct ZKVirtualMachine { pub constants: Vec<Scalar>, pub alloc: Vec<(AllocType, VariableIndex)>, pub ops: Vec<CryptoOperation>, pub constraints: Vec<ConstraintInstruction>, pub aux: Vec<Scalar>, pub params: Option<groth16::Parameters<Bls12>>, pub verifying_key: Option<groth16::PreparedVerifyingKey<Bls12>>, } pub type VariableIndex = usize; pub enum VariableRef { Aux(VariableIndex), Local(VariableIndex), } pub enum CryptoOperation { Set(VariableRef, VariableRef), Mul(VariableRef, VariableRef), Add(VariableRef, VariableRef), Sub(VariableRef, VariableRef), Load(VariableRef, VariableIndex), Divide(VariableRef, VariableRef), Double(VariableRef), Square(VariableRef), Invert(VariableRef), UnpackBits(VariableRef, VariableRef, VariableRef), Local, Debug(String, VariableRef), DumpAlloc, DumpLocal, } #[derive(Clone)] pub enum AllocType { Private, Public, } #[derive(Debug, Clone)] pub enum ConstraintInstruction { Lc0Add(VariableIndex), Lc1Add(VariableIndex), Lc2Add(VariableIndex), Lc0Sub(VariableIndex), Lc1Sub(VariableIndex), Lc2Sub(VariableIndex), Lc0AddOne, Lc1AddOne, Lc2AddOne, Lc0SubOne, Lc1SubOne, Lc2SubOne, Lc0AddCoeff(VariableIndex, VariableIndex), Lc1AddCoeff(VariableIndex, VariableIndex), Lc2AddCoeff(VariableIndex, VariableIndex), Lc0AddConstant(VariableIndex), Lc1AddConstant(VariableIndex), Lc2AddConstant(VariableIndex), Enforce, LcCoeffReset, LcCoeffDouble, } #[derive(Debug)] pub enum ZKVMError { DivisionByZero, MalformedRange, } impl ZKVirtualMachine { pub fn initialize( &mut self, params: &Vec<(VariableIndex, Scalar)>, ) -> std::result::Result<(), ZKVMError> { // Resize array self.aux = vec![Scalar::zero(); self.alloc.len()]; // Copy over the parameters for (index, value) in params { //println!("Setting {} to {:?}", index, value); self.aux[*index] = *value; } let mut local_stack: Vec<Scalar> = Vec::new(); for op in &self.ops { match op { CryptoOperation::Set(self_, other) => { let other = match other { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; *self_ = other; } CryptoOperation::Mul(self_, other) => { let other = match other { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; self_.mul_assign(other); } CryptoOperation::Add(self_, other) => { let other = match other { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; self_.add_assign(other); } CryptoOperation::Sub(self_, other) => { let other = match other { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; self_.sub_assign(other); } CryptoOperation::Load(self_, const_index) => { let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; *self_ = self.constants[*const_index]; } CryptoOperation::Divide(self_, other) => { let other = match other { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; let ret = other.invert().map(|other| *self_ * other); if bool::from(ret.is_some()) { *self_ = ret.unwrap(); } else { return Err(ZKVMError::DivisionByZero); } } CryptoOperation::Double(self_) => { let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; *self_ = self_.double(); } CryptoOperation::Square(self_) => { let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; *self_ = self_.square(); } CryptoOperation::Invert(self_) => { let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; if self_.is_zero() { return Err(ZKVMError::DivisionByZero); } else { *self_ = self_.invert().unwrap(); } } CryptoOperation::UnpackBits(value, start, end) => { let value = match value { VariableRef::Aux(index) => self.aux[*index].clone(), VariableRef::Local(index) => local_stack[*index].clone(), }; let (self_, start_index, end_index) = match start { VariableRef::Aux(start_index) => match end { VariableRef::Aux(end_index) => (&mut self.aux, start_index, end_index), VariableRef::Local(_) => { return Err(ZKVMError::MalformedRange); } }, VariableRef::Local(start_index) => match end { VariableRef::Aux(_) => { return Err(ZKVMError::MalformedRange); } VariableRef::Local(end_index) => { (&mut local_stack, start_index, end_index) } }, }; if start_index > end_index { return Err(ZKVMError::MalformedRange); } if (end_index + 1) - start_index != 256 { return Err(ZKVMError::MalformedRange); } if *end_index >= self_.len() { return Err(ZKVMError::MalformedRange); } for (i, bit) in value.to_le_bits().into_iter().cloned().enumerate() { match bit { true => self_[start_index + i] = Scalar::one(), false => self_[start_index + i] = Scalar::zero(), } } } CryptoOperation::Local => { local_stack.push(Scalar::zero()); } CryptoOperation::Debug(debug_str, self_) => { let self_ = match self_ { VariableRef::Aux(index) => &mut self.aux[*index], VariableRef::Local(index) => &mut local_stack[*index], }; println!("{}", debug_str); println!("value = {:?}", self_); } CryptoOperation::DumpAlloc => { println!("-------------------"); println!("alloc"); println!("-------------------"); for (i, value) in self.aux.iter().enumerate() { println!("{}: {:?}", i, value); } println!("-------------------"); } CryptoOperation::DumpLocal => { println!("-------------------"); println!("local"); println!("-------------------"); for (i, value) in local_stack.iter().enumerate() { println!("{}: {:?}", i, value); } println!("-------------------"); } } } Ok(()) } pub fn public(&self) -> Vec<(VariableIndex, Scalar)> { let mut publics = Vec::new(); for (alloc_type, index) in &self.alloc { match alloc_type { AllocType::Private => {} AllocType::Public => { let scalar = self.aux[*index].clone(); publics.push((*index, scalar)); } } } publics } pub fn setup(&mut self) -> Result<()> { let start = Instant::now(); // Create parameters for our circuit. In a production deployment these would // be generated securely using a multiparty computation. self.params = Some({ let circuit = ZKVMCircuit { aux: vec![None; self.aux.len()], alloc: self.alloc.clone(), constraints: self.constraints.clone(), constants: self.constants.clone(), }; groth16::generate_random_parameters::<Bls12, _, _>(circuit, &mut OsRng)? }); println!("Setup: [{:?}]", start.elapsed()); self.verifying_key = Some(groth16::prepare_verifying_key( &self.params.as_ref().unwrap().vk, )); Ok(()) } pub fn prove(&self) -> groth16::Proof<Bls12> { let aux = self.aux.iter().map(|scalar| Some(scalar.clone())).collect(); // Create an instance of our circuit (with the preimage as a witness). let circuit = ZKVMCircuit { aux, alloc: self.alloc.clone(), constraints: self.constraints.clone(), constants: self.constants.clone(), }; let start = Instant::now(); // Create a Groth16 proof with our parameters. let proof = groth16::create_random_proof(circuit, self.params.as_ref().unwrap(), &mut OsRng) .unwrap(); println!("Prove: [{:?}]", start.elapsed()); proof } pub fn verify(&self, proof: &groth16::Proof<Bls12>, public_values: &Vec<Scalar>) -> bool { let start = Instant::now(); let is_passed = groth16::verify_proof(self.verifying_key.as_ref().unwrap(), proof, public_values) .is_ok(); println!("Verify: [{:?}]", start.elapsed()); is_passed } } pub struct ZKVMCircuit { aux: Vec<Option<bls12_381::Scalar>>, alloc: Vec<(AllocType, VariableIndex)>, constraints: Vec<ConstraintInstruction>, constants: Vec<Scalar>, } impl Circuit<bls12_381::Scalar> for ZKVMCircuit { fn synthesize<CS: ConstraintSystem<bls12_381::Scalar>>( self, cs: &mut CS, ) -> std::result::Result<(), SynthesisError> { let mut variables = Vec::new(); for (alloc_type, index) in &self.alloc { match alloc_type { AllocType::Private => { let var = cs.alloc(|| "private alloc", || Ok(*self.aux[*index].get()?))?; variables.push(var); } AllocType::Public => { let var = cs.alloc_input(|| "public alloc", || Ok(*self.aux[*index].get()?))?; variables.push(var); } } } let mut coeff = bls12_381::Scalar::one(); let mut lc0 = bellman::LinearCombination::<Scalar>::zero(); let mut lc1 = bellman::LinearCombination::<Scalar>::zero(); let mut lc2 = bellman::LinearCombination::<Scalar>::zero(); for constraint in self.constraints { match constraint { ConstraintInstruction::Lc0Add(index) => { lc0 = lc0 + (coeff, variables[index]); } ConstraintInstruction::Lc1Add(index) => { lc1 = lc1 + (coeff, variables[index]); } ConstraintInstruction::Lc2Add(index) => { lc2 = lc2 + (coeff, variables[index]); } ConstraintInstruction::Lc0Sub(index) => { lc0 = lc0 - (coeff, variables[index]); } ConstraintInstruction::Lc1Sub(index) => { lc1 = lc1 - (coeff, variables[index]); } ConstraintInstruction::Lc2Sub(index) => { lc2 = lc2 - (coeff, variables[index]); } ConstraintInstruction::Lc0AddOne => { lc0 = lc0 + CS::one(); } ConstraintInstruction::Lc1AddOne => { lc1 = lc1 + CS::one(); } ConstraintInstruction::Lc2AddOne => { lc2 = lc2 + CS::one(); } ConstraintInstruction::Lc0SubOne => { lc0 = lc0 - CS::one(); } ConstraintInstruction::Lc1SubOne => { lc1 = lc1 - CS::one(); } ConstraintInstruction::Lc2SubOne => { lc2 = lc2 - CS::one(); } ConstraintInstruction::Lc0AddCoeff(const_index, index) => { lc0 = lc0 + (self.constants[const_index], variables[index]); } ConstraintInstruction::Lc1AddCoeff(const_index, index) => { lc1 = lc1 + (self.constants[const_index], variables[index]); } ConstraintInstruction::Lc2AddCoeff(const_index, index) => { lc2 = lc2 + (self.constants[const_index], variables[index]); } ConstraintInstruction::Lc0AddConstant(const_index) => { lc0 = lc0 + (self.constants[const_index], CS::one()); } ConstraintInstruction::Lc1AddConstant(const_index) => { lc1 = lc1 + (self.constants[const_index], CS::one()); } ConstraintInstruction::Lc2AddConstant(const_index) => { lc2 = lc2 + (self.constants[const_index], CS::one()); } ConstraintInstruction::Enforce => { cs.enforce( || "constraint", |_| lc0.clone(), |_| lc1.clone(), |_| lc2.clone(), ); coeff = bls12_381::Scalar::one(); lc0 = bellman::LinearCombination::<Scalar>::zero(); lc1 = bellman::LinearCombination::<Scalar>::zero(); lc2 = bellman::LinearCombination::<Scalar>::zero(); } ConstraintInstruction::LcCoeffReset => { coeff = bls12_381::Scalar::one(); } ConstraintInstruction::LcCoeffDouble => { coeff = coeff.double(); } } } Ok(()) } }
#[macro_export] macro_rules! switch { ($exp:expr, [$($template:tt)*] => $action:expr) => { switch!($exp, [$($template)*] => $action,) }; ($exp:expr, [$($template:tt)*] => $action:expr,) => { scheme_match!($exp, {$action}, $($template)*) .expect("Last clause in switch must never fail to match") }; ($exp:expr, [$($template:tt)*] => $action:expr, $($rest:tt)*) => { scheme_match!($exp, {$action}, $($template)*) .unwrap_or_else(|| switch!($exp, $($rest)*)) }; ($exp:expr, $predicate:expr => $action:expr,) => { if $predicate($exp) { $action } else { panic!("Last clause in switch must never fail to match") } }; ($exp:expr, $predicate:expr => $action:expr, $($rest:tt)*) => { if $predicate($exp) { $action } else { switch!($exp, $($rest)*) } }; } #[macro_export] macro_rules! scheme_match { ($exp:expr, $action:block, ($single:tt)) => { $exp.decons() .filter(|(_, cdr)| cdr.is_nil()) .and_then(|(_car, _)| scheme_match!(_car, $action, $single)) }; ($exp:expr, $action:block, ($car:tt . $($cdr:tt)*)) => { $exp.decons() .and_then(|(_car, _cdr)| scheme_match!(_car, { scheme_match!(_cdr, $action, $($cdr)*) }, $car)).unwrap_or(None) }; ($exp:expr, $action:block, (? $car:tt . $($cdr:tt)*)) => { $exp.decons() .and_then(|(_car, _cdr)| scheme_match!(_car, { scheme_match!(_cdr, $action, $($cdr)*) }, ?$car)).unwrap_or(None) }; ($exp:expr, $action:block, (? $var:tt)) => { $exp.decons() .filter(|(_, cdr)| cdr.is_nil()) .and_then(|(car, _)| scheme_match!(car, $action, ?$var)) }; ($exp:expr, $action:block, (? $first:tt $($rest:tt)*)) => { $exp.decons() .and_then(|(car, cdr)| { scheme_match!(car, { scheme_match!(cdr, $action, ($($rest)*)) }, ?$first).unwrap_or(None) }) }; ($exp:expr, $action:block, ($first:tt $($rest:tt)*)) => { $exp.decons() .and_then(|(_car, _cdr)| { scheme_match!(_car, { scheme_match!(_cdr, $action, ($($rest)*)) }, $first).unwrap_or(None) }) }; ($exp:expr, $action:block, ()) => { if $exp.is_nil() { Some($action) } else { None } }; ($exp:expr, $action:block, _) => { Some($action) }; ($exp:expr, $action:block, ? $var:ident) => { { let $var = $exp; Some($action) } }; ($exp:expr, $action:block, $sym:ident) => { if let Some(stringify!($sym)) = $exp.symbol_name() { Some($action) } else { None } }; ($exp:expr, $action:block, $val:expr) => { if $exp == &$val { Some($action) } else { None } }; } #[cfg(test)] mod tests { use crate::SchemeExpression; use Expr::*; #[derive(Debug, PartialEq)] enum Expr { Nil, Symbol(&'static str), Int(i64), Pair(Box<Expr>, Box<Expr>), } impl Expr { fn cons(car: Expr, cdr: Expr) -> Self { Pair(Box::new(car), Box::new(cdr)) } } impl crate::SchemeExpression for Expr { fn symbol_name(&self) -> Option<&'static str> { if let Symbol(name) = self { Some(name) } else { None } } fn car(&self) -> Option<&Self> { if let Pair(a, _) = self { Some(a) } else { None } } fn cdr(&self) -> Option<&Self> { if let Pair(_, d) = self { Some(d) } else { None } } fn is_nil(&self) -> bool { *self == Nil } } impl PartialEq<i64> for Expr { fn eq(&self, rhs: &i64) -> bool { if let Int(i) = self { i == rhs } else { false } } } #[test] fn simple_mismatch_sconstant() { assert_eq!(None, scheme_match!(&Symbol("xyz"), {}, abc)); assert_eq!(None, scheme_match!(&Int(666), {}, 42)); assert_eq!(None, scheme_match!(&Int(42), {}, ())); } #[test] fn simple_match_constant() { assert_eq!(Some(()), scheme_match!(&Symbol("xyz"), {}, xyz)); assert_eq!(Some(()), scheme_match!(&Int(42), {}, 42)); assert_eq!(Some(()), scheme_match!(&Nil, {}, ())); assert_eq!(Some(()), scheme_match!(&Symbol("xyz"), {}, _)); } #[test] fn simple_match_bound() { assert_eq!( Some(&Symbol("xyz")), scheme_match!(&Symbol("xyz"), { x }, ?x) ); assert_eq!(Some(&Int(42)), scheme_match!(&Int(42), { x }, ?x)); assert_eq!(Some(&Nil), scheme_match!(&Nil, { x }, ?x)); } #[test] fn unary_list() { let list = Expr::cons(Int(42), Nil); assert_eq!(Some(()), scheme_match!(&list, {}, (42))); let list = Expr::cons(Symbol("alpha"), Nil); assert_eq!(Some(()), scheme_match!(&list, {}, (alpha))); } #[test] fn unary_list_bound() { let list = Expr::cons(Int(42), Nil); assert_eq!(Some(&Int(42)), scheme_match!(&list, { x }, (?x))); } #[test] fn list_match() { let list = Expr::cons(Int(1), Expr::cons(Int(2), Expr::cons(Int(3), Nil))); assert_eq!(None, scheme_match!(&list, {}, (_ _))); assert_eq!(Some(()), scheme_match!(&list, {}, (_ _ _))); assert_eq!(None, scheme_match!(&list, {}, (_ _ _ _))); assert_eq!(Some(&Int(1)), scheme_match!(&list, {x}, (?x _ _))); assert_eq!(Some(&Int(2)), scheme_match!(&list, {y}, (_ ?y _))); assert_eq!(Some(&Int(3)), scheme_match!(&list, {z}, (_ _ ?z))); } #[test] fn nested_list() { let list = Expr::cons( Int(1), Expr::cons( Expr::cons(Symbol("a2"), Expr::cons(Symbol("b2"), Nil)), Expr::cons(Int(3), Nil), ), ); assert_eq!( Some((&Int(1), &Symbol("b2"))), scheme_match!(&list, { (x, y) }, (?x (a2 ?y) _)) ); } #[test] fn pair_match() { let pair = Expr::cons(Int(1), Int(2)); assert_eq!(None, scheme_match!(&pair, {}, (_ _))); assert_eq!(Some(()), scheme_match!(&pair, {}, (_ . _))); assert_eq!(None, scheme_match!(&pair, {}, (_ _ _))); assert_eq!(Some(&Int(1)), scheme_match!(&pair, {x}, (?x . _))); assert_eq!(Some(&Int(2)), scheme_match!(&pair, {y}, (_ . ?y))); } #[test] #[should_panic(expected = "Last clause in switch must never fail to match")] fn switch_error() { switch! { &Int(5), [4] => { } }; } #[test] fn switch_one_clause() { assert_eq!( switch! { &Int(5), [?x] => { x } }, &Int(5) ); assert_eq!( switch! { &Nil, [_] => { 42 } }, 42 ); } #[test] #[should_panic(expected = "Last clause in switch must never fail to match")] fn switch_n_error() { switch! { &Int(5), [1] => { }, [2] => { }, [3] => { }, }; } #[test] fn switch_n_clauses() { assert_eq!( switch! { &Int(5), [4] => 42, [_] => 0 }, 0 ); } #[test] fn switch_predicate() { assert_eq!( switch! { &Int(4), |_| false => 1, |_| true => 2, }, 2 ) } }
use crate::common::error::VdrResult; use crate::ledger::{PreparedRequest, RequestBuilder}; use crate::pool::handlers::{handle_consensus_request, handle_full_request, NodeReplies}; use crate::pool::{Pool, PoolBuilder, PoolTransactions, RequestResult, SharedPool}; use crate::utils::test::GenesisTransactions; use futures::executor::block_on; pub struct TestPool { pool: SharedPool, } impl TestPool { pub fn new() -> TestPool { let pool_transactions = PoolTransactions::from_transactions_json(GenesisTransactions::default_transactions()) .unwrap(); let pool = PoolBuilder::default() .transactions(pool_transactions) .unwrap() .into_shared() .unwrap(); TestPool { pool } } pub fn transactions(&self) -> Vec<String> { self.pool.get_transactions().unwrap() } pub fn request_builder(&self) -> RequestBuilder { self.pool.get_request_builder() } pub fn send_request(&self, prepared_request: &PreparedRequest) -> Result<String, String> { block_on(async { let request = self .pool .create_request( prepared_request.req_id.to_string(), prepared_request.req_json.to_string(), ) .await .unwrap(); let (request_result, _timing) = handle_consensus_request( request, prepared_request.sp_key.clone(), prepared_request.sp_timestamps, prepared_request.is_read_request, None, ) .await .unwrap(); match request_result { RequestResult::Reply(message) => Ok(message), RequestResult::Failed(err) => Err(err.extra().unwrap_or_default()), } }) } pub fn send_full_request( &self, prepared_request: &PreparedRequest, node_aliases: Option<Vec<String>>, timeout: Option<i64>, ) -> VdrResult<NodeReplies<String>> { block_on(async { let request = self .pool .create_request( prepared_request.req_id.to_string(), prepared_request.req_json.to_string(), ) .await .unwrap(); let (request_result, _timing) = handle_full_request(request, node_aliases, timeout) .await .unwrap(); match request_result { RequestResult::Reply(replies) => Ok(replies), RequestResult::Failed(err) => Err(err), } }) } pub fn send_request_with_retries( &self, prepared_request: &PreparedRequest, previous_response: &str, ) -> Result<String, String> { Self::_submit_retry( Self::extract_seq_no_from_reply(previous_response).unwrap(), || self.send_request(&prepared_request), ) } pub fn extract_seq_no_from_reply(reply: &str) -> Result<u64, &'static str> { let reply: serde_json::Value = serde_json::from_str(reply).map_err(|_| "Cannot deserialize transaction Response")?; let seq_no = reply["result"]["seqNo"] .as_u64() .or_else(|| reply["result"]["txnMetadata"]["seqNo"].as_u64()) .ok_or("Missed seqNo in reply")?; Ok(seq_no) } const SUBMIT_RETRY_CNT: usize = 3; fn _submit_retry<F>(minimal_timestamp: u64, submit_action: F) -> Result<String, String> where F: Fn() -> Result<String, String>, { let mut i = 0; let action_result = loop { let action_result = submit_action()?; let retry = Self::extract_seq_no_from_reply(&action_result) .map(|received_timestamp| received_timestamp < minimal_timestamp) .unwrap_or(true); if retry && i < Self::SUBMIT_RETRY_CNT { ::std::thread::sleep(::std::time::Duration::from_secs(2)); i += 1; } else { break action_result; } }; Ok(action_result) } }
//! Camera focus implementation. use arctk::{ access, geom::{Orient, Ray}, math::{Dir3, Pos3}, }; /// Focus structure. #[derive(Debug)] pub struct Focus { /// Orientation. orient: Orient, /// Target point. tar: Pos3, } impl Focus { access!(orient, orient_mut, Orient); access!(tar, Pos3); /// Construct a new instance. #[inline] #[must_use] pub fn new(pos: Pos3, tar: Pos3) -> Self { Self { orient: Orient::new(Ray::new(pos, Dir3::new_normalize(tar - pos))), tar, } } /// Create a direct observation ray. #[inline] #[must_use] pub fn observation_ray(&self) -> Ray { Ray::new( *self.orient.pos(), Dir3::new_normalize(self.tar - self.orient.pos()), ) } }
use crate::bot::dialogs::{Dialog, Subscribe, Unsubscribe}; use crate::db::client::DbClient; use crate::reddit::client::RedditClient; use crate::telegram::client::TelegramClient; use crate::telegram::types::Message; use diesel::result::DatabaseErrorKind; use diesel::result::Error::DatabaseError; const HELP_TEXT: &str = r#" You can send me these commands: /start /stop /subscribe /unsubscribe /subscriptions /help Bot is open source and available here https://github.com/aldis-ameriks/reddit-bot. If you encounter any issues feel free to open an issue. "#; pub async fn start( telegram_client: &TelegramClient, db: &DbClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { match db.create_user(user_id) { Ok(_) => { telegram_client .send_message(&Message { chat_id: user_id, text: HELP_TEXT, ..Default::default() }) .await?; Ok(()) } Err(DatabaseError(DatabaseErrorKind::UniqueViolation, _)) => { telegram_client .send_message(&Message { chat_id: user_id, text: HELP_TEXT, ..Default::default() }) .await?; Ok(()) } Err(err) => Err(Box::new(err)), } } pub async fn stop( telegram_client: &TelegramClient, db: &DbClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { db.delete_user(user_id)?; telegram_client .send_message(&Message { chat_id: user_id, text: "User and subscriptions deleted", ..Default::default() }) .await?; Ok(()) } pub async fn subscribe( telegram_client: &TelegramClient, db: &DbClient, reddit_client: &RedditClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { db.create_user(user_id).ok(); Dialog::<Subscribe>::new(user_id.to_string()) .handle_current_step(&telegram_client, &db, &reddit_client, "") .await?; Ok(()) } pub async fn unsubscribe( telegram_client: &TelegramClient, db: &DbClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { db.create_user(user_id).ok(); Dialog::<Unsubscribe>::new(user_id.to_string()) .handle_current_step(&telegram_client, &db, "") .await?; Ok(()) } pub async fn subscriptions( telegram_client: &TelegramClient, db: &DbClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { let subscriptions = db.get_user_subscriptions(user_id)?; if subscriptions.is_empty() { telegram_client .send_message(&Message { chat_id: user_id, text: "You have no subscriptions", ..Default::default() }) .await?; } else { let text = subscriptions .iter() .map(|subscription| format!("{}\n", subscription.subreddit)) .collect::<String>(); telegram_client .send_message(&Message { chat_id: user_id, text: &format!("You are currently subscribed to:\n{}", text), ..Default::default() }) .await?; } Ok(()) } pub async fn help( telegram_client: &TelegramClient, user_id: &str, ) -> Result<(), Box<dyn std::error::Error>> { telegram_client .send_message(&Message { chat_id: user_id, text: HELP_TEXT, ..Default::default() }) .await?; Ok(()) } #[cfg(test)] mod tests { use super::*; use crate::db::test_helpers::{setup_test_db, setup_test_db_with}; use crate::telegram::test_helpers::{mock_send_message_not_called, mock_send_message_success}; use mockito::server_url; use serial_test::serial; const TOKEN: &str = "token"; const USER_ID: &str = "123"; #[tokio::test] #[serial] async fn start_success() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: HELP_TEXT, ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let db_client = setup_test_db(); start(&telegram_client, &db_client, USER_ID).await.unwrap(); _m.assert(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); } #[tokio::test] #[serial] async fn start_existing_user() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: HELP_TEXT, ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let db_client = setup_test_db(); db_client.create_user(USER_ID).unwrap(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); start(&telegram_client, &db_client, USER_ID).await.unwrap(); _m.assert(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); } #[tokio::test] #[serial] async fn start_error() { let url = &server_url(); let _m = mock_send_message_not_called(TOKEN); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let db_client = setup_test_db_with(false); let result = start(&telegram_client, &db_client, USER_ID).await; assert!(result.is_err()); _m.assert(); } #[tokio::test] #[serial] async fn stop_success() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "User and subscriptions deleted", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let db_client = setup_test_db(); db_client.create_user(USER_ID).unwrap(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); stop(&telegram_client, &db_client, USER_ID).await.unwrap(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 0); _m.assert(); } #[tokio::test] #[serial] async fn stop_error() { let url = &server_url(); let _m = mock_send_message_not_called(TOKEN); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let db_client = setup_test_db_with(false); let result = stop(&telegram_client, &db_client, USER_ID).await; assert!(result.is_err()); _m.assert(); } #[tokio::test] #[serial] async fn subscribe_success() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "Type the name of subreddit you want to subscribe to", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let db_client = setup_test_db(); db_client.create_user(USER_ID).unwrap(); let reddit_client = RedditClient::new_with(url); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); subscribe(&telegram_client, &db_client, &reddit_client, USER_ID) .await .unwrap(); _m.assert(); } #[tokio::test] #[serial] async fn subscribe_without_user() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "Type the name of subreddit you want to subscribe to", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let db_client = setup_test_db(); let reddit_client = RedditClient::new_with(url); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 0); subscribe(&telegram_client, &db_client, &reddit_client, USER_ID) .await .unwrap(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); _m.assert(); } #[tokio::test] #[serial] async fn unsubscribe_without_user() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "You have no subscriptions to unsubscribe from", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let db_client = setup_test_db(); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); unsubscribe(&telegram_client, &db_client, USER_ID) .await .unwrap(); let users = db_client.get_users().unwrap(); assert_eq!(users.len(), 1); assert_eq!(users[0].id, USER_ID); _m.assert(); } #[tokio::test] #[serial] async fn subscriptions_success() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "You are currently subscribed to:\nrust\n", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let db_client = setup_test_db(); db_client.create_user(USER_ID).unwrap(); db_client.subscribe(USER_ID, "rust", 1, 1).unwrap(); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); subscriptions(&telegram_client, &db_client, USER_ID) .await .unwrap(); _m.assert(); } #[tokio::test] #[serial] async fn subscriptions_no_subscriptions() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: "You have no subscriptions", ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let db_client = setup_test_db(); db_client.create_user(USER_ID).unwrap(); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); subscriptions(&telegram_client, &db_client, USER_ID) .await .unwrap(); _m.assert(); } #[tokio::test] #[serial] async fn subscriptions_error() { let url = &server_url(); let _m = mock_send_message_not_called(TOKEN); let db_client = setup_test_db_with(false); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); let result = subscriptions(&telegram_client, &db_client, USER_ID).await; assert!(result.is_err()); _m.assert(); } #[tokio::test] #[serial] async fn help_success() { let url = &server_url(); let message = Message { chat_id: USER_ID, text: HELP_TEXT, ..Default::default() }; let _m = mock_send_message_success(TOKEN, &message); let telegram_client = TelegramClient::new_with(String::from(TOKEN), String::from(url)); help(&telegram_client, USER_ID).await.unwrap(); _m.assert(); } }
use errors::*; use Parameters; use tfdeploy::analyser::Analyser; /// Handles the `prune` subcommand. #[allow(dead_code)] pub fn handle(params: Parameters) -> Result<()> { let model = params.tfd_model; let output = model.get_node_by_id(params.output_node_id)?.id; info!("Starting the analysis."); let mut analyser = Analyser::new(model, output)?; info!( "Starting size of the graph: approx. {:?} bytes for {:?} nodes.", format!("{:?}", analyser.nodes).into_bytes().len(), analyser.nodes.len() ); analyser.run()?; analyser.propagate_constants()?; analyser.prune_unused(); info!( "Ending size of the graph: approx. {:?} bytes for {:?} nodes.", format!("{:?}", analyser.nodes).into_bytes().len(), analyser.nodes.len() ); Ok(()) }
use std::collections::HashMap; use arrayvec::ArrayVec; use quick_error::quick_error; use scroll::{Pread, Pwrite}; use crate::{ inode::{Inode, InodeIoError, InodeRaw, BASE_INODE_SIZE}, superblock::RequiredFeatureFlags, Filesystem, }; pub const MAGIC: u32 = 0xEA02_0000; pub const INLINE_HEADER_SIZE: usize = 4; #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Pread, Pwrite)] pub struct XattrInlineHeader { pub magic: u32, } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Pread, Pwrite)] pub struct XattrBlockHeader { pub magic: u32, pub refcount: u32, pub blocks_used: u32, pub hash: u32, pub checksum: u32, pub zero: [u32; 2], } #[derive(Clone, Debug, Eq, Hash, PartialEq)] pub struct XattrEntry { pub name_length: u8, pub name_index: u8, pub value_offset: u16, pub value_inode: u32, pub value_size: u32, pub hash: u32, pub name: Vec<u8>, } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] pub enum XattrNamePrefix { User = 1, SystemPosixAclAccess = 2, SystemPosixAclDefault = 3, Trusted = 4, Security = 6, System = 7, SystemRichAcl = 8, } #[derive(Debug)] struct InvalidPrefix(u8); impl XattrNamePrefix { fn from_raw(raw: u8) -> Result<Option<Self>, InvalidPrefix> { Ok(match raw { 0 => None, 1 => Some(Self::User), 2 => Some(Self::SystemPosixAclAccess), 3 => Some(Self::SystemPosixAclDefault), 4 => Some(Self::Trusted), 6 => Some(Self::Security), 7 => Some(Self::System), 8 => Some(Self::SystemRichAcl), other => return Err(InvalidPrefix(other)), }) } fn as_str(&self) -> &[u8] { match self { Self::User => b"user", Self::SystemPosixAclAccess => b"system.posix_acl_access", Self::SystemPosixAclDefault => b"system.posix_acl_default", Self::Trusted => b"trusted", Self::Security => b"security", Self::System => b"system", Self::SystemRichAcl => b"system.rich_acl", } } } impl XattrEntry { pub fn prefix(&self) -> Option<XattrNamePrefix> { XattrNamePrefix::from_raw(self.name_index) .expect("Validation passthrough when checking the xattr name prefix") } pub fn name(&self) -> Vec<u8> { let mut name = self.name.clone(); if let Some(prefix) = self.prefix() { let prefix = prefix.as_str(); // Prepend prefix and then a dot to the name. name.splice( 0..0, ArrayVec::from([prefix, &[b'.']]) .into_iter() .flatten() .copied(), ); } name } pub fn is_system_data(&self) -> bool { &self.name == b"data" && self.prefix() == Some(XattrNamePrefix::System) } } impl<'a> scroll::ctx::TryFromCtx<'a, scroll::Endian> for XattrEntry { type Error = scroll::Error; fn try_from_ctx(from: &'a [u8], ctx: scroll::Endian) -> Result<(Self, usize), Self::Error> { let mut offset = 0; let name_length: u8 = from.gread_with(&mut offset, ctx)?; let name_index = from.gread_with(&mut offset, ctx)?; let value_offset = from.gread_with(&mut offset, ctx)?; let value_inode = from.gread_with(&mut offset, ctx)?; let value_size = from.gread_with(&mut offset, ctx)?; let hash = from.gread_with(&mut offset, ctx)?; let len = offset + name_length as usize; if from.len() < len { return Err(scroll::Error::BadOffset(len - 1)); } let name = from[offset..len].to_owned(); Ok(( Self { name_length, name_index, value_offset, value_inode, value_size, hash, name, }, len, )) } } impl scroll::ctx::TryIntoCtx<scroll::Endian> for XattrEntry { type Error = scroll::Error; fn try_into_ctx(self, bytes: &mut [u8], ctx: scroll::Endian) -> Result<usize, Self::Error> { let mut offset = 0; bytes.gwrite_with(self.name_length, &mut offset, ctx)?; bytes.gwrite_with(self.name_index, &mut offset, ctx)?; bytes.gwrite_with(self.value_offset, &mut offset, ctx)?; bytes.gwrite_with(self.value_inode, &mut offset, ctx)?; bytes.gwrite_with(self.value_size, &mut offset, ctx)?; bytes.gwrite_with(self.hash, &mut offset, ctx)?; assert_eq!(self.name_length as usize, self.name.len()); let len = offset + self.name_length as usize; if bytes.len() < len { return Err(scroll::Error::BadOffset(len)); } bytes[offset..len].copy_from_slice(&self.name); Ok(len) } } #[derive(Clone, Debug, Eq, PartialEq)] pub struct InlineXattrs { pub header: XattrInlineHeader, pub entries: HashMap<XattrEntry, Vec<u8>>, } quick_error! { #[derive(Debug)] pub enum LoadXattrsError { EaInodeIoError(err: Box<InodeIoError>) { from() cause(err) description("extended attribute inode i/o error") display("extended attribute inode i/o error: {}", err) } ParseError(err: scroll::Error) { from() cause(err) description("parse error") display("parse error: {}", err) } } } impl From<InodeIoError> for LoadXattrsError { fn from(io: InodeIoError) -> Self { Box::new(io).into() } } impl InlineXattrs { pub fn load<D: fal::Device>( filesystem: &Filesystem<D>, inode: &InodeRaw, inode_bytes: &[u8], ) -> Result<Option<Self>, LoadXattrsError> { let inode_size = BASE_INODE_SIZE as u16 + inode.ext.as_ref().map(|ext| ext.extra_isize).unwrap_or(0); let space_for_xattrs = filesystem.superblock.inode_size() - inode_size; if space_for_xattrs < 4 { return Ok(None); } let mut offset = inode_size as usize; let header: XattrInlineHeader = inode_bytes.gread_with(&mut offset, scroll::LE)?; if header.magic != MAGIC { return Ok(None); } let mut entries = HashMap::new(); loop { let entry: XattrEntry = match inode_bytes.gread_with(&mut offset, scroll::LE) { Ok(e) => e, Err(scroll::Error::BadOffset(_)) => break, Err(other) => return Err(other.into()), }; if entry.name_length == 0 { // This makes little sense, but I'm not sure about an alternative. break; } let value = if entry.value_inode == 0 { let base = inode_size as usize + INLINE_HEADER_SIZE; inode_bytes[base + entry.value_offset as usize ..base + entry.value_offset as usize + entry.value_size as usize] .to_owned() } else { if filesystem .superblock .incompat_features() .contains(RequiredFeatureFlags::EA_INODE) { panic!("Xattr using EA_INODE even though the feature flag has been disabled.") } let inode = Inode::load(filesystem, entry.value_inode)?; let mut bytes = vec![0u8; entry.value_size as usize]; let bytes_read = inode.read(filesystem, entry.value_offset.into(), &mut bytes)?; assert_eq!(bytes_read, bytes.len()); bytes }; entries.insert(entry, value); } Ok(Some(Self { header, entries })) } }
#![cfg_attr(not(feature = "std"), no_std)] use liquid::storage; use liquid_lang as liquid; use liquid_lang::InOut; use liquid_prelude::{ string::{String, ToString}, vec::Vec, }; #[derive(InOut)] pub struct TableInfo { key_order: u8, key_column: String, value_columns: Vec<String>, } #[derive(InOut)] pub struct Entry { key: String, fields: Vec<String>, } #[derive(InOut)] pub struct UpdateField { column_name: String, value: String, } #[derive(InOut)] pub struct Condition { op: u8, field: String, value: String, } #[derive(InOut)] pub struct Limit { offset: u32, count: u32, } #[liquid::interface(name = auto)] mod table_manager { use super::*; extern "liquid" { fn createTable(&mut self, path: String, table_info: TableInfo) -> i32; } } #[liquid::interface(name = auto)] mod table { use super::*; extern "liquid" { fn select(&self, key: Vec<Condition>, limit: Limit) -> Vec<Entry>; fn insert(&mut self, entry: Entry) -> i32; fn update( &mut self, key: Vec<Condition>, limit: Limit, update_fields: Vec<UpdateField>, ) -> i32; fn remove(&mut self, key: Vec<Condition>, limit: Limit) -> i32; } } #[liquid::contract] mod table_test { use super::{table::*, table_manager::*, *}; #[liquid(event)] struct InsertResult { count: i32, } #[liquid(event)] struct UpdateResult { count: i32, } #[liquid(event)] struct RemoveResult { count: i32, } #[liquid(storage)] struct TableTest { table: storage::Value<Table>, tm: storage::Value<TableManager>, table_name: storage::Value<String>, } #[liquid(methods)] impl TableTest { pub fn new(&mut self) { self.table_name.initialize(String::from("t_testV320")); self.tm .initialize(TableManager::at("/sys/table_manager".parse().unwrap())); let mut column_names: Vec<String> = Vec::new(); column_names.push(String::from("name")); column_names.push(String::from("age")); column_names.push(String::from("status")); let ti = TableInfo { key_order: 1, key_column: String::from("id"), value_columns: column_names, }; self.tm.createTable(self.table_name.clone(), ti); self.table .initialize(Table::at("/tables/t_testV320".parse().unwrap())); } pub fn select(&self, id_low: i64, id_high: i64) -> Vec<String> { let limit = Limit { offset: 0, count: 500, }; let mut conditions: Vec<Condition> = Vec::new(); conditions.push(Condition { op: 0, field: String::from("id"), value: id_low.to_string(), }); conditions.push(Condition { op: 3, field: String::from("id"), value: id_high.to_string(), }); let entries = self.table.select(conditions, limit).unwrap(); let mut values: Vec<String> = Vec::new(); for entry in entries { values.push(entry.fields[0].clone()); } return values.clone(); } pub fn insert(&mut self, id: i64, name: String, age: String) -> i32 { let mut values = Vec::new(); values.push(name); values.push(age); values.push(String::from("init")); let entry = Entry { key: id.to_string(), fields: values, }; let result = self.table.insert(entry).unwrap(); self.env().emit(InsertResult { count: result.clone(), }); return result; } pub fn update(&mut self, id_low: i64, id_high: i64) -> i32 { let mut update_fields = Vec::new(); update_fields.push(UpdateField { column_name: String::from("status"), value: String::from("updated"), }); let limit = Limit { offset: 0, count: 500, }; let mut conditions: Vec<Condition> = Vec::new(); conditions.push(Condition { op: 0, field: String::from("id"), value: id_low.to_string(), }); conditions.push(Condition { op: 3, field: String::from("id"), value: id_high.to_string(), }); let result = self.table.update(conditions, limit, update_fields).unwrap(); self.env().emit(UpdateResult { count: result.clone(), }); return result; } pub fn remove(&mut self, id_low: i64, id_high: i64) -> i32 { let limit = Limit { offset: 0, count: 500, }; let mut conditions: Vec<Condition> = Vec::new(); conditions.push(Condition { op: 0, field: String::from("id"), value: id_low.to_string(), }); conditions.push(Condition { op: 3, field: String::from("id"), value: id_high.to_string(), }); let result = self.table.remove(conditions, limit).unwrap(); self.env().emit(RemoveResult { count: result.clone(), }); return result; } } }
use std::iter; use std::marker::PhantomData; use std::cmp::Ordering::{ Equal, Less, Greater }; use num::traits::{ Zero, Bounded }; use util::{ self, ExtInt }; use store::Store::{ Array, Bitmap }; pub enum Store<Size: ExtInt> { Array(Vec<Size>), Bitmap(Box<[u64]>), } impl<Size: ExtInt> Store<Size> { pub fn insert(&mut self, index: Size) -> bool { match *self { Array(ref mut vec) => { vec.binary_search(&index) .map_err(|loc| vec.insert(loc, index)) .is_err() }, Bitmap(ref mut bits) => { let (key, bit) = bitmap_location(index); if bits[key] & (1 << bit) == 0 { bits[key] |= 1 << bit; true } else { false } }, } } pub fn remove(&mut self, index: Size) -> bool { match *self { Array(ref mut vec) => { vec.binary_search(&index) .map(|loc| vec.remove(loc)) .is_ok() }, Bitmap(ref mut bits) => { let (key, bit) = bitmap_location(index); if bits[key] & (1 << bit) != 0 { bits[key] &= !(1 << bit); true } else { false } }, } } #[inline] pub fn contains(&self, index: Size) -> bool { match *self { Array(ref vec) => vec.binary_search(&index).is_ok(), Bitmap(ref bits) => bits[key(index)] & (1 << bit(index)) != 0 } } pub fn is_disjoint<'a>(&'a self, other: &'a Self) -> bool { match (self, other) { (&Array(ref vec1), &Array(ref vec2)) => { let (mut i1, mut i2) = (vec1.iter(), vec2.iter()); let (mut value1, mut value2) = (i1.next(), i2.next()); loop { match value1.and_then(|v1| value2.map(|v2| v1.cmp(v2))) { None => return true, Some(Equal) => return false, Some(Less) => value1 = i1.next(), Some(Greater) => value2 = i2.next(), } } }, (&Bitmap(ref bits1), &Bitmap(ref bits2)) => { bits1.iter().zip(bits2.iter()).all(|(&i1, &i2)| (i1 & i2) == 0) }, (&Array(ref vec), store @ &Bitmap(..)) | (store @ &Bitmap(..), &Array(ref vec)) => { vec.iter().all(|&i| !store.contains(i)) }, } } pub fn is_subset(&self, other: &Self) -> bool { match (self, other) { (&Array(ref vec1), &Array(ref vec2)) => { let (mut i1, mut i2) = (vec1.iter(), vec2.iter()); let (mut value1, mut value2) = (i1.next(), i2.next()); loop { match (value1, value2) { (None, _) => return true, (Some(..), None) => return false, (Some(v1), Some(v2)) => match v1.cmp(v2) { Equal => { value1 = i1.next(); value2 = i2.next(); }, Less => return false, Greater => value2 = i2.next(), }, } } }, (&Bitmap(ref bits1), &Bitmap(ref bits2)) => { bits1.iter().zip(bits2.iter()).all(|(&i1, &i2)| (i1 & i2) == i1) }, (&Array(ref vec), store @ &Bitmap(..)) => { vec.iter().all(|&i| store.contains(i)) }, (&Bitmap(..), &Array(..)) => false, } } pub fn to_array(&self) -> Self { match *self { Array(..) => panic!("Cannot convert array to array"), Bitmap(ref bits) => { let mut vec = Vec::new(); for (key, val) in bits.iter().map(|v| *v).enumerate().filter(|&(_, v)| v != 0) { for bit in 0..64 { if (val & (1 << bit)) != 0 { vec.push(util::cast(key * 64 + (bit as usize))); } } } Array(vec) }, } } pub fn to_bitmap(&self) -> Self { match *self { Array(ref vec) => { let count = util::cast::<Size, usize>(Bounded::max_value()) / 64 + 1; let mut bits = iter::repeat(0).take(count).collect::<Vec<u64>>().into_boxed_slice(); for &index in vec.iter() { bits[key(index)] |= 1 << bit(index); } Bitmap(bits) }, Bitmap(..) => panic!("Cannot convert bitmap to bitmap"), } } pub fn union_with(&mut self, other: &Self) { match (self, other) { (ref mut this, &Array(ref vec)) => { for &index in vec.iter() { this.insert(index); } }, (&mut Bitmap(ref mut bits1), &Bitmap(ref bits2)) => { for (index1, &index2) in bits1.iter_mut().zip(bits2.iter()) { *index1 |= index2; } }, (this @ &mut Array(..), &Bitmap(..)) => { *this = this.to_bitmap(); this.union_with(other); }, } } pub fn intersect_with(&mut self, other: &Self) { match (self, other) { (&mut Array(ref mut vec1), &Array(ref vec2)) => { let mut i1 = 0usize; let mut iter2 = vec2.iter(); let mut current2 = iter2.next(); while i1 < vec1.len() { match current2.map(|c2| vec1[i1].cmp(c2)) { None | Some(Less) => { vec1.remove(i1); }, Some(Greater) => { current2 = iter2.next(); }, Some(Equal) => { i1 += 1; current2 = iter2.next(); }, } } }, (&mut Bitmap(ref mut bits1), &Bitmap(ref bits2)) => { for (index1, &index2) in bits1.iter_mut().zip(bits2.iter()) { *index1 &= index2; } }, (&mut Array(ref mut vec), store @ &Bitmap(..)) => { for i in (0..(vec.len())).rev() { if !store.contains(vec[i]) { vec.remove(i); } } }, (this @ &mut Bitmap(..), &Array(..)) => { let mut new = other.clone(); new.intersect_with(this); *this = new; }, } } pub fn difference_with(&mut self, other: &Self) { match (self, other) { (&mut Array(ref mut vec1), &Array(ref vec2)) => { let mut i1 = 0usize; let mut iter2 = vec2.iter(); let mut current2 = iter2.next(); while i1 < vec1.len() { match current2.map(|c2| vec1[i1].cmp(c2)) { None => break, Some(Less) => { i1 += 1; }, Some(Greater) => { current2 = iter2.next(); }, Some(Equal) => { vec1.remove(i1); current2 = iter2.next(); }, } } }, (ref mut this @ &mut Bitmap(..), &Array(ref vec2)) => { for index in vec2.iter() { this.remove(*index); } }, (&mut Bitmap(ref mut bits1), &Bitmap(ref bits2)) => { for (index1, index2) in bits1.iter_mut().zip(bits2.iter()) { *index1 &= !*index2; } }, (&mut Array(ref mut vec), store @ &Bitmap(..)) => { for i in (0 .. vec.len()).rev() { if store.contains(vec[i]) { vec.remove(i); } } }, } } pub fn symmetric_difference_with(&mut self, other: &Self) { match (self, other) { (&mut Array(ref mut vec1), &Array(ref vec2)) => { let mut i1 = 0usize; let mut iter2 = vec2.iter(); let mut current2 = iter2.next(); while i1 < vec1.len() { match current2.map(|c2| vec1[i1].cmp(c2)) { None => break, Some(Less) => { i1 += 1; }, Some(Greater) => { vec1.insert(i1, *current2.unwrap()); i1 += 1; current2 = iter2.next(); }, Some(Equal) => { vec1.remove(i1); current2 = iter2.next(); }, } } if current2.is_some() { vec1.push(*current2.unwrap()); vec1.extend(iter2.map(|&x| x)); } }, (ref mut this @ &mut Bitmap(..), &Array(ref vec2)) => { for index in vec2.iter() { if this.contains(*index) { this.remove(*index); } else { this.insert(*index); } } }, (&mut Bitmap(ref mut bits1), &Bitmap(ref bits2)) => { for (index1, &index2) in bits1.iter_mut().zip(bits2.iter()) { *index1 ^= index2; } }, (this @ &mut Array(..), &Bitmap(..)) => { let mut new = other.clone(); new.symmetric_difference_with(this); *this = new; }, } } pub fn len(&self) -> u64 { match *self { Array(ref vec) => util::cast(vec.len()), Bitmap(ref bits) => { let mut len = 0; for bit in bits.iter() { len += bit.count_ones(); } util::cast(len) }, } } pub fn min(&self) -> Size { match *self { Array(ref vec) => *vec.first().unwrap(), Bitmap(ref bits) => { bits.iter().enumerate() .filter(|&(_, &bit)| bit != 0) .next().map(|(index, bit)| util::cast(index * 64 + (bit.trailing_zeros() as usize))) .unwrap() }, } } pub fn max(&self) -> Size { match *self { Array(ref vec) => *vec.last().unwrap(), Bitmap(ref bits) => { bits.iter().enumerate().rev() .filter(|&(_, &bit)| bit != 0) .next().map(|(index, bit)| util::cast(index * 64 + (63 - (bit.leading_zeros() as usize)))) .unwrap() }, } } #[inline] pub fn iter<'a>(&'a self) -> Box<Iterator<Item = Size> + 'a> { match *self { Array(ref vec) => Box::new(vec.iter().map(|x| *x)), Bitmap(ref bits) => Box::new(BitmapIter::new(bits)), } } } impl<Size: ExtInt> PartialEq for Store<Size> { fn eq(&self, other: &Self) -> bool { match (self, other) { (&Array(ref vec1), &Array(ref vec2)) => { vec1 == vec2 }, (&Bitmap(ref bits1), &Bitmap(ref bits2)) => { bits1.iter().zip(bits2.iter()).all(|(i1, i2)| i1 == i2) }, _ => false, } } } impl<Size: ExtInt> Clone for Store<Size> { fn clone(&self) -> Self { match *self { Array(ref vec) => Array(vec.clone()), Bitmap(ref bits) => { Bitmap(bits.iter().map(|&i| i).collect::<Vec<u64>>().into_boxed_slice()) }, } } } struct BitmapIter<'a, Size: ExtInt> { key: usize, bit: u8, bits: &'a Box<[u64]>, marker: PhantomData<Size>, } impl<'a, Size: ExtInt> BitmapIter<'a, Size> { fn new(bits: &'a Box<[u64]>) -> BitmapIter<'a, Size> { BitmapIter { key: 0, bit: Zero::zero(), bits: bits, marker: PhantomData, } } } impl<'a, Size: ExtInt> BitmapIter<'a, Size> { fn move_next(&mut self) { self.bit += 1; if self.bit == 64 { self.bit = 0; self.key += 1; } } } impl<'a, Size: ExtInt> Iterator for BitmapIter<'a, Size> { type Item = Size; fn next(&mut self) -> Option<Size> { loop { if self.key == self.bits.len() { return None; } else { if (self.bits[self.key] & (1u64 << util::cast::<u8, usize>(self.bit))) != 0 { let result = Some(util::cast::<usize, Size>(self.key * 64 + util::cast::<u8, usize>(self.bit))); self.move_next(); return result; } else { self.move_next(); } } } } fn size_hint(&self) -> (usize, Option<usize>) { let min = self.bits.iter().skip(self.key + 1).map(|bits| bits.count_ones()).fold(0, |acc, ones| acc + ones) as usize; (min, Some(min + self.bits[self.key].count_ones() as usize)) } } #[inline] fn bitmap_location<Size: ExtInt>(index: Size) -> (usize, usize) { (key(index), bit(index)) } #[inline] fn key<Size: ExtInt>(index: Size) -> usize { util::cast(index / util::cast(64u8)) } #[inline] fn bit<Size: ExtInt>(index: Size) -> usize { util::cast(index % util::cast(64u8)) }
use modifier::Modifier; use image_lib::FilterType; use super::Image; pub struct Resize { pub width: u32, pub height: u32, } pub struct Crop { pub x: u32, pub y: u32, pub width: u32, pub height: u32, } impl Modifier<Image> for Resize { fn modify(self, image: &mut Image) { image.value = image.value.resize(self.width, self.height, FilterType::Nearest) } } impl Modifier<Image> for Crop { fn modify(self, image: &mut Image) { image.value = image.value.crop(self.x, self.y, self.width, self.height) } }
use ast::*; use name::*; use span::{Span, Spanned, spanned}; use tokenizer::*; use tokenizer::Token::*; // See Chapter 18 for full grammar (p.449) (pdf p.475) macro_rules! spanned { ($node: expr) => (spanned(span!(), $node)); } parser! parse { // XXX: This syntax looks ugly Token; Span; (a, b) { Span::range(a, b) } // Compilation unit ($7.3) root: CompilationUnit { packageDeclaration[pkg] importDeclarations[imports] typeDeclarations[types] => CompilationUnit { package: pkg, imports: imports, types: types }, } // Package declarations ($7.4) packageDeclaration: Option<QualifiedIdentifier> { => None, PACKAGE qualifiedIdentifier[ident] Semicolon => Some(ident), } // Import declarations ($7.5) importDeclaration: ImportDeclaration { IMPORT qualifiedIdentifier[ident] Semicolon => spanned!(ImportDeclaration_::SingleType(ident)), IMPORT qualifiedIdentifierHelperDot[ident] Star Semicolon => spanned!(ImportDeclaration_::OnDemand(QualifiedIdentifier::new(ident))), } importDeclarations: Vec<ImportDeclaration> { => vec![], importDeclarations[mut dcls] importDeclaration[dcl] => { dcls.push(dcl); dcls } } // Top-level type declarations ($7.6) // Note that Joos 1W only supports one of these per file, but I leave that to the // weeding phase so it's easier to output a clearer error message. typeDeclaration: TypeDeclaration { classDeclaration[class] => spanned!(TypeDeclaration_::Class(class)), interfaceDeclaration[interface] => spanned!(TypeDeclaration_::Interface(interface)), } typeDeclarations: Vec<TypeDeclaration> { => vec![], typeDeclarations[mut dcls] typeDeclaration[dcl] => { dcls.push(dcl); dcls } } // Literals ($3.10) literal: Spanned<Literal> { IntegerLiteral(lit) => spanned!(Literal::Integer(lit)), BooleanLiteral(lit) => spanned!(Literal::Boolean(lit)), CharacterLiteral(lit) => spanned!(Literal::Character(lit)), StringLiteral(lit) => spanned!(Literal::String(lit)), NullLiteral => spanned!(Literal::Null), } // Types ($4.1 - $4.3) // Since type is a Rust keyword, use the term ty. // Note that multidimensional arrays are not in Joos 1W. ty: Type { primitiveType[t] => spanned!(Type_::SimpleType(t)), referenceType[t] => t, } primitiveType: SimpleType { BOOLEAN => spanned!(SimpleType_::Boolean), INT => spanned!(SimpleType_::Int), SHORT => spanned!(SimpleType_::Short), CHAR => spanned!(SimpleType_::Char), BYTE => spanned!(SimpleType_::Byte), } referenceType: Type { arrayType[t] => spanned!(Type_::ArrayType(t)), typeName[t] => spanned!(Type_::SimpleType(t)), } arrayType: SimpleType { primitiveType[t] LBracket RBracket => t, expressionNameOrType[q] LBracket RBracket => q.into(), } typeName: SimpleType { expressionNameOrType[q] => q.into(), } // Identifiers ($6.7) identifier: Ident { Identifier(ident) => spanned!(ident), } qualifiedIdentifier: QualifiedIdentifier { qualifiedIdentifierHelper[list] => QualifiedIdentifier::new(list) } qualifiedIdentifierHelperDot: Vec<Ident> { qualifiedIdentifierHelper[list] Dot => list, } qualifiedIdentifierHelper: Vec<Ident> { identifier[ident] => vec![ident], qualifiedIdentifierHelperDot[mut list] identifier[ident] => { list.push(ident); list } } // Classes ($8.1) classDeclaration : Class { modifierList[mods] CLASS identifier[ident] superType[s] interfaceImplementations[impls] classBody[body] => spanned!(Class_ { name: ident, modifiers: mods, extends: s, implements: impls, body: body, }), } superType: Option<QualifiedIdentifier> { => None, EXTENDS qualifiedIdentifier[extension] => Some(extension) } interfaceImplementations: Vec<QualifiedIdentifier> { => vec![], IMPLEMENTS interfaceList[impls] => impls, } // Class body ($8.1.5) classBody: Vec<ClassBodyDeclaration> { LBrace classBodyDeclarations[body] RBrace => body } classBodyDeclarations: Vec<ClassBodyDeclaration> { => vec![], classBodyDeclarations[dcls] Semicolon => { dcls } classBodyDeclarations[mut dcls] classBodyDeclaration[dcl] => { dcls.push(dcl); dcls }, } classBodyDeclaration: ClassBodyDeclaration { fieldDeclaration[dcl] => spanned!(ClassBodyDeclaration_::FieldDeclaration(dcl)), methodDeclaration[dcl] => spanned!(ClassBodyDeclaration_::MethodDeclaration(dcl)), constructorDeclaration[dcl] => spanned!(ClassBodyDeclaration_::ConstructorDeclaration(dcl)), } // Field declaration ($8.3) // Multiple fields per declarations not required. fieldDeclaration: Field { modifierList[mods] ty[t] variableDeclarator[(name, expr)] Semicolon => { spanned!(Field_ { name: name, modifiers: mods, ty: t, initializer: expr, }) } } variableDeclarator: (Ident, Option<Expression>) { identifier[name] => (name, None), identifier[name] Assignment variableInitializer[init] => (name, Some(init)), } voidLiteral: Type { VOID => spanned!(Type_::Void), } methodDeclaration: Method { modifierList[mods] voidLiteral[t] identifier[name] LParen parameterList[params] RParen block[b] => spanned!(Method_ { name: name, modifiers: mods, params: params, return_type: t, body: Some(b) }), modifierList[mods] ty[t] identifier[name] LParen parameterList[params] RParen block[b] => spanned!(Method_ { name: name, modifiers: mods, params: params, return_type: t, body: Some(b) }), methodDeclarationNoBody[dcl] => dcl, } // Method declaration ($8.4) methodDeclarationNoBody: Method { modifierList[mods] voidLiteral[t] identifier[name] LParen parameterList[params] RParen Semicolon => spanned!(Method_ { name: name, modifiers: mods, params: params, return_type: t, body: None }), modifierList[mods] ty[t] identifier[name] LParen parameterList[params] RParen Semicolon => spanned!(Method_ { name: name, modifiers: mods, params: params, return_type: t, body: None }), } // Class constructor ($8.8) constructorDeclaration: Constructor { modifierList[mods] identifier[name] LParen parameterList[params] RParen block[b] => spanned!(Constructor_ { name: name, modifiers: mods, params: params, body: b }), } // Interfaces ($9.1) interfaceDeclaration: Interface { modifierList[mods] INTERFACE identifier[ident] interfaceExtensions[exts] interfaceBody[body] => spanned!(Interface_ { name: ident, modifiers: mods, extends: exts, body: body, }), } interfaceExtensions: Vec<QualifiedIdentifier> { => vec![], EXTENDS interfaceList[impls] => impls, } // Interface body ($9.1.3) interfaceBody: Vec<Method> { LBrace interfaceMemberDeclarations[dcls] RBrace => dcls } interfaceMemberDeclarations: Vec<Method> { => vec![], interfaceMemberDeclarations[dcls] Semicolon => dcls, // Since we're not supposed to support nested type nor interface constants // in Joos 1W, there's only one type of interface member. interfaceMemberDeclarations[mut dcls] methodDeclarationNoBody[dcl] => { dcls.push(dcl); dcls }, } // Common to classes and interfaces interfaceList: Vec<QualifiedIdentifier> { qualifiedIdentifier[i] => vec![i], interfaceList[mut impls] Comma qualifiedIdentifier[i] => { impls.push(i); impls } } modifierList: Vec<Modifier> { => vec![], modifierList[mut list] modifier[m] => { list.push(m); list } } modifier: Modifier { PUBLIC[_] => spanned!(Modifier_::Public), PROTECTED[_] => spanned!(Modifier_::Protected), PRIVATE[_] => spanned!(Modifier_::Private), ABSTRACT[_] => spanned!(Modifier_::Abstract), STATIC[_] => spanned!(Modifier_::Static), FINAL[_] => spanned!(Modifier_::Final), NATIVE[_] => spanned!(Modifier_::Native), } // Method parameters ($8.4.1). The reference refers to them as formal parameters. parameterList: Vec<VariableDeclaration> { => vec![], variableDeclaration[p] => vec![p], parameterList[mut list] Comma variableDeclaration[p] => { list.push(p); list }, } variableDeclaration: VariableDeclaration { ty[t] identifier[name] => spanned!(VariableDeclaration_ { ty: t, name: name }), } // Variable initializers ($8.3) // Note that array initializers ("array data expressions") not in Joos 1W. variableInitializer: Expression { expression[expr] => expr, } // // Expressions ($15) // expressionNameOrType: ExpressionOrType { qualifiedIdentifier[q] => spanned!(ExpressionOrType_::Name(q)), } // Primary expression ($15.8) // Note that class literals are not needed. primary: Expression { primaryNoNewArray[expr] => expr, arrayCreationExpression[expr] => expr, } primaryNoNewArray: Expression { literal[lit] => spanned!(Expression_::Literal(lit.node)), THIS => spanned!(Expression_::This), qualifiedIdentifierHelperDot[q] THIS => { let ident = QualifiedIdentifier::new(q); spanned!(Expression_::QualifiedThis(ident)) }, LParen expressionNameOrType[expr] RParen => expr.into(), LParen expressionNotName[expr] RParen => expr, classInstanceCreationExpression[expr] => expr, fieldAccess[expr] => expr, methodInvocation[expr] => expr, arrayAccess[expr] => expr, } // Class instance creation expression ($15.9) classInstanceCreationExpression: Expression { NEW qualifiedIdentifier[q] LParen argumentList[args] RParen => spanned!(Expression_::NewStaticClass(q, args)), } argumentList: Vec<Expression> { => vec![], expression[expr] => vec![expr], argumentList[mut args] Comma expression[expr] => { args.push(expr); args }, } // Array creation expression ($15.10) // Note that Joos 1W only has 1D arrays and does not support array initializers. arrayCreationExpression: Expression { NEW primitiveType[t] LBracket expression[expr] RBracket => spanned!(Expression_::NewArray(t, box expr)), NEW typeName[t] LBracket expression[expr] RBracket => spanned!(Expression_::NewArray(t, box expr)), } // Field access expressions ($15.11) // Super field access not required in Joos 1W fieldAccess: Expression { primary[expr] Dot identifier[ident] => spanned!(Expression_::FieldAccess(box expr, ident)), } // Method invocation expressions ($15.12) methodInvocation: Expression { expressionNameOrType[node!(ExpressionOrType_::Name(ids))] LParen argumentList[args] RParen => { spanned!(Expression_::NamedMethodInvocation(ids, args)) } primary[expr] Dot identifier[ident] LParen argumentList[args] RParen => spanned!(Expression_::MethodInvocation(box expr, ident, args)), } // Array access expressions ($15.13) arrayAccess: Expression { expressionNameOrType[name] LBracket expression[expr] RBracket => spanned!(Expression_::ArrayAccess(box name.into(), box expr)), primaryNoNewArray[primary] LBracket expression[expr] RBracket => spanned!(Expression_::ArrayAccess(box primary, box expr)), } // Postfix expression (%15.14) // No -- or ++ in Joss 1W postfixExpression: Expression { primary[expr] => expr, expressionNameOrType[expr] => expr.into(), } // Unary operators ($15.15) unaryExpression: Expression { #[overriding] Minus IntegerLiteral(lit) => spanned!(Expression_::Literal(Literal::Integer(-lit))), Minus unaryExpression[expr] => spanned!(Expression_::Prefix(PrefixOperator::Minus, box expr)), unaryExpressionNotPlusMinus[expr] => expr } // Separate rule due to casting rules. unaryExpressionNotPlusMinus: Expression { castExpression[expr] => expr, postfixExpression[expr] => expr, Bang unaryExpression[expr] => spanned!(Expression_::Prefix(PrefixOperator::Not, box expr)), } // Casting ($15.16) // Note that the grammar in the ref appears to have a mistake (I don't think // there should be an Dim_opt since it would make it a reference type, plus // it doesn't make sense to cast something that supports unary minus to an // array type.) castExpression: Expression { LParen primitiveType[t] RParen unaryExpression[expr] => spanned!(Expression_::Cast(spanned(t.span, Type_::SimpleType(t)), box expr)), LParen arrayType[t] RParen unaryExpressionNotPlusMinus[expr] => spanned!(Expression_::Cast(spanned(t.span, Type_::ArrayType(t)), box expr)), LParen expressionNameOrType[q] RParen unaryExpressionNotPlusMinus[expr] => spanned!(Expression_::Cast(q.into(), box expr)), } // Multiplicative expressions ($15.17) multiplicativeExpression: Expression { unaryExpression[expr] => expr, multiplicativeExpression[expr1] multiplicativeOperator[op] unaryExpression[expr2] => spanned!(Expression_::Infix(op, box expr1, box expr2)), } multiplicativeOperator: InfixOperator { Star => InfixOperator::Mult, Slash => InfixOperator::Div, Percent => InfixOperator::Modulo, } // Additive expressions ($15.18) additiveExpression: Expression { multiplicativeExpression[expr] => expr, additiveExpression[expr1] Plus multiplicativeExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Plus, box expr1, box expr2)), additiveExpression[expr1] Minus multiplicativeExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Minus, box expr1, box expr2)), } // Shift operators ($15.19) // Not supported in Joos 1W, so we skip shiftExpression and go directly // from relationalExpression to additiveExpression. // Relational operators ($15.20) relationalExpression: Expression { additiveExpression[expr] => expr, relationalExpression[expr1] comparisonOperator[op] additiveExpression[expr2] => spanned!(Expression_::Infix(op, box expr1, box expr2)), relationalExpression[expr] INSTANCEOF referenceType[t] => spanned!(Expression_::InstanceOf(box expr, t)), } comparisonOperator: InfixOperator { LessThan => InfixOperator::LessThan, GreaterThan => InfixOperator::GreaterThan, LessEqual => InfixOperator::LessEqual, GreaterEqual => InfixOperator::GreaterEqual, } // Equality operator ($15.21) equalityExpression: Expression { relationalExpression[expr] => expr, equalityExpression[expr1] Equals relationalExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Equals, box expr1, box expr2)), equalityExpression[expr1] NotEquals relationalExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::NotEquals, box expr1, box expr2)), } // Logical operators ($15.22) andExpression: Expression { equalityExpression[expr] => expr, andExpression[expr1] And equalityExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::EagerAnd, box expr1, box expr2)), } exclusiveOrExpression: Expression { andExpression[expr] => expr, exclusiveOrExpression[expr1] Xor andExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Xor, box expr1, box expr2)), } inclusiveOrExpression: Expression { exclusiveOrExpression[expr] => expr, inclusiveOrExpression[expr1] Or exclusiveOrExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::EagerOr, box expr1, box expr2)), } // Skipping the ternary operator ($15.25) // Conditional operators ($15.23) ($15.24) conditionalAndExpression: Expression { inclusiveOrExpression[expr] => expr, conditionalAndExpression[expr1] AndAnd inclusiveOrExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::LazyAnd, box expr1, box expr2)), } conditionalOrExpression: Expression { conditionalAndExpression[expr] => expr, conditionalOrExpression[expr1] OrOr conditionalAndExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::LazyOr, box expr1, box expr2)), } // Assignment operator ($15.26) assignmentExpression: Expression { conditionalOrExpression[expr] => expr, assignment[a] => a, } assignment: Expression { conditionalOrExpression[lhs] Assignment assignmentExpression[expr] => spanned!(Expression_::Assignment(box lhs, box expr)), } // Expressions: expression: Expression { assignmentExpression[expr] => expr, } // Same as `expression`, but can't expand into just `expressionName`. // All the rules are inlined. expressionNotName: Expression { #[overriding] Minus IntegerLiteral(lit) => spanned!(Expression_::Literal(Literal::Integer(-lit))), Minus unaryExpression[expr] => spanned!(Expression_::Prefix(PrefixOperator::Minus, box expr)), castExpression[expr] => expr, primary[expr] => expr, Bang unaryExpression[expr] => spanned!(Expression_::Prefix(PrefixOperator::Not, box expr)), multiplicativeExpression[expr1] multiplicativeOperator[op] unaryExpression[expr2] => spanned!(Expression_::Infix(op, box expr1, box expr2)), additiveExpression[expr1] Plus multiplicativeExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Plus, box expr1, box expr2)), additiveExpression[expr1] Minus multiplicativeExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Minus, box expr1, box expr2)), relationalExpression[expr1] comparisonOperator[op] additiveExpression[expr2] => spanned!(Expression_::Infix(op, box expr1, box expr2)), relationalExpression[expr] INSTANCEOF referenceType[t] => spanned!(Expression_::InstanceOf(box expr, t)), equalityExpression[expr1] Equals relationalExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Equals, box expr1, box expr2)), equalityExpression[expr1] NotEquals relationalExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::NotEquals, box expr1, box expr2)), andExpression[expr1] And equalityExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::EagerAnd, box expr1, box expr2)), exclusiveOrExpression[expr1] Xor andExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::Xor, box expr1, box expr2)), inclusiveOrExpression[expr1] Or exclusiveOrExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::EagerOr, box expr1, box expr2)), conditionalAndExpression[expr1] AndAnd inclusiveOrExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::LazyAnd, box expr1, box expr2)), conditionalOrExpression[expr1] OrOr conditionalAndExpression[expr2] => spanned!(Expression_::Infix(InfixOperator::LazyOr, box expr1, box expr2)), assignment[a] => a, } // Block ($14.2) block: Block { LBrace blockStatements[stmts] RBrace => spanned!(Block_ { stmts: stmts }) } blockStatements: Vec<BlockStatement> { => vec![], blockStatements[mut stmts] blockStatement[stmt] => { stmts.push(stmt); stmts } } blockStatement: BlockStatement { localVariableDeclaration[local] Semicolon => spanned!(BlockStatement_::LocalVariable(local)), statement[s] => spanned!(BlockStatement_::Statement(s)), } // Local declarations ($14.4) localVariableDeclaration: LocalVariable { variableDeclaration[var] Assignment variableInitializer[init] => spanned!(LocalVariable_ { variable: var, initializer: init }) } // Statements ($14.5) statement: Statement { block[b] => spanned!(Statement_::Block(b)), #[no_reduce(ELSE)] IF LParen expression[test] RParen statement[s1] => spanned!(Statement_::If(test, box s1, None)), IF LParen expression[test] RParen statement[s1] ELSE statement[s2] => spanned!(Statement_::If(test, box s1, Some(box s2))), WHILE LParen expression[test] RParen statement[body] => spanned!(Statement_::While(test, box body)), FOR LParen maybeStatementExpression[f1] Semicolon maybeExpression[f2] Semicolon maybeStatementExpression[f3] RParen statement[body] => spanned!(Statement_::For(f1, f2, f3, box body)), FOR LParen localVariableDeclaration[f1] Semicolon maybeExpression[f2] Semicolon maybeStatementExpression[f3] RParen statement[body] => spanned!(Statement_::ForDecl(f1, f2, f3, box body)), Semicolon => spanned!(Statement_::Empty), statementExpression[expr] Semicolon => spanned!(Statement_::Expression(expr)), RETURN expression[expr] Semicolon => spanned!(Statement_::Return(Some(expr))), RETURN Semicolon => spanned!(Statement_::Return(None)), } statementExpression: Expression { assignment[e] => e, methodInvocation[e] => e, classInstanceCreationExpression[e] => e, } maybeStatementExpression: Option<Expression> { statementExpression[e] => Some(e), => None, } maybeExpression: Option<Expression> { expression[e] => Some(e), => None, } } pub fn make_ast<I: Iterator<Item=(Token, Span)>>(tokens: I) -> Result<CompilationUnit, (Option<(Token, Span)>, &'static str)> { parse(tokens) } // An intermediate type for parsing. Represents syntax that can be interpreted as // either an expression or a type. #[derive(Debug)] enum ExpressionOrType_ { Name(QualifiedIdentifier), } type ExpressionOrType = Spanned<ExpressionOrType_>; trait IsExpressionOrType { fn convert(ExpressionOrType) -> Self; } impl IsExpressionOrType for Expression { fn convert(x: ExpressionOrType) -> Expression { match x.node { ExpressionOrType_::Name(n) => spanned(x.span, Expression_::Name(n)), } } } impl IsExpressionOrType for SimpleType { fn convert(x: ExpressionOrType) -> SimpleType { match x.node { ExpressionOrType_::Name(n) => spanned(x.span, SimpleType_::Other(n)), } } } impl IsExpressionOrType for Type { fn convert(x: ExpressionOrType) -> Type { spanned(x.span, Type_::SimpleType(x.into())) } } impl ExpressionOrType { pub fn into<T: IsExpressionOrType>(self) -> T { IsExpressionOrType::convert(self) } }
use crate::atomicmin::AtomicMin; use crate::error::PngError; use crate::PngResult; use miniz_oxide::deflate::core::*; pub(crate) fn compress_to_vec_oxipng( input: &[u8], level: u8, window_bits: i32, strategy: i32, max_size: &AtomicMin, deadline: &crate::Deadline, ) -> PngResult<Vec<u8>> { // The comp flags function sets the zlib flag if the window_bits parameter is > 0. let flags = create_comp_flags_from_zip_params(level.into(), window_bits, strategy); let mut compressor = CompressorOxide::new(flags); // if max size is known, then expect that much data (but no more than input.len()) let mut output = Vec::with_capacity(max_size.get().unwrap_or(input.len() / 2).min(input.len())); // # Unsafe // We trust compress to not read the uninitialized bytes. unsafe { let cap = output.capacity(); output.set_len(cap); } let mut in_pos = 0; let mut out_pos = 0; loop { let (status, bytes_in, bytes_out) = compress( &mut compressor, &input[in_pos..], &mut output[out_pos..], TDEFLFlush::Finish, ); out_pos += bytes_out; in_pos += bytes_in; match status { TDEFLStatus::Done => { output.truncate(out_pos); break; } TDEFLStatus::Okay => { if let Some(max) = max_size.get() { if output.len() > max { return Err(PngError::DeflatedDataTooLong(output.len())); } } if deadline.passed() { return Err(PngError::TimedOut); } // We need more space, so extend the vector. if output.len().saturating_sub(out_pos) < 30 { let current_len = output.len(); output.reserve(current_len); // # Unsafe // We trust compress to not read the uninitialized bytes. unsafe { let cap = output.capacity(); output.set_len(cap); } } } // Not supposed to happen unless there is a bug. _ => panic!("Bug! Unexpectedly failed to compress!"), } } Ok(output) }
use crate::{ arch::Architecture, preload_interface::syscall_patch_hook, remote_code_ptr::RemoteCodePtr, remote_ptr::{RemotePtr, Void}, session::{address_space::address_space, task::record_task::RecordTask}, }; use std::{ collections::{HashMap, HashSet}, ffi::OsStr, }; const MAX_VDSO_SIZE: usize = 16384; const VDSO_ABSOLUTE_ADDRESS: usize = 0xffffe000; #[derive(Clone)] pub struct MonkeyPatcher { pub x86_vsyscall: RemotePtr<Void>, /// The list of pages we've allocated to hold our extended jumps. pub extended_jump_pages: Vec<ExtendedJumpPage>, /// Syscalls in the VDSO that we patched to be direct syscalls. These can /// always be safely patched to jump to the syscallbuf. pub patched_vdso_syscalls: HashSet<RemoteCodePtr>, /// Addresses/lengths of syscallbuf stubs. pub syscallbuf_stubs: HashMap<RemotePtr<u8>, usize>, /// The list of supported syscall patches obtained from the preload /// library. Each one matches a specific byte signature for the instruction(s) /// after a syscall instruction. syscall_hooks: Vec<syscall_patch_hook>, /// The addresses of the instructions following syscalls that we've tried /// (or are currently trying) to patch. tried_to_patch_syscall_addresses: HashSet<RemoteCodePtr>, } pub enum MmapMode { MmapExec, MmapSyscall, } #[derive(Clone)] pub struct ExtendedJumpPage { pub addr: RemotePtr<u8>, pub allocated: usize, } impl ExtendedJumpPage { pub fn new(addr: RemotePtr<u8>) -> Self { Self { addr, allocated: 0 } } } /// A class encapsulating patching state. There is one instance of this /// class per tracee address space. Currently this class performs the following /// tasks: /// /// 1) Patch the VDSO's user-space-only implementation of certain system calls /// (e.g. gettimeofday) to do a proper kernel system call instead, so rr can /// trap and record it (x86-64 only). /// /// 2) Patch the VDSO __kernel_vsyscall fast-system-call stub to redirect to /// our syscall hook in the preload library (x86 only). /// /// 3) Patch syscall instructions whose following instructions match a known /// pattern to call the syscall hook. /// /// MonkeyPatcher only runs during recording, never replay. impl MonkeyPatcher { pub fn new() -> MonkeyPatcher { MonkeyPatcher { x86_vsyscall: Default::default(), extended_jump_pages: vec![], patched_vdso_syscalls: Default::default(), syscallbuf_stubs: Default::default(), syscall_hooks: vec![], tried_to_patch_syscall_addresses: Default::default(), } } /// Apply any necessary patching immediately after exec. /// In this hook we patch everything that doesn't depend on the preload /// library being loaded. pub fn patch_after_exec(_t: &RecordTask) { unimplemented!() } pub fn patch_at_preload_init(&self, t: &RecordTask) { // NB: the tracee can't be interrupted with a signal while // we're processing the rdcall, because it's masked off all // signals. rd_arch_function_selfless!(patch_at_preload_init_arch, t.arch(), t, self); } /// Try to patch the syscall instruction that |t| just entered. If this /// returns false, patching failed and the syscall should be processed /// as normal. If this returns true, patching succeeded and the syscall /// was aborted; ip() has been reset to the start of the patched syscall, /// and execution should resume normally to execute the patched code. /// Zero or more mapping operations are also recorded to the trace and must /// be replayed. pub fn try_patch_syscall(_t: &RecordTask) -> bool { unimplemented!() } pub fn init_dynamic_syscall_patching( _t: &RecordTask, _syscall_patch_hook_count: usize, _syscall_patch_hooks: RemotePtr<syscall_patch_hook>, ) { unimplemented!() } /// Try to allocate a stub from the sycall patching stub buffer. Returns null /// if there's no buffer or we've run out of free stubs. pub fn allocate_stub(_t: &RecordTask, _bytes: usize) -> RemotePtr<u8> { unimplemented!() } /// Apply any necessary patching immediately after an mmap. We use this to /// patch libpthread.so. pub fn patch_after_mmap( _t: &RecordTask, _start: RemotePtr<Void>, _size: usize, _offset_pages: usize, _child_fd: i32, _mode: MmapMode, ) { unimplemented!() } pub fn is_jump_stub_instruction(_p: RemoteCodePtr) -> bool { unimplemented!() } } fn patch_at_preload_init_arch<Arch: Architecture>(_t: &RecordTask, _patcher: &MonkeyPatcher) { unimplemented!() } struct VdsoReader; /// @TODO Remove struct ElfReader; /// @TODO Remove struct SymbolTable; fn write_and_record_bytes(_t: &RecordTask, _child_addr: RemotePtr<Void>, _buf: &[u8]) { unimplemented!() } fn write_and_record_mem<T>(_t: &RecordTask, _child_addr: RemotePtr<T>, _vals: &[T]) { unimplemented!() } /// RecordSession sets up an LD_PRELOAD environment variable with an entry /// SYSCALLBUF_LIB_FILENAME_PADDED (and, if enabled, an LD_AUDIT environment /// variable with an entry RTLDAUDIT_LIB_FILENAME_PADDED) which is big enough to /// hold either the 32-bit or 64-bit preload/audit library file names. /// Immediately after exec we enter this function, which patches the environment /// variable value with the correct library name for the task's architecture. /// /// It's possible for this to fail if a tracee alters the LD_PRELOAD value /// and then does an exec. That's just too bad. If we ever have to handle that, /// we should modify the environment passed to the exec call. This function /// failing isn't necessarily fatal; a tracee might not rely on the functions /// overridden by the preload library, or might override them itself (e.g. /// because we're recording an rr replay). //// fn setup_library_path_arch<Arch: Architecture>( _t: &RecordTask, _env_var: &OsStr, _soname_base: &OsStr, _soname_padded: &OsStr, _soname_32: &OsStr, ) { unimplemented!() } fn setup_preload_library_path<Arch: Architecture>(_t: &RecordTask) { unimplemented!() } fn setup_audit_library_path<Arch: Architecture>(_t: &RecordTask) { unimplemented!() } fn patch_syscall_with_hook_arch<Arch: Architecture>( _patcher: &MonkeyPatcher, _t: &RecordTask, _hook: &syscall_patch_hook, ) -> bool { unimplemented!() } fn substitute<Arch: Architecture>( _buffer: &[u8], _return_addr: u64, _trampoline_relative_addr: u64, ) { unimplemented!() } fn substitute_extended_jump<Arch: Architecture>( _buffer: &[u8], _patch_addr: u64, _return_addr: u64, _target_addr: u64, ) { unimplemented!() } /// Allocate an extended jump in an extended jump page and return its address. /// The resulting address must be within 2G of from_end, and the instruction /// there must jump to to_start. fn allocate_extended_jump( _t: &RecordTask, _pages: Vec<ExtendedJumpPage>, _from_end: RemotePtr<u8>, ) -> RemotePtr<u8> { unimplemented!() } /// Some functions make system calls while storing local variables in memory /// below the stack pointer. We need to decrement the stack pointer by /// some "safety zone" amount to get clear of those variables before we make /// a call instruction. So, we allocate a stub per patched callsite, and jump /// from the callsite to the stub. The stub decrements the stack pointer, /// calls the appropriate syscall hook function, reincrements the stack pointer, /// and jumps back to immediately after the patched callsite. /// /// It's important that gdb stack traces work while a thread is stopped in the /// syscallbuf code. To ensure that the above manipulations don't foil gdb's /// stack walking code, we add CFI data to all the stubs. To ease that, the /// stubs are written in assembly and linked into the preload library. /// /// On x86-64 with ASLR, we need to be able to patch a call to a stub from /// sites more than 2^31 bytes away. We only have space for a 5-byte jump /// instruction. So, we allocate "extender pages" --- pages of memory within /// 2GB of the patch site, that contain the stub code. We don't really need this /// on x86, but we do it there too for consistency. fn patch_syscall_with_hook_x86ish( _patcher: &MonkeyPatcher, _t: &RecordTask, _hook: syscall_patch_hook, ) -> bool { unimplemented!() } fn patch_syscall_with_hook( _patcher: &MonkeyPatcher, _t: &RecordTask, _hook: &syscall_patch_hook, ) -> bool { unimplemented!() } fn task_safe_for_syscall_patching( _t: &RecordTask, _start: RemoteCodePtr, _end: RemoteCodePtr, ) -> bool { unimplemented!() } fn safe_for_syscall_patching(_start: RemoteCodePtr, _end: RemoteCodePtr, _exclude: &RecordTask) { unimplemented!() } /// Return true iff |addr| points to a known |__kernel_vsyscall()| /// implementation. fn is_kernel_vsyscall(_t: &RecordTask, _addr: RemotePtr<Void>) -> bool { unimplemented!() } /// Return the address of a recognized |__kernel_vsyscall()| /// implementation in |t|'s address space. fn locate_and_verify_kernel_vsyscall( _t: &RecordTask, _reader: &ElfReader, _syms: &SymbolTable, ) -> RemotePtr<Void> { unimplemented!() } /// VDSOs are filled with overhead critical functions related to getting the /// time and current CPU. We need to ensure that these syscalls get redirected /// into actual trap-into-the-kernel syscalls so rr can intercept them. fn patch_after_exec_arch<Arch: Architecture>(_t: &RecordTask, _patcher: &MonkeyPatcher) { unimplemented!() } struct NamedSyscall<'a> { pub name: &'a OsStr, pub syscall_number: i32, } fn erase_section(_t: &RecordTask, _reader: &VdsoReader, _name: &OsStr) { unimplemented!() } fn obliterate_debug_info(_t: &RecordTask, _reader: &VdsoReader) { unimplemented!() } fn resolve_address( _reader: &ElfReader, _elf_addr: usize, _map_start: RemotePtr<Void>, _map_size: usize, _map_offset_pages: usize, ) -> RemotePtr<Void> { unimplemented!() } fn set_and_record_bytes( _t: &RecordTask, _reader: &ElfReader, _elf_addr: usize, _bytes: &[u8], _map_start: RemotePtr<Void>, _map_size: usize, _map_offset_pages: usize, ) { unimplemented!() } /// Patch _dl_runtime_resolve_(fxsave,xsave,xsavec) to clear "FDP Data Pointer" /// register so that CPU-specific behaviors involving that register don't leak /// into stack memory. fn patch_dl_runtime_resolve( _patcher: &MonkeyPatcher, _t: &RecordTask, _reader: &ElfReader, _elf_addr: usize, _bytes: &[u8], _map_start: RemotePtr<Void>, _map_size: usize, _map_offset_pages: usize, ) { unimplemented!() } fn file_may_need_instrumentation(_map: &address_space::Mapping) -> bool { unimplemented!() }
#![allow(dead_code)] ///! ///! This module holds utility functions for vector manipulation. ///! This includes sequences, arrays, and polynomials. ///! use crate::prelude::*; use alloc::vec::Vec; #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Pad (append) a slice `v` to length `l` with `T::default()`. pub(crate) fn pad<T: Numeric + Copy>(v: &[T], l: usize) -> Vec<T> { let mut out = v.to_vec(); for _ in out.len()..l { out.push(T::default()); } out } #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Generate a `Vec<T>` of length `l`, containing the first `l` elements of `v`. pub(crate) fn make_fixed_length<T: Numeric + Copy>(v: &[T], l: usize) -> Vec<T> { let mut out = vec![T::default(); l]; for (a, &b) in out.iter_mut().zip(v.iter()) { *a = b; } out } #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Create a monomial `Vec<T>` with value `c` at position `d`. pub(crate) fn monomial<T>(c: T, d: usize) -> Vec<T> where T: Numeric + Copy, { let mut p = vec![T::default(); d + 1]; p[d] = c; p } #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Return vectors `x` and `y`, padded to maximum length of the two. pub(crate) fn normalize<T: Numeric + Copy>(x: &[T], y: &[T]) -> (Vec<T>, Vec<T>) { let max_len = core::cmp::max(x.len(), y.len()); (pad(x, max_len), pad(y, max_len)) } #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Return the leading coefficient (value) of `x` that's non-zero. /// Returns a (index, coefficient)-Tuple. pub(crate) fn leading_coefficient<T: Numeric + Copy>(x: &[T]) -> (usize, T) { let zero = T::default(); let mut degree: usize = 0; let mut coefficient = T::default(); for (i, &c) in x.iter().enumerate() { if !c.equal(zero) { degree = i; coefficient = c; } } (degree, coefficient) } #[inline] #[cfg_attr(feature = "use_attributes", not_hacspec)] /// Returns `true` if `v` is all zero, and `false` otherwise. /// Note: this is not constant-time. pub(crate) fn is_zero<T: Numeric + Copy>(v: &[T]) -> bool { for &x in v { if !x.equal(T::default()) { return false; } } true }
use files::Fd; use fuse::FileType; use nix::sys::xattr as _xattr; use nix::Result; use readlink::readlinkat; use std::ffi::OsStr; pub fn setxattr(fd: &Fd, kind: FileType, name: &OsStr, value: &[u8], flags: u32) -> Result<()> { if kind == FileType::Symlink { let path = readlinkat(fd.raw())?; _xattr::lsetxattr(path.as_os_str(), name, value, flags as i32) } else { _xattr::setxattr(fd.path().as_str(), name, value, flags as i32) } } pub fn removexattr(fd: &Fd, kind: FileType, name: &OsStr) -> Result<()> { if kind == FileType::Symlink { let path = readlinkat(fd.raw())?; _xattr::lremovexattr(path.as_os_str(), name) } else { _xattr::removexattr(fd.path().as_str(), name) } } pub fn listxattr(fd: &Fd, kind: FileType, name: &mut [u8]) -> Result<usize> { if kind == FileType::Symlink { let path = readlinkat(fd.raw())?; _xattr::llistxattr(path.as_os_str(), name) } else { _xattr::listxattr(fd.path().as_str(), name) } } pub fn getxattr(fd: &Fd, kind: FileType, name: &OsStr, buf: &mut [u8]) -> Result<usize> { if kind == FileType::Symlink { let path = readlinkat(fd.raw())?; _xattr::lgetxattr(path.as_os_str(), name, buf) } else { _xattr::getxattr(fd.path().as_str(), name, buf) } }
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use libc; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct ActionGroup(Object<ffi::GActionGroup, ffi::GActionGroupInterface>); match fn { get_type => || ffi::g_action_group_get_type(), } } pub trait ActionGroupExt { fn action_added(&self, action_name: &str); fn action_enabled_changed(&self, action_name: &str, enabled: bool); fn action_removed(&self, action_name: &str); fn action_state_changed(&self, action_name: &str, state: &glib::Variant); fn activate_action<'a, P: Into<Option<&'a glib::Variant>>>(&self, action_name: &str, parameter: P); fn change_action_state(&self, action_name: &str, value: &glib::Variant); fn get_action_enabled(&self, action_name: &str) -> bool; fn get_action_parameter_type(&self, action_name: &str) -> Option<glib::VariantType>; fn get_action_state(&self, action_name: &str) -> Option<glib::Variant>; fn get_action_state_hint(&self, action_name: &str) -> Option<glib::Variant>; fn get_action_state_type(&self, action_name: &str) -> Option<glib::VariantType>; fn has_action(&self, action_name: &str) -> bool; fn list_actions(&self) -> Vec<String>; fn connect_action_added<F: Fn(&Self, &str) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_action_enabled_changed<F: Fn(&Self, &str, bool) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_action_removed<F: Fn(&Self, &str) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_action_state_changed<F: Fn(&Self, &str, &glib::Variant) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<ActionGroup> + IsA<glib::object::Object>> ActionGroupExt for O { fn action_added(&self, action_name: &str) { unsafe { ffi::g_action_group_action_added(self.to_glib_none().0, action_name.to_glib_none().0); } } fn action_enabled_changed(&self, action_name: &str, enabled: bool) { unsafe { ffi::g_action_group_action_enabled_changed(self.to_glib_none().0, action_name.to_glib_none().0, enabled.to_glib()); } } fn action_removed(&self, action_name: &str) { unsafe { ffi::g_action_group_action_removed(self.to_glib_none().0, action_name.to_glib_none().0); } } fn action_state_changed(&self, action_name: &str, state: &glib::Variant) { unsafe { ffi::g_action_group_action_state_changed(self.to_glib_none().0, action_name.to_glib_none().0, state.to_glib_none().0); } } fn activate_action<'a, P: Into<Option<&'a glib::Variant>>>(&self, action_name: &str, parameter: P) { let parameter = parameter.into(); let parameter = parameter.to_glib_none(); unsafe { ffi::g_action_group_activate_action(self.to_glib_none().0, action_name.to_glib_none().0, parameter.0); } } fn change_action_state(&self, action_name: &str, value: &glib::Variant) { unsafe { ffi::g_action_group_change_action_state(self.to_glib_none().0, action_name.to_glib_none().0, value.to_glib_none().0); } } fn get_action_enabled(&self, action_name: &str) -> bool { unsafe { from_glib(ffi::g_action_group_get_action_enabled(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn get_action_parameter_type(&self, action_name: &str) -> Option<glib::VariantType> { unsafe { from_glib_none(ffi::g_action_group_get_action_parameter_type(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn get_action_state(&self, action_name: &str) -> Option<glib::Variant> { unsafe { from_glib_full(ffi::g_action_group_get_action_state(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn get_action_state_hint(&self, action_name: &str) -> Option<glib::Variant> { unsafe { from_glib_full(ffi::g_action_group_get_action_state_hint(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn get_action_state_type(&self, action_name: &str) -> Option<glib::VariantType> { unsafe { from_glib_none(ffi::g_action_group_get_action_state_type(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn has_action(&self, action_name: &str) -> bool { unsafe { from_glib(ffi::g_action_group_has_action(self.to_glib_none().0, action_name.to_glib_none().0)) } } fn list_actions(&self) -> Vec<String> { unsafe { FromGlibPtrContainer::from_glib_full(ffi::g_action_group_list_actions(self.to_glib_none().0)) } } fn connect_action_added<F: Fn(&Self, &str) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &str) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "action-added", transmute(action_added_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_action_enabled_changed<F: Fn(&Self, &str, bool) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &str, bool) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "action-enabled-changed", transmute(action_enabled_changed_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_action_removed<F: Fn(&Self, &str) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &str) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "action-removed", transmute(action_removed_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } fn connect_action_state_changed<F: Fn(&Self, &str, &glib::Variant) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self, &str, &glib::Variant) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "action-state-changed", transmute(action_state_changed_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn action_added_trampoline<P>(this: *mut ffi::GActionGroup, action_name: *mut libc::c_char, f: glib_ffi::gpointer) where P: IsA<ActionGroup> { callback_guard!(); let f: &&(Fn(&P, &str) + 'static) = transmute(f); f(&ActionGroup::from_glib_borrow(this).downcast_unchecked(), &String::from_glib_none(action_name)) } unsafe extern "C" fn action_enabled_changed_trampoline<P>(this: *mut ffi::GActionGroup, action_name: *mut libc::c_char, enabled: glib_ffi::gboolean, f: glib_ffi::gpointer) where P: IsA<ActionGroup> { callback_guard!(); let f: &&(Fn(&P, &str, bool) + 'static) = transmute(f); f(&ActionGroup::from_glib_borrow(this).downcast_unchecked(), &String::from_glib_none(action_name), from_glib(enabled)) } unsafe extern "C" fn action_removed_trampoline<P>(this: *mut ffi::GActionGroup, action_name: *mut libc::c_char, f: glib_ffi::gpointer) where P: IsA<ActionGroup> { callback_guard!(); let f: &&(Fn(&P, &str) + 'static) = transmute(f); f(&ActionGroup::from_glib_borrow(this).downcast_unchecked(), &String::from_glib_none(action_name)) } unsafe extern "C" fn action_state_changed_trampoline<P>(this: *mut ffi::GActionGroup, action_name: *mut libc::c_char, value: *mut glib_ffi::GVariant, f: glib_ffi::gpointer) where P: IsA<ActionGroup> { callback_guard!(); let f: &&(Fn(&P, &str, &glib::Variant) + 'static) = transmute(f); f(&ActionGroup::from_glib_borrow(this).downcast_unchecked(), &String::from_glib_none(action_name), &from_glib_borrow(value)) }
pub mod aabb; pub mod bvh; pub mod camera; pub mod hittable; pub mod material; pub mod onb; pub mod pdf; pub mod ray; pub mod renderer; pub mod scenes; pub mod texture; pub mod util; pub mod vec3;
extern crate clap; extern crate zip; use std::fs; use std::io; use std::path; use std::process; use clap::{App, Arg}; #[cfg(target_os = "linux")] static DEV_PLATFORM: &str = "linux"; #[cfg(target_os = "macos")] static DEV_PLATFORM: &str = "macos"; #[cfg(target_os = "windows")] static DEV_PLATFORM: &str = "win32"; fn main() { let (download_dir, sdk_version) = get_configuration(); download_and_unpack( &SpatialPackageSource::WorkerSdk, "c-static-x86_64-msvc_mt-win32", &sdk_version, &format!("{}/win", &download_dir), ) .expect("Could not download package"); download_and_unpack( &SpatialPackageSource::WorkerSdk, "c-static-x86_64-clang_libcpp-macos", &sdk_version, &format!("{}/macos", &download_dir), ) .expect("Could not download package"); download_and_unpack( &SpatialPackageSource::WorkerSdk, "c-static-x86_64-gcc_libstdcpp_pic-linux", &sdk_version, &format!("{}/linux", &download_dir), ) .expect("Could not download package"); download_and_unpack( &SpatialPackageSource::Schema, "standard_library", &sdk_version, &format!("{}/std-lib", &download_dir), ) .expect("Could not download package"); download_and_unpack( &SpatialPackageSource::Tools, format!("schema_compiler-x86_64-{}", DEV_PLATFORM).as_ref(), &sdk_version, &format!("{}/schema-compiler", &download_dir), ) .expect("Could not download package"); download_and_unpack( &SpatialPackageSource::Tools, format!("snapshot_converter-x86_64-{}", DEV_PLATFORM).as_ref(), &sdk_version, &format!("{}/snapshot-converter", &download_dir), ) .expect("Could not download package"); } enum SpatialPackageSource { WorkerSdk, Tools, Schema, } impl SpatialPackageSource { fn to_str(&self) -> &str { use crate::SpatialPackageSource::*; match *self { WorkerSdk => "worker_sdk", Tools => "tools", Schema => "schema", } } } fn get_configuration() -> (String, String) { let matches = App::new("Spatial OS SDK Downloader") .author("Jamie Brynes <jamiebrynes7@gmail.com>") .about("Downloads SDK packages used in the SpatialOS SDK for Rust") .arg( Arg::with_name("download_location") .short("d") .long("download_location") .value_name("DOWNLOAD_DIR") .help("Download directory location. Relative to the current working directory.") .takes_value(true) .required(true), ) .arg( Arg::with_name("sdk_version") .short("s") .long("sdk-version") .value_name("SDK_VERSION") .help("SDK version to download") .takes_value(true) .required(true), ) .get_matches(); let download_dir = matches.value_of("download_location").unwrap().to_string(); let sdk_version = matches.value_of("sdk_version").unwrap().to_string(); (download_dir, sdk_version) } /// Downloads and unpacks a Spatial package into a specified directory. /// /// * package_source - the source of the package /// * package_name - the name of the package /// * sdk_version - the Spatial SDK version /// * target_directory - the target directory to unpack to /// /// * returns - an error if the operation could not be completed, empty otherwise fn download_and_unpack( package_source: &SpatialPackageSource, package_name: &str, sdk_version: &str, target_directory: &str, ) -> Result<(), io::Error> { let current_dir = std::env::current_dir().expect("Could not find current working directory."); // Clean target directory. fs::remove_dir_all(target_directory).unwrap_or(()); fs::create_dir_all(target_directory)?; // Create temporary directory. let mut tmp_dir = current_dir.clone(); tmp_dir.push("tmp"); fs::create_dir_all(&tmp_dir)?; let mut tmp_file = tmp_dir.clone(); tmp_file.push(package_name); println!("Downloading {}.", package_name); download_package( package_source, package_name, sdk_version, tmp_file.to_str().unwrap(), ); println!("Unpacking {} to {}.", package_name, target_directory); unpack_package(tmp_file.to_str().unwrap(), target_directory)?; // Clean temp directory. fs::remove_dir_all(&tmp_dir)?; Ok(()) } /// Downloads a Spatial package through the spatial CLI. /// /// * package_source - the package source, i.e - worker_sdk, tools, schema. fn download_package( package_source: &SpatialPackageSource, package_name: &str, sdk_version: &str, target_file: &str, ) { let args = vec![ "package", "retrieve", package_source.to_str(), package_name, sdk_version, target_file, ]; let out = process::Command::new("spatial") .args(args) .output() .expect("Could not run spatial package retrieve"); if !out.status.success() { let stdout = match String::from_utf8(out.stdout) { Ok(v) => v, Err(e) => panic!( "Could not decode stdout from spatial command with error: {}", e ), }; let stderr = match String::from_utf8(out.stderr) { Ok(v) => v, Err(e) => panic!( "Could not decode stderr from spatial command with error: {}", e ), }; panic!( "spatial package retrieve returned a non-zero error code.\n Stdout: {}\nStderr: {}", stdout, stderr ); } } /// Unpacks a zip archive into a directory. /// /// * target_package_path - the absolute path of the package archive. /// * target_directory - the absolute path of the target directory. /// /// * result - an IO error if the operation could not be completed, empty otherwise. fn unpack_package(target_package_path: &str, target_directory: &str) -> Result<(), io::Error> { // Prepare target directory. fs::remove_dir_all(target_directory)?; fs::create_dir_all(target_directory)?; // Unpack zip archive let fname = path::Path::new(target_package_path); let file = fs::File::open(&fname)?; let mut archive = zip::ZipArchive::new(file)?; for i in 0..archive.len() { let mut file = archive.by_index(i)?; let mut output_path = path::PathBuf::new(); output_path.push(target_directory); output_path.push(file.sanitized_name()); if (&*file.name()).ends_with('/') { fs::create_dir_all(&output_path)?; } else { if let Some(p) = output_path.parent() { if !p.exists() { fs::create_dir_all(&p)?; } } let mut outfile = fs::File::create(&output_path)?; io::copy(&mut file, &mut outfile)?; #[cfg(any(unix))] { use std::os::unix::fs::PermissionsExt; let mut perms = outfile.metadata()?.permissions(); perms.set_mode(0o774); fs::set_permissions(&output_path, perms)?; } } } Ok(()) }
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } fn vec<T: FromStr>(&mut self, len: usize) -> Vec<T> { (0..len).map(|_| self.input()).collect() } fn mat<T: FromStr>(&mut self, row: usize, col: usize) -> Vec<Vec<T>> { (0..row).map(|_| self.vec(col)).collect() } } trait BinarySearch<T> { // key 以上の値が最初に現れる index を返す fn lower_bound(&self, &T) -> usize; // key より大きい値が最初に現れる index を返す fn upper_bound(&self, &T) -> usize; } use std::cmp::Ordering; impl<T: Ord> BinarySearch<T> for [T] { fn lower_bound(&self, key: &T) -> usize { let mut ng = -1; let mut ok = self.len() as i64; while (ok - ng).abs() > 1 { let mid = (ok + ng) / 2; match key.cmp(&self[mid as usize]) { Ordering::Less | Ordering::Equal => { ok = mid; } Ordering::Greater => { ng = mid; } } } ok as usize } fn upper_bound(&self, key: &T) -> usize { let mut ng = -1; let mut ok = self.len() as i64; while (ok - ng).abs() > 1 { let mid = (ok + ng) / 2; match key.cmp(&self[mid as usize]) { Ordering::Less => { ok = mid; } Ordering::Equal | Ordering::Greater => { ng = mid; } } } ok as usize } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let n: i64 = sc.input(); let mut a: Vec<i64> = sc.vec(n as usize); let mut b: Vec<i64> = sc.vec(n as usize); let mut c: Vec<i64> = sc.vec(n as usize); a.sort(); b.sort(); c.sort(); let mut ans: i64 = 0; for x in b.iter() { let lower = a.lower_bound(&x) as i64; let upper = c.upper_bound(&x) as i64; ans += lower * (n - upper); } println!("{}", ans); }
use crate::ast; use crate::{Parse, Spanned, ToTokens}; /// A return statement `return [expr]`. #[derive(Debug, Clone, ToTokens, Parse, Spanned)] pub struct ExprReturn { /// The return token. pub return_: ast::Return, /// An optional expression to return. #[rune(iter)] pub expr: Option<Box<ast::Expr>>, }
use crossterm::Result; use rand::Rng; use rc_game::{Game, GameState, Offset, RogueCrossGame, TileType}; fn xy_idx(x: usize, y: usize, cols: usize) -> usize { (y * cols) + x } #[derive(Default)] struct Ch03Game {} impl Game for Ch03Game {} fn create_map(gs: &GameState, player_position: &Offset) -> Vec<TileType> { let mut map = vec![TileType::Empty; (gs.rows * gs.cols) as usize]; let GameState { cols, rows, .. } = *gs; let cols = cols as usize; let rows = rows as usize; // Walls for x in 0..cols { map[xy_idx(x, 0, cols)] = TileType::Wall; map[xy_idx(x, rows - 1, cols)] = TileType::Wall; } for y in 0..rows { map[xy_idx(0, y, cols)] = TileType::Wall; map[xy_idx(cols - 1, y, cols)] = TileType::Wall; } let mut rng = rand::thread_rng(); for _ in 0..400 { let x = rng.gen_range(1, cols - 1); let y = rng.gen_range(1, rows - 1); if x != player_position.x as usize || y != player_position.y as usize { let idx = xy_idx(x, y, cols); map[idx] = TileType::Wall; } } map } fn main() -> Result<()> { let mut game: RogueCrossGame<Ch03Game> = Default::default(); game.build_map(create_map); game.start() }
use volatile::Volatile; use crate::asm; const EFLAGS_AC_BIT: u32 = 0x00040000; const CR0_CACHE_DISABLE: u32 = 0x60000000; pub fn memtest(start: u32, end: u32) -> u32 { let mut flg486 = false; asm::store_eflags((asm::load_eflags() as u32 | EFLAGS_AC_BIT) as i32); let mut eflags = asm::load_eflags() as u32; // 386ではAC=1にしても自動で0に戻ってしまう if eflags & EFLAGS_AC_BIT != 0 { flg486 = true; } eflags &= !EFLAGS_AC_BIT; asm::store_eflags(eflags as i32); if flg486 { // キャッシュ禁止 let cr0 = asm::load_cr0() | CR0_CACHE_DISABLE; asm::store_cr0(cr0); } let memory = memtest_main(start, end); if flg486 { // キャッシュ許可 let mut cr0 = asm::load_cr0(); cr0 &= !CR0_CACHE_DISABLE; asm::store_cr0(cr0); } memory } fn memtest_main(start: u32, end: u32) -> u32 { let pat0: u32 = 0xaa55aa55; let pat1: u32 = 0x55aa55aa; let mut r = start; for i in (start..end).step_by(0x1000) { r = i; let mp = (i + 0xffc) as *mut u32; let p = unsafe { &mut *(mp as *mut Volatile<u32>) }; let old = p.read(); p.write(pat0); p.write(!p.read()); if p.read() != pat1 { p.write(old); break; } p.write(!p.read()); if p.read() != pat0 { p.write(old); break; } p.write(old); } r } const MEMMAN_FREES: u32 = 4090; // 約32KB pub const MEMMAN_ADDR: u32 = 0x003c0000; #[derive(Debug, Clone, Copy, PartialEq)] #[repr(C, packed)] struct FreeInfo { addr: u32, size: u32, } #[derive(Clone, Copy)] #[repr(C, packed)] pub struct MemMan { frees: u32, maxfrees: u32, lostsize: u32, losts: u32, free: [FreeInfo; MEMMAN_FREES as usize], } impl MemMan { pub fn new() -> MemMan { MemMan { frees: 0, maxfrees: 0, lostsize: 0, losts: 0, free: [FreeInfo { addr: 0, size: 0 }; MEMMAN_FREES as usize], } } pub fn total(&self) -> u32 { let mut t = 0; for i in 0..self.frees { t += self.free[i as usize].size; } t } pub fn alloc(&mut self, size: u32) -> Result<u32, &'static str> { for i in 0..self.frees { let i = i as usize; if self.free[i].size >= size { let a = self.free[i].addr; self.free[i].addr += size; self.free[i].size -= size; if self.free[i].size == 0 { self.frees -= 1; self.free[i] = self.free[i + 1] } return Ok(a); } } Err("CANNOT ALLOCATE MEMORY") } pub fn free(&mut self, addr: u32, size: u32) -> Result<(), &'static str> { let mut idx: usize = 0; // addrの順に並ぶように、insertすべきindexを決める for i in 0..self.frees { let i = i as usize; if self.free[i].addr > addr { idx = i; break; } } if idx > 0 { if self.free[idx - 1].addr + self.free[idx - 1].size == addr { self.free[idx - 1].size += size; if idx < self.frees as usize { if addr + size == self.free[idx].addr { self.free[idx - 1].size += self.free[idx].size; } self.frees -= 1; for i in idx..(self.frees as usize) { self.free[i] = self.free[i + 1]; } } return Ok(()); } } if idx < self.frees as usize { if addr + size == self.free[idx].addr { self.free[idx].addr = addr; self.free[idx].size += size; return Ok(()); } } if self.frees < MEMMAN_FREES { let mut j = self.frees as usize; while j > idx { self.free[j] = self.free[j - 1]; j -= 1; } self.frees += 1; if self.maxfrees < self.frees { self.maxfrees = self.frees; } self.free[idx].addr = addr; self.free[idx].size = size; return Ok(()); } self.losts += 1; self.lostsize += size; Err("CANNOT FREE MEMORY") } pub fn alloc_4k(&mut self, size: u32) -> Result<u32, &'static str> { let size = (size + 0xfff) & 0xfffff000; self.alloc(size) } pub fn free_4k(&mut self, addr: u32, size: u32) -> Result<(), &'static str> { let size = (size + 0xfff) & 0xfffff000; self.free(addr, size) } }
//! This crate provides methods to manipulate networking resources (links, addresses, arp tables, //! route tables) via the netlink protocol. //! //! It can be used on its own for simple needs, but it is possible to tweak any netlink request. //! See this [link creation snippet](struct.LinkAddRequest.html#example) for example. //! //! # Example: listing links //! //! ```rust,no_run //! extern crate futures; //! extern crate rtnetlink; //! extern crate tokio_core; //! //! use futures::{Stream, Future}; //! use rtnetlink::new_connection; //! use tokio_core::reactor::Core; //! //! fn main() { //! // Create a netlink connection, and a handle to send requests via this connection //! let (connection, handle) = new_connection().unwrap(); //! //! // The connection will run in an event loop //! let mut core = Core::new().unwrap(); //! core.handle().spawn(connection.map_err(|_| ())); //! //! /// Create a netlink request //! let request = handle.link().get().execute().for_each(|link| { //! println!("{:#?}", link); //! Ok(()) //! }); //! //! /// Run the request on the event loop //! core.run(request).unwrap(); //! } //! ``` //! //! # Example: creating a veth pair //! //! ```rust,no_run //! use std::thread::spawn; //! //! use futures::Future; //! use tokio_core::reactor::Core; //! //! use rtnetlink::new_connection; //! //! fn main() { //! // Create a netlink connection, and a handle to send requests via this connection //! let (connection, handle) = new_connection().unwrap(); //! //! // The connection we run in its own thread //! spawn(move || Core::new().unwrap().run(connection)); //! //! // Create a request to create the veth pair //! handle //! .link() //! .add() //! .veth("veth-rs-1".into(), "veth-rs-2".into()) //! // Execute the request, and wait for it to finish //! .execute() //! .wait() //! .unwrap(); //! } //! ``` //! //! # Example: deleting a link by name //! //! ```rust,no_run //! use std::env; //! use std::thread::spawn; //! //! use futures::{Stream, Future}; //! use tokio_core::reactor::Core; //! //! use rtnetlink::new_connection; //! use netlink_packet_route::link::nlas::LinkNla; //! //! fn main() { //! let args: Vec<String> = env::args().collect(); //! if args.len() != 2 { panic!("expected one link name as argument"); } //! let link_name = &args[1]; //! //! let (connection, handle) = new_connection().unwrap(); //! spawn(move || Core::new().unwrap().run(connection)); //! //! // Get the list of links //! let links = handle.link().get().execute().collect().wait().unwrap(); //! //! // Find the link with the name provided as argument, and delete it //! for link in links { //! for nla in &link.nlas { //! // Find the link with the name provided as argument //! if let LinkNla::IfName(ref name) = nla { //! if name == link_name { //! // Set it down //! handle.link().del(link.header.index).execute().wait().unwrap(); //! return; //! } //! } //! } //! } //! } //! ``` #![allow(clippy::module_inception)] #[macro_use] extern crate lazy_static; use failure; pub use netlink_packet_core; pub use netlink_packet_route; use netlink_proto; pub use netlink_proto::{sys::Protocol, Connection}; mod handle; pub use crate::handle::*; mod errors; pub use crate::errors::*; mod link; pub use crate::link::*; mod addr; pub use crate::addr::*; use std::io; use crate::netlink_packet_core::NetlinkMessage; use crate::netlink_packet_route::RtnlMessage; use futures::sync::mpsc::UnboundedReceiver; pub fn new_connection() -> io::Result<(Connection<RtnlMessage>, Handle)> { let (conn, handle, _) = netlink_proto::new_connection(Protocol::Route)?; Ok((conn, Handle::new(handle))) } pub fn new_connection_with_messages() -> io::Result<( Connection<RtnlMessage>, Handle, UnboundedReceiver<NetlinkMessage<RtnlMessage>>, )> { let (conn, handle, messages) = netlink_proto::new_connection(Protocol::Route)?; Ok((conn, Handle::new(handle), messages)) }
#[doc = r"Register block"] #[repr(C)] pub struct CH { #[doc = "0x00 - DMA channel x configuration register"] pub cr: CR, #[doc = "0x04 - DMA channel x number of data register"] pub ndtr: NDTR, #[doc = "0x08 - This register must not be written when the channel is enabled."] pub par: PAR, #[doc = "0x0c - This register must not be written when the channel is enabled."] pub m0ar: M0AR, #[doc = "0x10 - Channel x memory 1 address register"] pub m1ar: M1AR, } #[doc = "CR (rw) register accessor: DMA channel x configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "DMA channel x configuration register"] pub mod cr; #[doc = "NDTR (rw) register accessor: DMA channel x number of data register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ndtr::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 [`ndtr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ndtr`] module"] pub type NDTR = crate::Reg<ndtr::NDTR_SPEC>; #[doc = "DMA channel x number of data register"] pub mod ndtr; #[doc = "PAR (rw) register accessor: This register must not be written when the channel is enabled.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`par::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 [`par::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`par`] module"] pub type PAR = crate::Reg<par::PAR_SPEC>; #[doc = "This register must not be written when the channel is enabled."] pub mod par; #[doc = "M0AR (rw) register accessor: This register must not be written when the channel is enabled.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m0ar::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 [`m0ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m0ar`] module"] pub type M0AR = crate::Reg<m0ar::M0AR_SPEC>; #[doc = "This register must not be written when the channel is enabled."] pub mod m0ar; #[doc = "M1AR (rw) register accessor: Channel x memory 1 address register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`m1ar::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 [`m1ar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`m1ar`] module"] pub type M1AR = crate::Reg<m1ar::M1AR_SPEC>; #[doc = "Channel x memory 1 address register"] pub mod m1ar;
/// bindings for ARINC653P1-5 3.6.2.1 sampling pub mod basic { use crate::bindings::*; use crate::Locked; pub type SamplingPortName = ApexName; // TODO P2 extension /// According to ARINC 653P1-5 this may either be 32 or 64 bits. /// Internally we will use 64-bit by default. /// The implementing Hypervisor may cast this to 32-bit if needed pub type SamplingPortId = ApexLongInteger; #[repr(u32)] #[derive(Debug, Copy, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[cfg_attr(feature = "strum", derive(strum::FromRepr))] pub enum Validity { Invalid = 0, Valid = 1, } #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct ApexSamplingPortStatus { pub refresh_period: ApexSystemTime, pub max_message_size: MessageSize, pub port_direction: PortDirection, pub last_msg_validity: Validity, } pub trait ApexSamplingPortP4 { // Only during Warm/Cold-Start #[cfg_attr(not(feature = "full_doc"), doc(hidden))] fn create_sampling_port<L: Locked>( sampling_port_name: SamplingPortName, max_message_size: MessageSize, port_direction: PortDirection, refresh_period: ApexSystemTime, ) -> Result<SamplingPortId, ErrorReturnCode>; #[cfg_attr(not(feature = "full_doc"), doc(hidden))] fn write_sampling_message<L: Locked>( sampling_port_id: SamplingPortId, message: &[ApexByte], ) -> Result<(), ErrorReturnCode>; /// # Safety /// /// This function is safe, as long as the buffer can hold whatever is received #[cfg_attr(not(feature = "full_doc"), doc(hidden))] unsafe fn read_sampling_message<L: Locked>( sampling_port_id: SamplingPortId, message: &mut [ApexByte], ) -> Result<(Validity, MessageSize), ErrorReturnCode>; } pub trait ApexSamplingPortP1: ApexSamplingPortP4 { #[cfg_attr(not(feature = "full_doc"), doc(hidden))] fn get_sampling_port_id<L: Locked>( sampling_port_name: SamplingPortName, ) -> Result<SamplingPortId, ErrorReturnCode>; #[cfg_attr(not(feature = "full_doc"), doc(hidden))] fn get_sampling_port_status<L: Locked>( sampling_port_id: SamplingPortId, ) -> Result<ApexSamplingPortStatus, ErrorReturnCode>; } } /// abstractions for ARINC653P1-5 3.6.2.1 sampling pub mod abstraction { use core::marker::PhantomData; use core::sync::atomic::AtomicPtr; use core::time::Duration; // Reexport important basic-types for downstream-user pub use super::basic::{SamplingPortId, Validity}; use crate::bindings::*; use crate::hidden::Key; use crate::prelude::*; #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub struct SamplingPortStatus { pub refresh_period: SystemTime, pub max_message_size: MessageSize, pub port_direction: PortDirection, pub last_msg_validity: Validity, } impl From<ApexSamplingPortStatus> for SamplingPortStatus { fn from(s: ApexSamplingPortStatus) -> Self { SamplingPortStatus { refresh_period: s.refresh_period.into(), max_message_size: s.max_message_size, port_direction: s.port_direction, last_msg_validity: s.last_msg_validity, } } } #[derive(Debug)] pub struct SamplingPortSource<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> { _b: PhantomData<AtomicPtr<S>>, id: SamplingPortId, } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> Clone for SamplingPortSource<MSG_SIZE, S> { fn clone(&self) -> Self { Self { _b: self._b, id: self.id, } } } #[derive(Debug)] pub struct SamplingPortDestination<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> { _b: PhantomData<AtomicPtr<S>>, id: SamplingPortId, refresh: Duration, } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> Clone for SamplingPortDestination<MSG_SIZE, S> { fn clone(&self) -> Self { Self { _b: self._b, id: self.id, refresh: self.refresh, } } } pub trait ApexSamplingPortP4Ext: ApexSamplingPortP4 + Sized { fn sampling_port_send_unchecked( id: SamplingPortId, buffer: &[ApexByte], ) -> Result<(), Error>; /// # Safety /// /// This function is safe, as long as the buffer can hold whatever is received unsafe fn sampling_port_receive_unchecked( id: SamplingPortId, buffer: &mut [ApexByte], ) -> Result<(Validity, &[ApexByte]), Error>; } pub trait ApexSamplingPortP1Ext: ApexSamplingPortP1 + Sized { /// Returns Err(Error::InvalidConfig) if sampling port with name does not exists or /// if the message size of the found sampling port is different than MSG_SIZE fn get_sampling_port_source<const MSG_SIZE: MessageSize>( name: Name, ) -> Result<SamplingPortSource<MSG_SIZE, Self>, Error>; /// Returns Err(Error::InvalidConfig) if sampling port with name does not exists or /// if the message size of the found sampling port is different than MSG_SIZE fn get_sampling_port_destination<const MSG_SIZE: MessageSize>( name: Name, ) -> Result<SamplingPortDestination<MSG_SIZE, Self>, Error>; } impl<S: ApexSamplingPortP4> ApexSamplingPortP4Ext for S { fn sampling_port_send_unchecked( id: SamplingPortId, buffer: &[ApexByte], ) -> Result<(), Error> { S::write_sampling_message::<Key>(id, buffer)?; Ok(()) } unsafe fn sampling_port_receive_unchecked( id: SamplingPortId, buffer: &mut [ApexByte], ) -> Result<(Validity, &[ApexByte]), Error> { let (val, len) = S::read_sampling_message::<Key>(id, buffer)?; Ok((val, &buffer[..(len as usize)])) } } impl<S: ApexSamplingPortP1> ApexSamplingPortP1Ext for S { /// Returns Err(Error::InvalidConfig) if sampling port with name does not exists or /// if the message size of the found sampling port is different than MSG_SIZE fn get_sampling_port_source<const MSG_SIZE: MessageSize>( name: Name, ) -> Result<SamplingPortSource<MSG_SIZE, Self>, Error> { let id = S::get_sampling_port_id::<Key>(name.into())?; // According to ARINC653P1-5 3.6.2.1.5 this can only fail if the sampling_port_id // does not exist in the current partition. // But since we retrieve the sampling_port_id directly from the hypervisor // there is no possible way for it not existing let SamplingPortStatus { refresh_period: _, max_message_size, port_direction, .. } = S::get_sampling_port_status::<Key>(id).unwrap().into(); if max_message_size != MSG_SIZE { return Err(Error::InvalidConfig); } if port_direction != PortDirection::Source { return Err(Error::InvalidConfig); } Ok(SamplingPortSource { _b: Default::default(), id, }) } /// Returns Err(Error::InvalidConfig) if sampling port with name does not exists or /// if the message size of the found sampling port is different than MSG_SIZE fn get_sampling_port_destination<const MSG_SIZE: MessageSize>( name: Name, ) -> Result<SamplingPortDestination<MSG_SIZE, Self>, Error> { let id = S::get_sampling_port_id::<Key>(name.into())?; // According to ARINC653P1-5 3.6.2.1.5 this can only fail if the sampling_port_id // does not exist in the current partition. // But since we retrieve the sampling_port_id directly from the hypervisor // there is no possible way for it not existing let SamplingPortStatus { refresh_period, max_message_size, port_direction, .. } = S::get_sampling_port_status::<Key>(id)?.into(); if max_message_size != MSG_SIZE { return Err(Error::InvalidConfig); } if port_direction != PortDirection::Destination { return Err(Error::InvalidConfig); } Ok(SamplingPortDestination { _b: Default::default(), id, // According to ARINC653P1-5 3.6.2.1.1 the refresh_period defined during // COLD/WARM-Start is always positive, hence this unwrap cannot fail refresh: refresh_period.unwrap_duration(), }) } } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> SamplingPortSource<MSG_SIZE, S> { pub fn send(&self, buffer: &[ApexByte]) -> Result<(), Error> { buffer.validate_write(MSG_SIZE)?; S::sampling_port_send_unchecked(self.id, buffer) } pub fn id(&self) -> SamplingPortId { self.id } pub const fn size(&self) -> MessageSize { MSG_SIZE } } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP1> SamplingPortSource<MSG_SIZE, S> { pub fn from_name(name: Name) -> Result<SamplingPortSource<MSG_SIZE, S>, Error> { S::get_sampling_port_source(name) } pub fn status(&self) -> SamplingPortStatus { // According to ARINC653P1-5 3.6.2.1.5 this can only fail if the sampling_port_id // does not exist in the current partition. // But since we retrieve the sampling_port_id directly from the hypervisor // there is no possible way for it to not exist S::get_sampling_port_status::<Key>(self.id).unwrap().into() } } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP4> SamplingPortDestination<MSG_SIZE, S> { pub fn receive<'a>( &self, buffer: &'a mut [ApexByte], ) -> Result<(Validity, &'a [ApexByte]), Error> { buffer.validate_read(MSG_SIZE)?; unsafe { S::sampling_port_receive_unchecked(self.id, buffer) } } pub fn id(&self) -> SamplingPortId { self.id } pub const fn size(&self) -> MessageSize { MSG_SIZE } pub fn refresh_period(&self) -> Duration { self.refresh } } impl<const MSG_SIZE: MessageSize, S: ApexSamplingPortP1> SamplingPortDestination<MSG_SIZE, S> { pub fn from_name(name: Name) -> Result<SamplingPortDestination<MSG_SIZE, S>, Error> { S::get_sampling_port_destination(name) } pub fn status(&self) -> SamplingPortStatus { // According to ARINC653P1-5 3.6.2.1.5 this can only fail if the sampling_port_id // does not exist in the current partition. // But since we retrieve the sampling_port_id directly from the hypervisor // there is no possible way for it not existing S::get_sampling_port_status::<Key>(self.id).unwrap().into() } } impl<S: ApexSamplingPortP4> StartContext<S> { pub fn create_sampling_port_source<const MSG_SIZE: MessageSize>( &mut self, name: Name, ) -> Result<SamplingPortSource<MSG_SIZE, S>, Error> { let id = S::create_sampling_port::<Key>( name.into(), MSG_SIZE, PortDirection::Source, // use random non-zero duration. // while refresh_period is ignored for the source // it may produce an error if set to zero SystemTime::Normal(Duration::from_nanos(1)).into(), )?; Ok(SamplingPortSource { _b: Default::default(), id, }) } pub fn create_sampling_port_destination<const MSG_SIZE: MessageSize>( &mut self, name: Name, refresh: Duration, ) -> Result<SamplingPortDestination<MSG_SIZE, S>, Error> { let id = S::create_sampling_port::<Key>( name.into(), MSG_SIZE, PortDirection::Destination, SystemTime::Normal(refresh).into(), )?; Ok(SamplingPortDestination { _b: Default::default(), id, refresh, }) } } }
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. use crate::error::{Error, Result}; use serde::ser::{Impossible, Serialize, Serializer}; /// All serde_v8 "magic" values are reduced to structs with 1 or 2 u64 fields /// assuming usize==u64, most types are simply a pointer or pointer+len (e.g: Box<T>) pub type TransmutedField = u64; pub type FieldResult = Result<TransmutedField>; macro_rules! not_reachable { ($($name:ident($ty:ty);)*) => { $(fn $name(self, _v: $ty) -> FieldResult { unreachable!(); })* }; } /// FieldSerializer is a simple serde::Serializer that only returns u64s /// it allows the "magic" struct serializers to obtain the transmuted field values pub struct FieldSerializer {} impl Serializer for FieldSerializer { type Ok = TransmutedField; type Error = Error; type SerializeSeq = Impossible<TransmutedField, Error>; type SerializeTuple = Impossible<TransmutedField, Error>; type SerializeTupleStruct = Impossible<TransmutedField, Error>; type SerializeTupleVariant = Impossible<TransmutedField, Error>; type SerializeMap = Impossible<TransmutedField, Error>; type SerializeStruct = Impossible<TransmutedField, Error>; type SerializeStructVariant = Impossible<TransmutedField, Error>; fn serialize_u64(self, transmuted_field: u64) -> FieldResult { Ok(transmuted_field) } not_reachable! { serialize_i8(i8); serialize_i16(i16); serialize_i32(i32); serialize_i64(i64); serialize_u8(u8); serialize_u16(u16); serialize_u32(u32); // serialize_u64(TransmutedField); the chosen one serialize_f32(f32); serialize_f64(f64); serialize_bool(bool); serialize_char(char); serialize_str(&str); serialize_bytes(&[u8]); } fn serialize_none(self) -> FieldResult { unreachable!(); } fn serialize_some<T: ?Sized + Serialize>(self, _value: &T) -> FieldResult { unreachable!(); } fn serialize_unit(self) -> FieldResult { unreachable!(); } fn serialize_unit_struct(self, _name: &'static str) -> FieldResult { unreachable!(); } fn serialize_unit_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, ) -> FieldResult { unreachable!(); } fn serialize_newtype_struct<T: ?Sized + Serialize>( self, _name: &'static str, _value: &T, ) -> FieldResult { unreachable!(); } fn serialize_newtype_variant<T: ?Sized + Serialize>( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _value: &T, ) -> FieldResult { unreachable!(); } fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq> { unreachable!(); } fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple> { unreachable!(); } fn serialize_tuple_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeTupleStruct> { unreachable!(); } fn serialize_tuple_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeTupleVariant> { unreachable!(); } fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> { unreachable!(); } fn serialize_struct( self, _name: &'static str, _len: usize, ) -> Result<Self::SerializeStruct> { unreachable!(); } fn serialize_struct_variant( self, _name: &'static str, _variant_index: u32, _variant: &'static str, _len: usize, ) -> Result<Self::SerializeStructVariant> { unreachable!(); } }
#[doc = "Reader of register SAI_ASR"] pub type R = crate::R<u32, super::SAI_ASR>; #[doc = "Reader of field `OVRUDR`"] pub type OVRUDR_R = crate::R<bool, bool>; #[doc = "Reader of field `MUTEDET`"] pub type MUTEDET_R = crate::R<bool, bool>; #[doc = "Reader of field `WCKCFG`"] pub type WCKCFG_R = crate::R<bool, bool>; #[doc = "Reader of field `FREQ`"] pub type FREQ_R = crate::R<bool, bool>; #[doc = "Reader of field `CNRDY`"] pub type CNRDY_R = crate::R<bool, bool>; #[doc = "Reader of field `AFSDET`"] pub type AFSDET_R = crate::R<bool, bool>; #[doc = "Reader of field `LFSDET`"] pub type LFSDET_R = crate::R<bool, bool>; #[doc = "Reader of field `FLVL`"] pub type FLVL_R = crate::R<u8, u8>; impl R { #[doc = "Bit 0 - Overrun / underrun. This bit is read only. The overrun and underrun conditions can occur only when the audio block is configured as a receiver and a transmitter, respectively. It can generate an interrupt if OVRUDRIE bit is set in SAI_xIM register. This flag is cleared when the software sets COVRUDR bit in SAI_xCLRFR register."] #[inline(always)] pub fn ovrudr(&self) -> OVRUDR_R { OVRUDR_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Mute detection. This bit is read only. This flag is set if consecutive 0 values are received in each slot of a given audio frame and for a consecutive number of audio frames (set in the MUTECNT bit in the SAI_xCR2 register). It can generate an interrupt if MUTEDETIE bit is set in SAI_xIM register. This flag is cleared when the software sets bit CMUTEDET in the SAI_xCLRFR register."] #[inline(always)] pub fn mutedet(&self) -> MUTEDET_R { MUTEDET_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - Wrong clock configuration flag. This bit is read only. This bit is used only when the audio block operates in master mode (MODE\\[1\\] = 0) and NODIV = 0. It can generate an interrupt if WCKCFGIE bit is set in SAI_xIM register. This flag is cleared when the software sets CWCKCFG bit in SAI_xCLRFR register."] #[inline(always)] pub fn wckcfg(&self) -> WCKCFG_R { WCKCFG_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - FIFO request. This bit is read only. The request depends on the audio block configuration: If the block is configured in transmission mode, the FIFO request is related to a write request operation in the SAI_xDR. If the block configured in reception, the FIFO request related to a read request operation from the SAI_xDR. This flag can generate an interrupt if FREQIE bit is set in SAI_xIM register."] #[inline(always)] pub fn freq(&self) -> FREQ_R { FREQ_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - Codec not ready. This bit is read only. This bit is used only when the AC97 audio protocol is selected in the SAI_xCR1 register and configured in receiver mode. It can generate an interrupt if CNRDYIE bit is set in SAI_xIM register. This flag is cleared when the software sets CCNRDY bit in SAI_xCLRFR register."] #[inline(always)] pub fn cnrdy(&self) -> CNRDY_R { CNRDY_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - Anticipated frame synchronization detection. This bit is read only. This flag can be set only if the audio block is configured in slave mode. It is not used in AC97or SPDIF mode. It can generate an interrupt if AFSDETIE bit is set in SAI_xIM register. This flag is cleared when the software sets CAFSDET bit in SAI_xCLRFR register."] #[inline(always)] pub fn afsdet(&self) -> AFSDET_R { AFSDET_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - Late frame synchronization detection. This bit is read only. This flag can be set only if the audio block is configured in slave mode. It is not used in AC97 or SPDIF mode. It can generate an interrupt if LFSDETIE bit is set in the SAI_xIM register. This flag is cleared when the software sets bit CLFSDET in SAI_xCLRFR register"] #[inline(always)] pub fn lfsdet(&self) -> LFSDET_R { LFSDET_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bits 16:18 - FIFO level threshold. This bit is read only. The FIFO level threshold flag is managed only by hardware and its setting depends on SAI block configuration (transmitter or receiver mode). If the SAI block is configured as transmitter: If SAI block is configured as receiver:"] #[inline(always)] pub fn flvl(&self) -> FLVL_R { FLVL_R::new(((self.bits >> 16) & 0x07) as u8) } }
test_normalize! { DIR="D:\\repro" INPUT="tests\\ui\\nonzero_fail.rs" " error[E0080]: evaluation of constant value failed --> D:\\repro\\tests\\ui\\nonzero_fail.rs:7:10 | 7 | #[derive(NonZeroRepr)] | ^^^^^^^^^^^ the evaluated program panicked at 'expected non-zero discriminant expression', D:\\repro\\tests\\ui\\nonzero_fail.rs:7:10 " " error[E0080]: evaluation of constant value failed --> tests/ui/nonzero_fail.rs:7:10 | 7 | #[derive(NonZeroRepr)] | ^^^^^^^^^^^ the evaluated program panicked at 'expected non-zero discriminant expression', $DIR/tests/ui/nonzero_fail.rs:7:10 "}
//! 3x3 Matrix use super::common::{Mat3, Mat4, Mat2d, Quat, Vec2, hypot, EPSILON}; /// Creates a new identity mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn create() -> Mat3 { let mut out: Mat3 = [0_f32; 9]; out[0] = 1.; out[4] = 1.; out[8] = 1.; out } /// Copies the upper-left 3x3 values into the given mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_mat4(out: &mut Mat3, a: &Mat4) -> Mat3 { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[4]; out[4] = a[5]; out[5] = a[6]; out[6] = a[8]; out[7] = a[9]; out[8] = a[10]; *out } /// Creates a new mat3 initialized with values from an existing matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn clone(a: &Mat3) -> Mat3 { let mut out: Mat3 = [0_f32; 9]; out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; out } /// Copy the values from one mat3 to another. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn copy(out: &mut Mat3, a: &Mat3) -> Mat3 { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; *out } /// Create a new mat3 with the given values. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_values(m00: f32, m01: f32, m02: f32, m10: f32, m11: f32, m12: f32, m20: f32, m21: f32, m22: f32) -> Mat3 { let mut out: Mat3 = [0_f32; 9]; out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; out } /// Set the components of a mat3 to the given values. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn set(out: &mut Mat3, m00: f32, m01: f32, m02: f32, m10: f32, m11: f32, m12: f32, m20: f32, m21: f32, m22: f32) -> Mat3 { out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; *out } /// Set a mat3 to the identity matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn identity(out: &mut Mat3) -> Mat3 { out[0] = 1.; out[1] = 0.; out[2] = 0.; out[3] = 0.; out[4] = 1.; out[5] = 0.; out[6] = 0.; out[7] = 0.; out[8] = 1.; *out } /// Copies the upper-left 3x3 values into the given mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn transpose(out: &mut Mat3, a: &Mat3) -> Mat3 { // If we are transposing ourselves we can skip a few steps but have to cache some values if out.eq(&a) { let a01 = a[1]; let a02 = a[2]; let a12 = a[5]; out[1] = a[3]; out[2] = a[6]; out[3] = a01; out[5] = a[7]; out[6] = a02; out[7] = a12; } else { out[0] = a[0]; out[1] = a[3]; out[2] = a[6]; out[3] = a[1]; out[4] = a[4]; out[5] = a[7]; out[6] = a[2]; out[7] = a[5]; out[8] = a[8]; } *out } /// Inverts a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn invert(out: &mut Mat3, a: &Mat3) -> Option<Mat3> { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; let b01 = a22 * a11 - a12 * a21; let b11 = -a22 * a10 + a12 * a20; let b21 = a21 * a10 - a11 * a20; // Calculate the determinant let det = a00 * b01 + a01 * b11 + a02 * b21; // Make sure matrix is not singular if det == 0_f32 { return None; } let det = 1_f32 / det; out[0] = b01 * det; out[1] = (-a22 * a01 + a02 * a21) * det; out[2] = (a12 * a01 - a02 * a11) * det; out[3] = b11 * det; out[4] = (a22 * a00 - a02 * a20) * det; out[5] = (-a12 * a00 + a02 * a10) * det; out[6] = b21 * det; out[7] = (-a21 * a00 + a01 * a20) * det; out[8] = (a11 * a00 - a01 * a10) * det; Some(*out) } /// Calculates the adjugate of a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn adjoint(out: &mut Mat3, a: &Mat3) -> Mat3 { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; out[0] = a11 * a22 - a12 * a21; out[1] = a02 * a21 - a01 * a22; out[2] = a01 * a12 - a02 * a11; out[3] = a12 * a20 - a10 * a22; out[4] = a00 * a22 - a02 * a20; out[5] = a02 * a10 - a00 * a12; out[6] = a10 * a21 - a11 * a20; out[7] = a01 * a20 - a00 * a21; out[8] = a00 * a11 - a01 * a10; *out } /// Calculates the determinant of a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn determinant(a: &Mat3) -> f32 { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20) } /// Multiplies two mat3's. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn multiply(out: &mut Mat3, a: &Mat3, b: &Mat3) -> Mat3 { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; let b00 = b[0]; let b01 = b[1]; let b02 = b[2]; let b10 = b[3]; let b11 = b[4]; let b12 = b[5]; let b20 = b[6]; let b21 = b[7]; let b22 = b[8]; out[0] = b00 * a00 + b01 * a10 + b02 * a20; out[1] = b00 * a01 + b01 * a11 + b02 * a21; out[2] = b00 * a02 + b01 * a12 + b02 * a22; out[3] = b10 * a00 + b11 * a10 + b12 * a20; out[4] = b10 * a01 + b11 * a11 + b12 * a21; out[5] = b10 * a02 + b11 * a12 + b12 * a22; out[6] = b20 * a00 + b21 * a10 + b22 * a20; out[7] = b20 * a01 + b21 * a11 + b22 * a21; out[8] = b20 * a02 + b21 * a12 + b22 * a22; *out } /// Translate a mat3 by the given vector. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn translate(out: &mut Mat3, a: &Mat3, v: &Vec2) -> Mat3 { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; let x = v[0]; let y = v[1]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a10; out[4] = a11; out[5] = a12; out[6] = x * a00 + y * a10 + a20; out[7] = x * a01 + y * a11 + a21; out[8] = x * a02 + y * a12 + a22; *out } /// Rotates a mat3 by the given angle. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn rotate(out: &mut Mat3, a: &Mat3, rad: f32) -> Mat3 { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a10 = a[3]; let a11 = a[4]; let a12 = a[5]; let a20 = a[6]; let a21 = a[7]; let a22 = a[8]; let s = f32::sin(rad); let c = f32::cos(rad); out[0] = c * a00 + s * a10; out[1] = c * a01 + s * a11; out[2] = c * a02 + s * a12; out[3] = c * a10 - s * a00; out[4] = c * a11 - s * a01; out[5] = c * a12 - s * a02; out[6] = a20; out[7] = a21; out[8] = a22; *out } /// Scales the mat3 by the dimensions in the given vec2. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn scale(out: &mut Mat3, a: &Mat3, v: &Vec2) -> Mat3 { let x = v[0]; let y = v[1]; out[0] = x * a[0]; out[1] = x * a[1]; out[2] = x * a[2]; out[3] = y * a[3]; out[4] = y * a[4]; out[5] = y * a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; *out } /// Creates a matrix from a vector translation. /// /// This is equivalent to (but much faster than): /// ``` /// use gl_matrix::common::*; /// use gl_matrix::mat3; /// /// let dest = &mut [0., 0., 0., /// 0., 0., 0., /// 0., 0., 0.]; /// let vec: Vec2 = [2., 3.]; /// /// mat3::identity(dest); /// mat3::translate(dest, &mat3::clone(dest), &vec); /// ``` /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_translation(out: &mut Mat3 , v: &Vec2) -> Mat3 { out[0] = 1.; out[1] = 0.; out[2] = 0.; out[3] = 0.; out[4] = 1.; out[5] = 0.; out[6] = v[0]; out[7] = v[1]; out[8] = 1.; *out } /// Creates a matrix from a given angle. /// /// This is equivalent to (but much faster than): /// ``` /// use gl_matrix::common::*; /// use gl_matrix::mat3; /// /// let dest = &mut [0., 0., 0., /// 0., 0., 0., /// 0., 0., 0.]; /// let rad = PI * 0.5; /// /// mat3::identity(dest); /// mat3::rotate(dest, &mat3::clone(dest), rad); /// ``` /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_rotation(out: &mut Mat3, rad: f32) -> Mat3 { let s = f32::sin(rad); let c = f32::cos(rad); out[0] = c; out[1] = s; out[2] = 0.; out[3] = -s; out[4] = c; out[5] = 0.; out[6] = 0.; out[7] = 0.; out[8] = 1.; *out } /// Creates a matrix from a vector scaling. /// /// This is equivalent to (but much faster than): /// ``` /// use gl_matrix::common::*; /// use gl_matrix::mat3; /// /// let dest = &mut [0., 0., 0., /// 0., 0., 0., /// 0., 0., 0.]; /// let vec: Vec2 = [2., 3.]; /// /// mat3::identity(dest); /// mat3::scale(dest, &mat3::clone(dest), &vec); /// ``` /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_scaling(out: &mut Mat3, v: &Vec2) -> Mat3 { out[0] = v[0]; out[1] = 0.; out[2] = 0.; out[3] = 0.; out[4] = v[1]; out[5] = 0.; out[6] = 0.; out[7] = 0.; out[8] = 1.; *out } /// Copies the values from a mat2d into a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_mat2d(out: &mut Mat3, a: &Mat2d) -> Mat3 { out[0] = a[0]; out[1] = a[1]; out[2] = 0.; out[3] = a[2]; out[4] = a[3]; out[5] = 0.; out[6] = a[4]; out[7] = a[5]; out[8] = 1.; *out } /// Calculates a 3x3 matrix from the given quaternion. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn from_quat(out: &mut Mat3, q: &Quat) -> Mat3 { let x = q[0]; let y = q[1]; let z = q[2]; let w = q[3]; let x2 = x + x; let y2 = y + y; let z2 = z + z; let xx = x * x2; let yx = y * x2; let yy = y * y2; let zx = z * x2; let zy = z * y2; let zz = z * z2; let wx = w * x2; let wy = w * y2; let wz = w * z2; out[0] = 1. - yy - zz; out[3] = yx - wz; out[6] = zx + wy; out[1] = yx + wz; out[4] = 1. - xx - zz; out[7] = zy - wx; out[2] = zx - wy; out[5] = zy + wx; out[8] = 1. - xx - yy; *out } /// Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn normal_from_mat4(out: &mut Mat3, a: &Mat4) -> Option<Mat3> { let a00 = a[0]; let a01 = a[1]; let a02 = a[2]; let a03 = a[3]; let a10 = a[4]; let a11 = a[5]; let a12 = a[6]; let a13 = a[7]; let a20 = a[8]; let a21 = a[9]; let a22 = a[10]; let a23 = a[11]; let a30 = a[12]; let a31 = a[13]; let a32 = a[14]; let a33 = a[15]; let b00 = a00 * a11 - a01 * a10; let b01 = a00 * a12 - a02 * a10; let b02 = a00 * a13 - a03 * a10; let b03 = a01 * a12 - a02 * a11; let b04 = a01 * a13 - a03 * a11; let b05 = a02 * a13 - a03 * a12; let b06 = a20 * a31 - a21 * a30; let b07 = a20 * a32 - a22 * a30; let b08 = a20 * a33 - a23 * a30; let b09 = a21 * a32 - a22 * a31; let b10 = a21 * a33 - a23 * a31; let b11 = a22 * a33 - a23 * a32; // Calculate the determinant let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if det == 0_f32 { return None; } let det = 1_f32 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; Some(*out) } /// Generates a 2D projection matrix with the given bounds. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn projection(out: &mut Mat3, width: f32, height: f32) -> Mat3 { out[0] = 2. / width; out[1] = 0.; out[2] = 0.; out[3] = 0.; out[4] = -2. / height; out[5] = 0.; out[6] = -1.; out[7] = 1.; out[8] = 1.; *out } /// Returns a string representation of a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn string(a: &Mat3) -> String { let a0 = ["mat3(".to_string(), a[0].to_string()].join(""); let a1 = a[1].to_string(); let a2 = a[2].to_string(); let a3 = a[3].to_string(); let a4 = a[4].to_string(); let a5 = a[5].to_string(); let a6 = a[6].to_string(); let a7 = a[7].to_string(); let a8 = [a[8].to_string(), ")".to_string()].join(""); [a0, a1, a2, a3, a4, a5, a6, a7, a8].join(", ") } /// Returns Frobenius norm of a mat3. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn frob(a: &Mat3) -> f32 { hypot(a) } /// Adds two mat3's. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn add(out: &mut Mat3, a: &Mat3, b: &Mat3) -> Mat3 { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; out[3] = a[3] + b[3]; out[4] = a[4] + b[4]; out[5] = a[5] + b[5]; out[6] = a[6] + b[6]; out[7] = a[7] + b[7]; out[8] = a[8] + b[8]; *out } /// Subtracts matrix b from matrix a. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn subtract(out: &mut Mat3, a: &Mat3, b: &Mat3) -> Mat3 { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; out[3] = a[3] - b[3]; out[4] = a[4] - b[4]; out[5] = a[5] - b[5]; out[6] = a[6] - b[6]; out[7] = a[7] - b[7]; out[8] = a[8] - b[8]; *out } /// Multiply each element of the matrix by a scalar. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn multiply_scalar(out: &mut Mat3, a: &Mat3, b: f32) -> Mat3 { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; out[3] = a[3] * b; out[4] = a[4] * b; out[5] = a[5] * b; out[6] = a[6] * b; out[7] = a[7] * b; out[8] = a[8] * b; *out } /// Adds two mat3's after multiplying each element of the second operand by a scalar value. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn multiply_scalar_and_add(out: &mut Mat3, a: &Mat3, b: &Mat3, scale: f32) -> Mat3 { out[0] = a[0] + (b[0] * scale); out[1] = a[1] + (b[1] * scale); out[2] = a[2] + (b[2] * scale); out[3] = a[3] + (b[3] * scale); out[4] = a[4] + (b[4] * scale); out[5] = a[5] + (b[5] * scale); out[6] = a[6] + (b[6] * scale); out[7] = a[7] + (b[7] * scale); out[8] = a[8] + (b[8] * scale); *out } /// Returns whether or not the matrices have exactly the same elements in the same position (when compared with ==). /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn exact_equals(a: &Mat3, b: &Mat3) -> bool { a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3] && a[4] == b[4] && a[5] == b[5] && a[6] == b[6] && a[7] == b[7] && a[8] == b[8] } /// Returns whether or not the matrices have approximately the same elements in the same position. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn equals(a: &Mat3, b: &Mat3) -> bool { let a0 = a[0]; let a1 = a[1]; let a2 = a[2]; let a3 = a[3]; let a4 = a[4]; let a5 = a[5]; let a6 = a[6]; let a7 = a[7]; let a8 = a[8]; let b0 = b[0]; let b1 = b[1]; let b2 = b[2]; let b3 = b[3]; let b4 = b[4]; let b5 = b[5]; let b6 = b[6]; let b7 = b[7]; let b8 = b[8]; f32::abs(a0 - b0) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a0), f32::abs(b0))) && f32::abs(a1 - b1) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a1), f32::abs(b1))) && f32::abs(a2 - b2) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a2), f32::abs(b2))) && f32::abs(a3 - b3) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a3), f32::abs(b3))) && f32::abs(a4 - b4) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a4), f32::abs(b4))) && f32::abs(a5 - b5) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a5), f32::abs(b5))) && f32::abs(a6 - b6) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a6), f32::abs(b6))) && f32::abs(a7 - b7) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a7), f32::abs(b7))) && f32::abs(a8 - b8) <= EPSILON * f32::max(1.0, f32::max(f32::abs(a8), f32::abs(b8))) } /// Alias for mat3::multiply. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn mul(out: &mut Mat3, a: &Mat3, b: &Mat3) -> Mat3 { multiply(out, a, b) } /// Alias for mat3::subtract. /// /// [glMatrix Documentation](http://glmatrix.net/docs/module-mat3.html) pub fn sub(out: &mut Mat3, a: &Mat3, b: &Mat3) -> Mat3 { subtract(out, a, b) } #[cfg(test)] mod tests { use super::*; #[test] fn create_a_mat3() { let ident: Mat3 = [1., 0., 0., 0., 1., 0., 0., 0., 1.]; let out = create(); assert_eq!(ident, out); } #[test] fn mat3_from_mat4() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat4 = [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]; let result = from_mat4(&mut out, &mat_a); assert_eq!([1., 0., 0., 0., 1., 0., 0., 0., 1.], out); assert_eq!(result, out); } #[test] fn clone_a_mat3() { let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let out = clone(&mat_a); assert_eq!(mat_a, out); } #[test] fn copy_values_from_a_mat3_to_another() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = copy(&mut out, &mat_a); assert_eq!(mat_a, out); assert_eq!(result, out); } #[test] fn create_mat3_from_values() { let out = from_values(1., 2., 3., 4., 5., 6., 7., 8., 9.); assert_eq!([1., 2., 3., 4., 5., 6., 7., 8., 9.], out); } #[test] fn set_mat3_with_values() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let result = set(&mut out, 1., 2., 3., 4., 5., 6., 7., 8., 9.); assert_eq!([1., 2., 3., 4., 5., 6., 7., 8., 9.], out); assert_eq!(result, out); } #[test] fn set_a_mat3_to_identity() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let ident: Mat3 = [1., 0., 0., 0., 1., 0., 0., 0., 1.]; let result = identity(&mut out); assert_eq!(ident, out); assert_eq!(result, out); } #[test] fn transpose_same_mat3() { let mut mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let mat_a_copy: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = transpose(&mut mat_a, &mat_a_copy); assert_eq!([1., 0., 1., 0., 1., 2., 0., 0., 1.], mat_a); assert_eq!(result, mat_a); } #[test] fn transpose_different_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = transpose(&mut out, &mat_a); assert_eq!([1., 0., 1., 0., 1., 2., 0., 0., 1.], out); assert_eq!(result, out); } #[test] fn adjugate_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = adjoint(&mut out, &mat_a); assert_eq!([1., 0., 0., 0., 1., 0., -1., -2., 1.], out); assert_eq!(result, out); } #[test] fn get_mat3_determinant() { let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let det: f32 = determinant(&mat_a); assert_eq!(1_f32, det); } #[test] fn multiply_two_mat3s() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let mat_b: Mat3 = [1., 0., 0., 0., 1., 0., 3., 4., 1.]; let result = multiply(&mut out, &mat_a, &mat_b); assert_eq!([1., 0., 0., 0., 1., 0., 4., 6., 1.], out); assert_eq!(result, out); } #[test] fn mul_two_mat3s() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let mat_b: Mat3 = [1., 0., 0., 0., 1., 0., 3., 4., 1.]; let result = mul(&mut out, &mat_a, &mat_b); assert_eq!([1., 0., 0., 0., 1., 0., 4., 6., 1.], out); assert_eq!(result, out); } #[test] fn mul_is_equal_to_multiply() { let mut out_a: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mut out_b: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let mat_b: Mat3 = [1., 0., 0., 0., 1., 0., 3., 4., 1.]; multiply(&mut out_a, &mat_a, &mat_b); mul(&mut out_b, &mat_a, &mat_b); assert_eq!(out_a, out_b); } #[test] fn translate_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let vec_a: Vec2 = [2., 3.]; let result = translate(&mut out, &mat_a, &vec_a); assert_eq!([1., 0., 0., 0., 1., 0., 3., 5., 1.], out); assert_eq!(result, out); } #[test] fn rotate_a_mat3() { use super::super::common::{PI}; let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = rotate(&mut out, &mat_a, PI * 0.5); assert!(equals(&[0., 1., 0., -1., 0., 0., 1., 2., 1.], &out)); assert_eq!(result, out); } #[test] fn scale_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let vec_a: Vec2 = [2., 3.]; let scale = scale(&mut out, &mat_a, &vec_a); assert_eq!([ 2., 0., 0., 0., 3., 0., 1., 2., 1.], out); assert_eq!(scale, out); } #[test] fn mat3_from_translation() { let mut out = create(); let vec_a: Vec2 = [2., 3.]; let result = from_translation(&mut out, &vec_a); assert_eq!([1., 0., 0., 0., 1., 0., 2., 3., 1.], out); assert_eq!(result, out); } #[test] fn mat3_from_rotation() { use super::super::common::{PI}; let mut out = create(); let result = from_rotation(&mut out, PI); assert!(equals(&[-1., 0., 0., 0.,-1., 0., 0., 0., 1.], &out)); assert_eq!(result, out); } #[test] fn mat3_from_scaling() { let mut out = create(); let vec_a: Vec2 = [2., 3.]; let result = from_scaling(&mut out, &vec_a); assert_eq!([ 2., 0., 0., 0., 3., 0., 0., 0., 1.], out); assert_eq!(result, out); } #[test] fn mat3_from_mat2d() { let mut out = create(); let mat_a: Mat2d = [1., 2., 3., 4., 5., 6.]; let result = from_mat2d(&mut out, &mat_a); assert_eq!([1., 2., 0., 3., 4., 0., 5., 6., 1.], out); assert_eq!(result, out); } #[test] fn mat3_from_quat() { let mut out = create(); let q: Quat = [0., -0.7071067811865475, 0., 0.7071067811865475]; let result = from_quat(&mut out, &q); assert!(equals(&[0., 0., 1., 0., 1., 0., -1., 0., 0.], &out)); assert_eq!(result, out); } #[test] fn mat3_normal_from_mat4() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat4 = [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]; let result = normal_from_mat4(&mut out, &mat_a).unwrap(); assert_eq!([1., 0., 0., 0., 1., 0., 0., 0., 1.], out); assert_eq!(result, out) } #[test] fn mat3_normal_from_mat4_none() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat4 = [-1., 3./2., 0., 0., 2./3., -1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]; let result = normal_from_mat4(&mut out, &mat_a); assert_eq!([0., 0., 0., 0., 0., 0., 0., 0., 0.], out); assert_eq!(None, result); } #[test] fn mat3_normal_from_mat4_translation_and_rotation() { use super::super::common::PI; use super::super::mat4; let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a = &mut [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]; mat4::translate(mat_a, &mat4::clone(mat_a), &[2., 4., 6.]); mat4::rotate_x(mat_a, &mat4::clone(mat_a), PI / 2_f32); let result = normal_from_mat4(&mut out, &mat_a).unwrap(); assert!(equals(&[1., 0., 0., 0., 0., 1., 0., -1., 0.], &out)); assert_eq!(result, out) } #[test] fn mat3_normal_from_mat4_translation_rotation_and_scale() { use super::super::common::PI; use super::super::mat4; let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a = &mut [1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1.]; mat4::translate(mat_a, &mat4::clone(mat_a), &[2., 4., 6.]); mat4::rotate_x(mat_a, &mat4::clone(mat_a), PI / 2_f32); mat4::scale(mat_a, &mat4::clone(mat_a), &[2., 3., 4.]); let result = normal_from_mat4(&mut out, &mat_a).unwrap(); assert!(equals(&[0.5, 0., 0., 0., 0., 0.333333, 0., -0.25, 0.], &out)); assert_eq!(result, out) } #[test] fn invert_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let result = invert(&mut out, &mat_a).unwrap(); assert_eq!([1., 0., 0., 0., 1., 0., -1., -2., 1.], out); assert_eq!(result, out); } #[test] fn invert_singular_mat2d() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [-1., 3./2., 0., 2./3., -1., 0., 0., 0., 1.]; let result = invert(&mut out, &mat_a); assert_eq!([0., 0., 0., 0., 0., 0., 0., 0., 0.], out); assert_eq!(None, result); } #[test] fn projection_of_mat3() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let result = projection(&mut out, 100.0, 200.0); assert_eq!([0.02, 0., 0., 0., -0.01, 0., -1., 1., 1.], out); assert_eq!(result, out); } #[test] fn get_mat3_string() { let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let str_a = string(&mat_a); assert_eq!("mat3(1, 0, 0, 0, 1, 0, 1, 2, 1)".to_string(), str_a); } #[test] fn calc_frob_norm_of_mat3() { let mat_a: Mat3 = [1., 0., 0., 0., 1., 0., 1., 2., 1.]; let frob_a = frob(&mat_a); assert_eq!((1_f32.powi(2) + 0_f32.powi(2) + 0_f32.powi(2) + 0_f32.powi(2) + 1_f32.powi(2) + 0_f32.powi(2) + 1_f32.powi(2) + 2_f32.powi(2) + 1_f32.powi(2)).sqrt(), frob_a); } #[test] fn add_two_mat3s() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [10., 11., 12., 13., 14., 15., 16., 17., 18.]; let result = add(&mut out, &mat_a, &mat_b); assert_eq!([11., 13., 15., 17., 19., 21., 23., 25., 27.], out); assert_eq!(result, out); } #[test] fn subtract_two_mat3s() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [10., 11., 12., 13., 14., 15., 16., 17., 18.]; let result = subtract(&mut out, &mat_a, &mat_b); assert_eq!([-9., -9., -9., -9., -9., -9., -9., -9., -9.], out); assert_eq!(result, out); } #[test] fn sub_two_mat3s() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [10., 11., 12., 13., 14., 15., 16., 17., 18.]; let result = sub(&mut out, &mat_a, &mat_b); assert_eq!([-9., -9., -9., -9., -9., -9., -9., -9., -9.], out); assert_eq!(result, out); } #[test] fn sub_is_equal_to_subtract() { let mut out_a: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mut out_b: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [10., 11., 12., 13., 14., 15., 16., 17., 18.]; sub(&mut out_a, &mat_a, &mat_b); subtract(&mut out_b, &mat_a, &mat_b); assert_eq!(out_a, out_b); } #[test] fn multiply_mat3_by_scalar() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let result = multiply_scalar(&mut out, &mat_a, 2.); assert_eq!([2., 4., 6., 8., 10., 12., 14., 16., 18.], out); assert_eq!(result, out); } #[test] fn multiply_mat3_by_scalar_and_add() { let mut out: Mat3 = [0., 0., 0., 0., 0., 0., 0., 0., 0.]; let mat_a: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [10., 11., 12., 13., 14., 15., 16., 17., 18.]; let result = multiply_scalar_and_add(&mut out, &mat_a, &mat_b, 0.5); assert_eq!([6., 7.5, 9., 10.5, 12., 13.5, 15., 16.5, 18.], out); assert_eq!(result, out); } #[test] fn mat3s_are_exact_equal() { let mat_a: Mat3 = [0., 1., 2., 3., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [0., 1., 2., 3., 5., 6., 7., 8., 9.]; let r0 = exact_equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat3s_are_not_exact_equal() { let mat_a: Mat3 = [0., 1., 2., 3., 4., 5., 6., 7., 8.]; let mat_b: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let r0 = exact_equals(&mat_a, &mat_b); assert!(!r0); } #[test] fn mat3s_are_equal() { let mat_a: Mat3 = [0., 1., 2., 3., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [0., 1., 2., 3., 5., 6., 7., 8., 9.]; let r0 = equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat3s_are_equal_enough() { let mat_a: Mat3 = [0., 1., 2., 3., 5., 6., 7., 8., 9.]; let mat_b: Mat3 = [1_f32*10_f32.powi(-16), 1., 2., 3., 5., 6., 7., 8., 9.]; let r0 = equals(&mat_a, &mat_b); assert!(r0); } #[test] fn mat3s_are_not_equal() { let mat_a: Mat3 = [0., 1., 2., 3., 4., 5., 6., 7., 8.]; let mat_b: Mat3 = [1., 2., 3., 4., 5., 6., 7., 8., 9.]; let r0 = equals(&mat_a, &mat_b); assert!(!r0); } }
type Id = usize; use material::Material; use shape::Shape; use ray::Ray; use color::Color; use vector::Vector3; use ray::Intersection; use light::Light; #[derive(Debug)] pub struct Scene { objects: Vec<Id>, materials: Vec<Option<Material>>, shapes: Vec<Option<Shape>>, lights: Vec<Light> } const MAX_BOUNCES: usize = 10; const MAX_LIGHT_SAMPLES: usize = 40; const MAX_BOUNCE_SAMPLES: usize = 10; struct RayProperties { bounces: usize, light_samples: usize, bounce_samples: usize } impl Scene { pub fn new() -> Scene { Scene { objects: Vec::new(), materials: Vec::new(), shapes: Vec::new(), lights: Vec::new(), } } pub fn add_object(&mut self, shape: Shape, material: Material) -> Id { let id = self.generate_next_id(); self.materials[id] = Some(material); self.shapes[id] = Some(shape); id } pub fn add_light(&mut self, light: Light) { self.lights.push(light); } pub fn trace(&self, ray: Ray) -> Color { let properties = RayProperties { bounces: MAX_BOUNCES, light_samples: MAX_LIGHT_SAMPLES, bounce_samples: MAX_BOUNCE_SAMPLES, }; if let Some(color) = self.trace_ray_color(&ray, properties) { color } else { Color { r: 0.25 * ray.direction.x.abs(), g: 0.25 * ray.direction.y.abs(), b: 0.25 * ray.direction.z.abs() } } } } impl Scene { fn generate_next_id(&mut self) -> Id { let id = self.objects.len(); self.resize_to_fit(id); id } fn resize_to_fit(&mut self, id: Id) { self.objects.push(id); self.materials.push(None); self.shapes.push(None); } fn trace_ray_color(&self, ray: &Ray, properties: RayProperties) -> Option<Color> { if properties.bounces == 0 { return None; } if let Some((entry, object)) = self.get_intersection(&ray) { if let Some(ref material) = self.materials[object] { let ambient_color = material.color.apply_brightness(0.1); let point = entry.point - ray.direction * 0.0001; let adjusted_entry = Intersection {point, ..entry}; let light_color = self.light_color(adjusted_entry.clone(), properties.light_samples) .multiply(material.color); let bounce_color = self.bounce_color(ray, adjusted_entry, properties, material); return Some(ambient_color.add(light_color).add(bounce_color)); } } None } fn get_intersection(&self, ray: &Ray) -> Option<(Intersection, Id)> { let mut intersections = Vec::new(); for &object in self.objects.iter() { if let Some(ref shape) = self.shapes[object] { if let Some((entry, _)) = shape.first_intersection(ray) { if entry.distance > 0.0 { intersections.push((entry, object)); } } } } intersections.into_iter() .min_by(|(a, _), (b, _)| { a.distance.partial_cmp(&b.distance).unwrap() }) } fn light_color(&self, entry: Intersection, samples: usize) -> Color { let mut color = Color::black(); for light in self.lights.iter() { for _ in 0..samples { if let Some(distance) = self.distance_to_light(entry.point, light) { let diffuse = Vector3::dot(entry.point - light.sample_point(), -entry.normal); let brightness = light.brightness(distance) * if diffuse > 0.0 {diffuse} else {0.0}; let light_color = light.color().apply_brightness(brightness / samples as f64); color = color.add(light_color); } } } color } fn bounce_color( &self, ray: &Ray, entry: Intersection, properties: RayProperties, material: &Material ) -> Color { let mut bounce_color = Color::black(); for _ in 0..properties.bounce_samples { let bounce_ray = Ray::scatter(ray, entry.clone(), material.roughness); let bounce_properties = RayProperties { bounces: properties.bounces - 1, light_samples: (properties.light_samples as f64 / 4.0).ceil() as usize, bounce_samples: (properties.bounce_samples as f64 / 5.0).ceil() as usize, }; if let Some(color) = self.trace_ray_color(&bounce_ray, bounce_properties) { bounce_color = bounce_color.add( color.apply_brightness(material.reflectiveness / properties.bounce_samples as f64) ); } } bounce_color } fn distance_to_light(&self, point: Vector3, light: &Light) -> Option<f64> { let delta = light.sample_point() - point; let light_ray = Ray { origin: point, direction: delta.normal(), }; let light_depth = delta.length(); if let Some((entry, _)) = self.get_intersection(&light_ray) { if light_depth < entry.distance { Some(light_depth) } else { None } } else { Some(light_depth) } } }
use anyhow::{Context, Result}; use futures::StreamExt; use kafka_settings::{producer, KafkaSettings}; use polygon::ws::{Aggregate, Connection, PolygonMessage, PolygonStatus, Quote, Trade}; use rdkafka::producer::FutureRecord; use std::time::Duration; use tracing::{debug, error}; pub async fn run( settings: &KafkaSettings, paper_settings: &Option<KafkaSettings>, connection: Connection<'_>, ) -> Result<()> { let prod_producer = producer(settings)?; let paper_producer = paper_settings.as_ref().map(|s| producer(s).ok()).flatten(); let ws = connection.connect().await.context("Failed to connect")?; let (_, stream) = ws.split::<String>(); stream .for_each_concurrent( 10_000, // Equal to 1/10 the max buffer size in rdkafka |message| async { match message { Ok(polygon_message) => { if let PolygonMessage::Status { status, message } = &polygon_message { if let PolygonStatus::MaxConnections | PolygonStatus::ForceDisconnect = status { panic!("Disconnecting: {}", message) } } let topic = get_topic(&polygon_message); let key = get_key(&polygon_message); let payload = serde_json::to_string(&polygon_message); match payload { Ok(payload) => { debug!(%payload, %key, %topic); let res = prod_producer .send( FutureRecord::to(topic).key(key).payload(&payload), Duration::from_secs(0), ) .await; if let Err((e, _)) = res { let e = e.into(); sentry_anyhow::capture_anyhow(&e); error!(%e, %payload) } if let Some(paper_producer) = paper_producer.as_ref() { let res = paper_producer .send( FutureRecord::to(topic).key(key).payload(&payload), Duration::from_secs(0), ) .await; if let Err((e, _)) = res { let e = e.into(); sentry_anyhow::capture_anyhow(&e); error!(%e, %payload) } } } Err(e) => { let e = e.into(); sentry_anyhow::capture_anyhow(&e); error!(%e) } } } Err(e) => match e { polygon::errors::Error::Serde { .. } => { let e = e.into(); sentry_anyhow::capture_anyhow(&e); error!(%e) } _ => panic!("Failed to receive message from the WebSocket: {}", e), }, } }, ) .await; Ok(()) } fn get_topic(s: &PolygonMessage) -> &str { match s { PolygonMessage::Trade { .. } => "trades", PolygonMessage::Quote { .. } => "quotes", PolygonMessage::Second { .. } => "second-aggregates", PolygonMessage::Minute { .. } => "minute-aggregates", PolygonMessage::Status { .. } => "meta", } } fn get_key(s: &PolygonMessage) -> &str { match s { PolygonMessage::Trade(Trade { symbol, .. }) => symbol, PolygonMessage::Quote(Quote { symbol, .. }) => symbol, PolygonMessage::Second(Aggregate { symbol, .. }) => symbol, PolygonMessage::Minute(Aggregate { symbol, .. }) => symbol, PolygonMessage::Status { .. } => "status", // unkeyed on purpose to preserve ordering } }
use std::{ ops::Deref, sync::{Arc, Mutex}, thread::{spawn, yield_now}, }; use criterion::{black_box, criterion_group, criterion_main, Criterion}; #[cfg(feature = "arrayvec")] use lock_many::lock_many_arrayvec; use lock_many::lock_many_vec; fn run_parallel_lock_many<const THREAD_NUM: usize>(n: u64, swapped: bool) { let m1 = Arc::new(Mutex::new(1u64)); let m2 = Arc::new(Mutex::new(1u64)); let mut threads = Vec::with_capacity(THREAD_NUM); for i in 0..THREAD_NUM { let mut m1a = m1.clone(); let mut m2a = m2.clone(); threads.push(spawn(move || { if swapped && i & 1 == 0 { std::mem::swap(&mut m1a, &mut m2a); } for _ in 0..n { let mut g = lock_many_vec(&[m1a.deref(), m2a.deref()]).unwrap(); let fib = g[0].wrapping_add(*g[1]); *g[1] = *g[0]; *g[0] = fib; } })); } threads.into_iter().for_each(|t| { t.join().unwrap(); }); } #[cfg(feature = "arrayvec")] fn run_parallel_lock_many_arrayvec<const THREAD_NUM: usize>(n: u64, swapped: bool) { let m1 = Arc::new(Mutex::new(1u64)); let m2 = Arc::new(Mutex::new(1u64)); let mut threads = Vec::with_capacity(THREAD_NUM); for i in 0..THREAD_NUM { let mut m1a = m1.clone(); let mut m2a = m2.clone(); threads.push(spawn(move || { if swapped && i & 1 == 0 { std::mem::swap(&mut m1a, &mut m2a); } for _ in 0..n { let mut g = lock_many_arrayvec::<_, THREAD_NUM>(&[m1a.deref(), m2a.deref()]).unwrap(); let fib = g[0].wrapping_add(*g[1]); *g[1] = *g[0]; *g[0] = fib; } })); } threads.into_iter().for_each(|t| { t.join().unwrap(); }); } // This is "persistent" algorithm from the https://howardhinnant.github.io/dining_philosophers.html // However, it doesn't use any vector (even arrayvec), being simple and non-universal. fn run_parallel_dumb<const THREAD_NUM: usize>(n: u64, swapped: bool) { let m1 = Arc::new(Mutex::new(1u64)); let m2 = Arc::new(Mutex::new(1u64)); let mut threads = Vec::with_capacity(THREAD_NUM); for i in 0..THREAD_NUM { let mut m1a = m1.clone(); let mut m2a = m2.clone(); threads.push(spawn(move || { if swapped && i & 1 == 0 { std::mem::swap(&mut m1a, &mut m2a); } for _ in 0..n { let mut g = loop { let g1 = m1a.lock().unwrap(); match m2a.try_lock() { Ok(g2) => break [g1, g2], Err(_) => { yield_now(); continue; } } }; let fib = g[0].wrapping_add(*g[1]); *g[1] = *g[0]; *g[0] = fib; } })); } threads.into_iter().for_each(|t| { t.join().unwrap(); }); } fn criterion_benchmark(c: &mut Criterion) { const COUNT: u64 = 20000; #[cfg(not(benchmark_swapped))] const SWAPPED: bool = false; #[cfg(benchmark_swapped)] const SWAPPED: bool = true; c.bench_function("run_parallel_lock_many", |b| { b.iter(|| run_parallel_lock_many::<2>(black_box(COUNT), SWAPPED)) }); c.bench_function("run_parallel_dumb", |b| { b.iter(|| run_parallel_dumb::<2>(black_box(COUNT), SWAPPED)) }); #[cfg(feature = "arrayvec")] c.bench_function("run_parallel_arrayvec", |b| { b.iter(|| run_parallel_lock_many_arrayvec::<2>(black_box(COUNT), SWAPPED)) }); c.bench_function("run_parallel_lock_many4", |b| { b.iter(|| run_parallel_lock_many::<4>(black_box(COUNT), SWAPPED)) }); c.bench_function("run_parallel_dumb4", |b| { b.iter(|| run_parallel_dumb::<4>(black_box(COUNT), SWAPPED)) }); #[cfg(feature = "arrayvec")] c.bench_function("run_parallel_arrayvec4", |b| { b.iter(|| run_parallel_lock_many_arrayvec::<4>(black_box(COUNT), SWAPPED)) }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);