text
stringlengths
8
4.13M
use proconio::{input, marker::Chars}; fn main() { input! { n: usize, s: Chars, }; let t = s.iter().filter(|&&ch| ch == 'T').count(); let a = s.iter().filter(|&&ch| ch == 'A').count(); if t > a { println!("T"); } else if t < a { println!("A"); } else if s[n - 1] == 'T' { println!("A"); } else { println!("T"); } }
use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; pub fn establish_connection() -> mongodb::coll::Collection { let client = Client::connect("mongo", 27017) .expect("Failed to initialize standalone client."); client.db("test").collection("tmp") }
#[macro_use] extern crate criterion; extern crate geo; use geo::prelude::*; fn criterion_benchmark(c: &mut criterion::Criterion) { c.bench_function("vincenty distance f32", |bencher| { let a = geo::Point::<f32>::new(17.107558, 48.148636); let b = geo::Point::<f32>::new(16.372477, 48.208810); bencher.iter(|| { let _ = a.vincenty_distance(&b); }); }); c.bench_function("vincenty distance f64", |bencher| { let a = geo::Point::<f64>::new(17.107558, 48.148636); let b = geo::Point::<f64>::new(16.372477, 48.208810); bencher.iter(|| { let _ = a.vincenty_distance(&b); }); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
use piston_window::{rectangle, Context, G2d}; use piston_window::types::Color; // use std::cmp; use game::GAME_SIZE; const TILE_COLOR: Color = [(15.0/255.0), (20.0/255.0), (45.0/255.0), 1.0]; const PLAYER1_TILE_COLOR: Color = [(20.0/255.0), 0.75, (45.0/255.0), 1.0]; const PLAYER2_TILE_COLOR: Color = [(15.0/255.0), (45.0/255.0), 0.75, 1.0]; #[derive(Debug)] pub enum TileState { Player1, Player2, None, } pub fn variant_eq(a: &TileState, b: &TileState) -> bool { match (a, b) { (&TileState::Player1, &TileState::Player1) => true, (&TileState::Player2, &TileState::Player2) => true, (&TileState::None, &TileState::None) => true, _ => false, } } // impl PartialEq for TileState { // fn eq(&self, tile_state: &TileState) -> bool { // self == tile_state // } // } // #[derive(PartialEq)] pub struct Tile { pub row: i32, pub col: i32, pub tile_size: f64, pub offset_size: f64, pub clicked: bool, pub tile_state: TileState, } impl Tile { pub fn new(row: i32, col: i32, tile_size: f64, offset_size: f64) -> Tile { Tile { row, col, tile_size, offset_size, tile_state: TileState::None, clicked: false, } } pub fn clicked(&mut self, player: &TileState) { match self.tile_state { TileState::None => { self.clicked = true; self.tile_state = match player { TileState::Player1 => TileState::Player1, TileState::Player2 => TileState::Player2, _ => TileState::None, }; }, _ => (), } } pub fn draw(&self, con: &Context, g: &mut G2d) { let color = match self.tile_state { TileState::Player1 => PLAYER1_TILE_COLOR, TileState::Player2 => PLAYER2_TILE_COLOR, _ => TILE_COLOR, }; rectangle( color, [ (self.row as f64 * self.tile_size * GAME_SIZE) + (self.offset_size * GAME_SIZE * ((self.row + 1) as f64)), (self.col as f64 * self.tile_size * GAME_SIZE) + (self.offset_size * GAME_SIZE * ((self.col + 1) as f64)), (self.tile_size * GAME_SIZE), (self.tile_size * GAME_SIZE), ], con.transform, g, ); } // pub fn update(&mut self) { // } }
extern crate piston; extern crate glutin_window; extern crate graphics; extern crate opengl_graphics; use piston::window::WindowSettings; use glutin_window::GlutinWindow; use piston::event_loop::{Events, EventSettings, EventLoop}; use opengl_graphics::{OpenGL, GlGraphics, Filter, TextureSettings, GlyphCache}; use piston::input::RenderEvent; use rand::seq::SliceRandom; pub use crate::gameboard::Gameboard; mod gameboard; pub use crate::gameboard_controller::GameboardController; mod gameboard_controller; pub use crate::gameboard_view::{GameboardView, GameboardViewSettings}; mod gameboard_view; fn main() { let opengl = OpenGL::V3_2; let settings = WindowSettings::new("Sudoku", [720; 2]).graphics_api(opengl).exit_on_esc(true); let mut window: GlutinWindow = settings.build().expect("Could not create window"); let mut events = Events::new(EventSettings::new().lazy(true)); let mut gl = GlGraphics::new(opengl); // generate sudoku pub fn hor_check(row: &Vec<(u8, bool)>, val: u8) -> bool{ for i in 0..9 { if row[i].0 == val{ return false; } } true } pub fn ver_check(tab: &Vec<Vec<(u8, bool)>>, ind: usize, val: u8) -> bool{ for i in 0..9 { if tab[i][ind].0 == val{ return false; } } true } pub fn box_check(tab: &Vec<Vec<(u8, bool)>>, ind: [usize; 2], val: u8) -> bool{ let section_x = ind[0] / 3; let section_y = ind[1] / 3; for i in (section_x * 3)..(section_x * 3 + 3){ for j in (section_y * 3)..(section_y * 3 + 3){ if tab[i][j].0 == val{ return false; } } } true } pub fn fill_cells(tab: &mut Vec<Vec<(u8, bool)>>, mut ind_i: usize, mut ind_j: usize) -> bool { if ind_j >= 9 && ind_i < 8 { ind_i += 1; ind_j = 0; } if ind_i >= 9 && ind_j >= 9 { return true; } if ind_i < 3 { if ind_j < 3 { ind_j = 3; } } else if ind_i < 6 { if ind_j == 3 { ind_j += 3; } } else { if ind_j == 6 { ind_i += 1; ind_j = 0; if ind_i >= 9 { return true; } } } for num in 1..10 { if box_check(tab, [ind_i, ind_j], num) && hor_check(&tab[ind_i], num) && ver_check(tab, ind_j, num) { tab[ind_i][ind_j].0 = num; if fill_cells(tab, ind_i, ind_j + 1) { return true; } tab[ind_i][ind_j].0 = 0; } } return false; } let mut cells_gen: Vec<Vec<(u8, bool)>> = vec![vec![(0, false); 9]; 9]; let mut ind: usize = 0; for _i in 0..3 { let mut vals = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; for j in 0..9 { let a = *vals.choose(&mut rand::thread_rng()).unwrap() as u8; cells_gen[(j / 3) + ind][(j % 3) + ind].0 = a; vals.remove(vals.iter().position(|&x| x == a).unwrap()); } ind += 3; } fill_cells(&mut cells_gen, 0, 3); let mut positions: Vec<(usize, usize)> = vec![(0, 0); 81]; let mut ind = 0; for i in 0..9 { for j in 0..9 { positions[ind] = (i, j); ind += 1; } } for i in 0..9 { println!("{:?}", cells_gen[i]); } for _i in 0..2 { let aa = *positions.choose(&mut rand::thread_rng()).unwrap(); cells_gen[aa.0][aa.1] = (0, true); positions.remove(positions.iter().position(|&x| x == aa).unwrap()); } let cells_color = cells_gen.clone(); let gameboard = Gameboard::new(cells_gen); let mut gameboard_controller = GameboardController::new(gameboard); let gameboard_view_settings = GameboardViewSettings::new(); let gameboard_view = GameboardView::new(gameboard_view_settings, cells_color); let texture_settings = TextureSettings::new().filter(Filter::Nearest); let ref mut glyphs = GlyphCache::new("CollegiateBlackFLF.ttf", (), texture_settings).expect("Could not load font"); while let Some(e) = events.next(&mut window) { gameboard_controller.event(gameboard_view.settings.size, &e); if let Some(args) = e.render_args() { gl.draw(args.viewport(), |c, g| { use graphics::{clear}; clear([1.0; 4], g); gameboard_view.draw(&gameboard_controller, glyphs, &c, g); }); } } }
use sqs_executor::{ cache::NopCache, event_handler::{ CompletedEvents, EventHandler, }, }; use crate::{ generator::OSQueryGenerator, metrics::OSQueryGeneratorMetrics, tests::utils, }; #[tokio::test] async fn test_subgraph_generation_process_create() { let metrics = OSQueryGeneratorMetrics::new("osquery-generator"); let mut generator = OSQueryGenerator::new(NopCache {}, metrics); let logs = utils::read_osquery_test_data("process_create.zstd").await; let mut completion = CompletedEvents::default(); let output_event = generator.handle_event(logs, &mut completion).await; match &output_event { Ok(subgraph) => { assert!(!subgraph.is_empty(), "Generated subgraph was empty.") } Err(Ok((subgraph, e))) => { assert!( !subgraph.is_empty(), "Generated subgraph was empty and errors were generated" ); panic!( "OSQuery subgraph generator failed to generate subgraph with error: {}", e ); } Err(Err(e)) => panic!( "OSQuery subgraph generator failed to generate subgraph with error: {}", e ), }; }
use super::utills::{get_points, started_check}; use prelude::*; use serenity::framework::standard::CreateGroup; use store::UsersInfo; use utills::{success, warn}; struct GiveCommand; impl Command for GiveCommand { fn execute(&self, ctx: &mut Context, msg: &Message, mut args: Args) -> CommandResult { let target = match msg.mentions.first() { Some(user) => user, None => { warn(msg.channel_id, "You must mention a user", Some("❓👤❓")); return Ok(()); } }; let give_points = match args.find::<usize>() { Ok(points) => points, Err(_) => { warn(msg.channel_id, "You must supply an amount of points", Some("❓💵❓")); return Ok(()); } }; // if target.id == msg.author.id { // let _ = warn( // msg.channel_id, // "You can't give yourself points.", // Some("🤦"), // ); // } let user_points = get_points(ctx, msg.author.id).unwrap(); if user_points < give_points { let _ = warn(msg.channel_id, "You don't have enough points", None); return Ok(()); }; { let mut data = ctx.data.lock(); let users = data.get_mut::<UsersInfo>().unwrap(); { let target_user_points = match users.get_mut(&target.id.0) { Some(target_user_points) => target_user_points, None => { let _ = warn( msg.channel_id, "They haven't started collecting Boogie Points yet", None, ); return Ok(()); } }; target_user_points.points += give_points; } let giver_user_points = users.get_mut(&msg.author.id.0).unwrap(); giver_user_points.points -= give_points; }; success( msg.channel_id, format!( "You've successfully given `{}` Boogie Points to <@{}>", give_points, target.id ), Some("🤑 ➡️ 😌"), ); // let _ = msg.channel_id.send_message(|m| { // m.embed(|e| { // e.color(WARN_COLOR).title("😟️").description(format!( // "Are you sure you want to give {} to <@{}>", // give_points, target.id // )) // }).reactions(vec!['✅', '❌']) // }); Ok(()) } } pub fn register_command(sf: CreateGroup) -> CreateGroup { sf.command("give", |c| c.check(started_check).cmd(GiveCommand).desc("Gives a set amount of points to someone.").example("@someone 100").usage("<someone> <amount of points>")) }
use crate::Vec3; use crate::vec3::{self, Point3}; use crate::color::{Color}; use crate::perlin::{Perlin}; pub trait Texture { fn value(&self, u: f32, v: f32, p: &Point3) -> Color; } pub struct SolidColor { color: Color } impl SolidColor { pub fn new_from_color(c: Color) -> Self { SolidColor { color: c } } pub fn new_from_raw(r: f32, g: f32, b: f32) -> Self { SolidColor { color: Color(vec3::Vec3{ x: r, y: g, z: b }) } } } impl Texture for SolidColor { fn value(&self, _u: f32, _v: f32, _p: &Point3) -> Color { self.color } } pub struct CheckerTexture { odd: Box<dyn Texture>, even: Box<dyn Texture>, } impl CheckerTexture { pub fn new(c1: Color, c2: Color) -> Self { Self { odd: Box::new(SolidColor::new_from_color(c1)), even: Box::new(SolidColor::new_from_color(c2)), } } } impl Texture for CheckerTexture { fn value(&self, u: f32, v: f32, p: &Point3) -> Color { // What is sines? let sines = (10. * p.x).sin() * (10. * p.y).sin() * (10. * p.z).sin(); if sines < 0. { self.odd.value(u, v, p) } else { self.even.value(u, v, p) } } } pub struct NoiseTexture { pub noise: Perlin, pub scale: f32, } impl Texture for NoiseTexture { fn value(&self, _u: f32, _v: f32, p: &Point3) -> Color { Color(Vec3::new(1., 1., 1.) * 0.5 * (1. + (self.scale * p.z + 10. * self.noise.turb(&(self.scale * *p), 7)).sin())) } } use image::{open, DynamicImage, GenericImageView, Pixel, Rgb}; pub struct ImageTexture { pub data: DynamicImage, } fn clamp(x: f32, min: f32, max: f32) -> f32 { if x < min { return min; } if x > max { return max; } return x; } impl ImageTexture { pub fn new(fname: &str) -> Self { ImageTexture { data: open(fname).unwrap(), } } } impl Texture for ImageTexture { fn value(&self, u: f32, v: f32, p: &Point3) -> Color { let u = clamp(u, 0., 1.); let v = 1.0 - clamp(v, 0., 1.); let (width, height) = self.data.dimensions(); let mut i = (u * width as f32) as u32; let mut j = (v * height as f32) as u32; if i >= width { i = width - 1; } if j >= height { j = height - 1; } let color_scale = 1. / 255.; let Rgb([r, g, b]) = self.data.get_pixel(i, j).to_rgb(); Color(Vec3{ x: r as f32 * color_scale, y: g as f32 * color_scale, z: b as f32 * color_scale}) } }
//! Configuration. use std::{collections::HashMap, fs::File, io::Read, path::Path}; use serde_derive::Deserialize; #[derive(Debug, Deserialize)] pub struct Config { pub fcm: FcmConfig, pub apns: ApnsConfig, pub hms: Option<HashMap<String, HmsConfig>>, pub threema_gateway: Option<ThreemaGatewayConfig>, pub influxdb: Option<InfluxdbConfig>, } #[derive(Debug, Deserialize)] pub struct FcmConfig { pub api_key: String, } #[derive(Debug, Deserialize)] pub struct ApnsConfig { pub keyfile: String, pub key_id: String, pub team_id: String, } #[derive(Debug, Clone, Deserialize)] pub struct HmsConfig { pub client_id: String, pub client_secret: String, pub high_priority: Option<bool>, } #[derive(Clone, Debug, Deserialize)] pub struct ThreemaGatewayConfig { pub base_url: String, pub identity: String, pub secret: String, pub private_key_file: String, } #[derive(Debug, Deserialize)] pub struct InfluxdbConfig { pub connection_string: String, pub user: String, pub pass: String, pub db: String, } impl Config { pub fn load(path: &Path) -> Result<Config, String> { let mut file = File::open(path).map_err(|e| e.to_string())?; let mut contents = String::new(); file.read_to_string(&mut contents) .map_err(|e| e.to_string())?; toml::from_str(&contents).map_err(|e| e.to_string()) } }
use crate::render::{RenderSubsystem, ReconfigureEvent, Framebuffer}; pub struct BloomSubsystem { pub max_octaves: u32, pub framebuffer_bloom_temp: Framebuffer, pub framebuffers_bloom_levels: Vec<Framebuffer>, } impl BloomSubsystem { pub fn new() -> BloomSubsystem { BloomSubsystem { max_octaves: 6, framebuffer_bloom_temp: Framebuffer::new(0, 0), framebuffers_bloom_levels: Vec::with_capacity(6), } } } impl RenderSubsystem for BloomSubsystem { fn initialize(&mut self) { // Do nothing } fn deinitialize(&mut self) { // Do nothing } fn reconfigure(&mut self, event: ReconfigureEvent<'_>) { let base_width = event.resolution.0; let base_height = event.resolution.1; // Resize framebuffers self.framebuffer_bloom_temp.resize(base_width, base_height); if !self.framebuffer_bloom_temp.is_allocated() { self.framebuffer_bloom_temp.allocate(); } } } pub struct BloomOctave { }
use core::cmp; use core::fmt; use core::marker::PhantomData; use core::mem; use core::ptr::NonNull; #[cfg(not(feature = "std"))] use alloc::boxed::Box; use crate::{Reclaim, Record}; //////////////////////////////////////////////////////////////////////////////////////////////////// // Retired //////////////////////////////////////////////////////////////////////////////////////////////////// /// A type-erased fat pointer to a retired record. pub struct Retired<R>(NonNull<dyn Any + 'static>, PhantomData<R>); /********** impl inherent *************************************************************************/ impl<R: Reclaim + 'static> Retired<R> { /// Creates a new [`Retired`] record from a raw pointer. /// /// # Safety /// /// The caller has to ensure numerous safety invariants in order for a /// [`Retired`] record to be used safely: /// /// - the given `record` pointer **must** point to a valid heap allocated /// value /// - the record **must** have been allocated as part of a [`Record`] of /// the appropriate [`LocalReclaim`] implementation /// - *if* the type of the retired record implements [`Drop`] *and* contains /// any non-static references, it must be ensured that these are **not** /// accessed by the [`drop`][Drop::drop] function. #[inline] pub unsafe fn new_unchecked<'a, T: 'a>(record: NonNull<T>) -> Self { let any: NonNull<dyn Any + 'a> = Record::<T, R>::from_raw_non_null(record); let any: NonNull<dyn Any + 'static> = mem::transmute(any); Self(any, PhantomData) } /// Converts a retired record to a raw pointer. /// /// Since retired records are type-erased trait object (fat) pointers to /// retired values that should no longer be used, only the 'address' part /// of the pointer is returned, i.e. a pointer to an `()`. #[inline] pub fn as_ptr(&self) -> *const () { self.0.as_ptr() as *mut () as *const () } /// Returns the numeric representation of the retired record's memory /// address. #[inline] pub fn address(&self) -> usize { self.0.as_ptr() as *mut () as usize } /// Reclaims the retired record by dropping it and de-allocating its memory. /// /// # Safety /// /// This method **must** not be called more than once or when some other /// thread or scope still has some reference to the record. #[inline] pub unsafe fn reclaim(&mut self) { mem::drop(Box::from_raw(self.0.as_ptr())); } } /********** impl PartialEq ************************************************************************/ impl<R: Reclaim + 'static> PartialEq for Retired<R> { #[inline] fn eq(&self, other: &Self) -> bool { self.as_ptr().eq(&other.as_ptr()) } } /********** impl PartialOrd ***********************************************************************/ impl<R: Reclaim + 'static> PartialOrd for Retired<R> { #[inline] fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> { self.as_ptr().partial_cmp(&other.as_ptr()) } } /********** impl Ord ******************************************************************************/ impl<R: Reclaim + 'static> Ord for Retired<R> { #[inline] fn cmp(&self, other: &Self) -> cmp::Ordering { self.as_ptr().cmp(&other.as_ptr()) } } /********** impl Eq *******************************************************************************/ impl<R: Reclaim + 'static> Eq for Retired<R> {} /********** impl Debug ****************************************************************************/ impl<R: Reclaim + 'static> fmt::Debug for Retired<R> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Retired").field("address", &self.as_ptr()).finish() } } /********** impl Display **************************************************************************/ impl<R: Reclaim + 'static> fmt::Display for Retired<R> { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.as_ptr(), f) } } //////////////////////////////////////////////////////////////////////////////////////////////////// // Any (trait) //////////////////////////////////////////////////////////////////////////////////////////////////// trait Any {} impl<T> Any for T {}
#![no_main] #![feature(start)] extern crate olin; use anyhow::{anyhow, Result}; use olin::{entrypoint, env, runtime, stdio, time}; use std::io::Write; entrypoint!(); fn main() -> Result<()> { let mut out = stdio::out(); if let Ok(url) = env::get("GEMINI_URL") { write!(out, "20 text/gemini\n# WebAssembly Runtime Information\n")?; write!(out, "URL: {}\n", url)?; write!( out, "Server software: {}\n", env::get("SERVER_SOFTWARE").unwrap() )?; } let mut rt_name = [0u8; 32]; let runtime_name = runtime::name_buf(rt_name.as_mut()) .ok_or_else(|| anyhow!("Runtime name larger than 32 byte limit"))?; write!(out, "CPU: {}\n", "wasm32").expect("write to work"); write!( out, "Runtime: {} {}.{}\n", runtime_name, runtime::spec_major(), runtime::spec_minor() )?; write!(out, "Now: {}\n", time::now().to_rfc3339())?; Ok(()) }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[cfg(feature = "ApplicationModel_Resources_Core")] pub mod Core; #[cfg(feature = "ApplicationModel_Resources_Management")] pub mod Management; #[link(name = "windows")] extern "system" {} pub type ResourceLoader = *mut ::core::ffi::c_void;
#![experimental] /// Packs a protocol command into a single string. #[experimental] pub fn pack(word: &str, args: &[&str]) -> String { // Escape all the arguments first. let mut vargs = args.iter() .map(|a| format_argument(*a)) .collect::<Vec<String>>(); // Don't escape the word, as it is guaranteed not to contain a special // character by the BAPS3 spec. vargs.insert(0, word.to_string()); vargs.connect(" ") } fn is_special_char(c: char) -> bool { c.is_whitespace() || "'\"\\".contains_char(c) } fn has_special_chars(cs: &str) -> bool { cs.chars().any(is_special_char) } fn escape_string(arg: &str) -> String { ["'", &*arg.replace("'", "'\\''"), "'"].concat() } fn format_argument(arg: &str) -> String { if has_special_chars(arg) { escape_string(arg) } else { arg.to_string() } } #[cfg(test)] mod test { use super::pack; /// Test the emitter on a 'load' request. /// /// A 'load' request has a file-path argument, which is a good use case for /// single quoting. #[test] fn pack_load_request() { assert_eq!(pack("load", &[ "C:\\Users\\Test\\Music\\example.mp3" ]), "load 'C:\\Users\\Test\\Music\\example.mp3'" .to_string()) } /// Test the emitter on a 'play' request. /// /// A 'play' request has no arguments, and should be passed through /// verbatim. #[test] fn pack_play_request() { assert_eq!(pack("play", &[]), "play".to_string()) } /// Ensure that the emitter emits double quotes correctly. /// /// Since the emitter uses single-quotes, double quotes need not and should /// not be escaped especially. #[test] fn pack_double_quotes() { assert_eq!(pack("foo", &["a\"bar\"b"]), "foo 'a\"bar\"b'".to_string()); } /// Ensure that the emitter emits single quotes correctly. /// /// Since the emitter uses single-quotes, single quotes need to be escaped. /// The easiest, most stupid way of doing this is to emit '\''. #[test] fn pack_single_quotes() { assert_eq!(pack("foo", &["a'bar'b"]), "foo 'a'\\''bar'\\''b'".to_string()); } /// Ensure that the emitter doesn't emit quotes for arguments unless necessary. #[test] fn pack_unquoted() { assert_eq!(pack("foo", &["bar", "baz", "yadda"]), "foo bar baz yadda".to_string()); } }
pub mod window; pub use window::{Window,canvas::{Canvas,content::{Content,SimpleCamera}}}; pub mod camera; pub use camera::Camera;
pub const DEFINITE_ARTICLE: &str = "the"; const VOWELS: [char; 6] = ['a', 'e', 'i', 'o', 'u', 'y']; pub trait Display { fn name(&self) -> String; fn default_article(&self) -> &str { self.indefinite_article() } fn indefinite_article(&self) -> &str { let first = self.name().chars().nth(0); match first { None => "a", Some(letter) => match VOWELS.contains(&letter) { true => "an", false => "a", }, } } } pub trait DisplayWeapon: Display { fn display_offensive_action_1st(&self) -> String { "bash".to_owned() } fn display_offensive_action_2nd(&self) -> String { let first_person = self.display_offensive_action_1st(); let last = first_person.chars().last(); match last { None => "".to_owned(), Some(letter) => match VOWELS.contains(&letter) { true => format!("{}s", &first_person), false => format!("{}es", &first_person), }, } } }
// public importable router pub mod router;
use criterion::{black_box, criterion_group, criterion_main, Criterion}; use day_16::{self, INPUT}; fn criterion_benchmark(c: &mut Criterion) { let valves = day_16::parser::parse(INPUT).unwrap(); let (processed_valves, initial_distances) = day_16::preprocess(valves.clone()); c.bench_function("day_16::parser::parse", |b| { b.iter(|| day_16::parser::parse(black_box(INPUT))); }); c.bench_function("day_16::preprocess", |b| { b.iter_batched( || valves.clone(), |valves| day_16::preprocess(black_box(valves)), criterion::BatchSize::SmallInput, ); }); c.bench_function("day_16::part_one", |b| { b.iter(|| day_16::part_one(black_box(&processed_valves), black_box(&initial_distances))); }); c.bench_function("day_16::part_two", |b| { b.iter(|| day_16::part_two(black_box(&processed_valves), black_box(&initial_distances))); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
#[doc = "Writer for register IC"] pub type W = crate::W<u32, super::IC>; #[doc = "Register IC `reset()`'s with value 0"] impl crate::ResetValue for super::IC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `FPIDCIC`"] pub struct FPIDCIC_W<'a> { w: &'a mut W, } impl<'a> FPIDCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Write proxy for field `FPDZCIC`"] pub struct FPDZCIC_W<'a> { w: &'a mut W, } impl<'a> FPDZCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `FPIOCIC`"] pub struct FPIOCIC_W<'a> { w: &'a mut W, } impl<'a> FPIOCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `FPUFCIC`"] pub struct FPUFCIC_W<'a> { w: &'a mut W, } impl<'a> FPUFCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `FPOFCIC`"] pub struct FPOFCIC_W<'a> { w: &'a mut W, } impl<'a> FPOFCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `FPIXCIC`"] pub struct FPIXCIC_W<'a> { w: &'a mut W, } impl<'a> FPIXCIC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } impl W { #[doc = "Bit 0 - Floating-Point Input Denormal Exception Interrupt Clear"] #[inline(always)] pub fn fpidcic(&mut self) -> FPIDCIC_W { FPIDCIC_W { w: self } } #[doc = "Bit 1 - Floating-Point Divide By 0 Exception Interrupt Clear"] #[inline(always)] pub fn fpdzcic(&mut self) -> FPDZCIC_W { FPDZCIC_W { w: self } } #[doc = "Bit 2 - Floating-Point Invalid Operation Interrupt Clear"] #[inline(always)] pub fn fpiocic(&mut self) -> FPIOCIC_W { FPIOCIC_W { w: self } } #[doc = "Bit 3 - Floating-Point Underflow Exception Interrupt Clear"] #[inline(always)] pub fn fpufcic(&mut self) -> FPUFCIC_W { FPUFCIC_W { w: self } } #[doc = "Bit 4 - Floating-Point Overflow Exception Interrupt Clear"] #[inline(always)] pub fn fpofcic(&mut self) -> FPOFCIC_W { FPOFCIC_W { w: self } } #[doc = "Bit 5 - Floating-Point Inexact Exception Interrupt Clear"] #[inline(always)] pub fn fpixcic(&mut self) -> FPIXCIC_W { FPIXCIC_W { w: self } } }
#[derive(PartialEq, Debug)] struct Policy { byte: u8, min: u8, max: u8, } type ByteOccurences = [u8; 256]; fn parse_policy(policy: &str) -> Policy { let dash = policy.find('-').unwrap(); let space = policy.find(' ').unwrap(); let min: u8 = policy[..dash].parse().unwrap(); let max: u8 = policy[dash + 1..space].parse().unwrap(); let byte = policy.as_bytes()[space + 1]; Policy { byte, min, max } } fn validate(line: &str, f: impl Fn(Policy, &str) -> bool) -> bool { let mut splits = line.split(':'); let pol = splits.next().unwrap(); let pw = &splits.next().unwrap()[1..]; let pol = parse_policy(pol); f(pol, pw) } fn valid1(policy: Policy, password: &str) -> bool { let ocs = count(password.as_bytes()); let count = ocs[policy.byte as usize]; count >= policy.min && count <= policy.max } fn valid2(policy: Policy, password: &str) -> bool { let bytes = password.as_bytes(); let mut count = 0; if bytes[policy.min as usize - 1] == policy.byte { count += 1; } if bytes[policy.max as usize - 1] == policy.byte { count += 1; } count == 1 } fn count(bytes: &[u8]) -> ByteOccurences { let mut ocs = [0; 256]; for &b in bytes { ocs[b as usize] += 1; } ocs } fn part1(input: &str) -> usize { input.lines().filter(|s| validate(s, valid1)).count() } fn part2(input: &str) -> usize { input.lines().filter(|s| validate(s, valid2)).count() } #[test] fn test_valid2() { assert!(valid2( Policy { min: 1, max: 3, byte: b'a' }, "abcde" )); assert!(!valid2( Policy { min: 1, max: 3, byte: b'b' }, "cdefg" )); assert!(!valid2( Policy { min: 2, max: 9, byte: b'c' }, "ccccccccc" )); } #[test] fn test_parse_policy() { assert_eq!( parse_policy("1-3 a"), Policy { min: 1, max: 3, byte: b'a' } ); } aoc::tests! { fn part1: "1-3 a: abcde\n\ 1-3 b: cdefg\n\ 2-9 c: ccccccccc" => 2; in => 591; fn part2: in => 335; } aoc::main!(part1, part2);
use crate::scene::Scene; use crate::scene::triangle::Triangle; use crate::util::rng::get_rng; use rand::distributions::weighted::alias_method::WeightedIndex; use rand::distributions::WeightedError; use rand::Rng; use serde::export::fmt::Debug; use serde::export::Formatter; use core::fmt; #[derive(Debug)] pub enum LightError { WeightedError(WeightedError), } pub struct LightSourceManager<'l> { lightsources: Vec<&'l Triangle<'l>>, weights: WeightedIndex<f64>, } impl<'l> Debug for LightSourceManager<'l> { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "Lightsource manager") } } impl<'l> LightSourceManager<'l> { pub fn new(scene: &'l Scene) -> Result<Self, LightError> { Self::from_triangle_iter(scene.triangles()) } pub(super) fn from_triangle_iter( iter: impl Iterator<Item = &'l Triangle<'l>>, ) -> Result<Self, LightError> { let lightsources: Vec<&'l Triangle> = iter .filter(|i| !i.mesh.material.emittance.iszero()) .collect(); let weights = WeightedIndex::new( lightsources .iter() .map(|l| { let area = l.area(); let emittance = l.mesh.material.emittance.length(); (area * emittance) as f64 }) .collect(), ) .map_err(LightError::WeightedError)?; Ok(Self { lightsources, weights, }) } pub fn random_source(&self) -> &'l Triangle { let index = get_rng(|mut r| r.sample(&self.weights)); self.lightsources[index] } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use { fuchsia_zircon::{self as zx, DurationNum}, std::ops, zerocopy::{AsBytes, FromBytes}, }; /// Representation of N IEEE 802.11 TimeUnits. /// A TimeUnit is defined as 1024 micro seconds. /// Note: Be careful with arithmetic operations on a TimeUnit. A TimeUnit is limited to 2 octets /// and can easily overflow. However, there is usually no need to ever work with TUs > 0xFFFF. #[repr(C)] #[derive(AsBytes, FromBytes, Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct TimeUnit(u16); impl From<TimeUnit> for zx::Duration { fn from(tu: TimeUnit) -> zx::Duration { (tu.0 as i64 * 1024).micros() } } impl From<TimeUnit> for i64 { fn from(tu: TimeUnit) -> i64 { tu.0 as i64 } } impl From<TimeUnit> for u16 { fn from(tu: TimeUnit) -> u16 { tu.0 } } impl From<u16> for TimeUnit { fn from(tus: u16) -> TimeUnit { TimeUnit(tus) } } impl<T> ops::Add<T> for TimeUnit where T: Into<u16>, { type Output = Self; fn add(self, tus: T) -> Self { Self(self.0 + tus.into()) } } impl<T> ops::Mul<T> for TimeUnit where T: Into<u16>, { type Output = Self; fn mul(self, tus: T) -> Self { Self(self.0 * tus.into()) } } impl TimeUnit { pub const DEFAULT_BEACON_INTERVAL: Self = Self(100); } /// Returns a deadline after N beacons assuming a fix Beacon Period of 100ms. pub fn deadline_after_beacons(bcn_count: u8) -> zx::Time { // TODO: Take variable beacon_period into account rather than a constant. let duration_tus = TimeUnit::DEFAULT_BEACON_INTERVAL * bcn_count; zx::Time::after(duration_tus.into()) } #[cfg(test)] mod tests { use super::*; #[test] fn timeunit() { let mut duration: zx::Duration = TimeUnit(1).into(); assert_eq!(duration, 1024.micros()); duration = TimeUnit(100).into(); assert_eq!(duration, (100 * 1024).micros()); duration = TimeUnit::DEFAULT_BEACON_INTERVAL.into(); assert_eq!(duration, (100 * 1024).micros()); duration = (TimeUnit(100) * 20_u8).into(); assert_eq!(duration, (100 * 20 * 1024).micros()); duration = (TimeUnit(100) * TimeUnit(20)).into(); assert_eq!(duration, (100 * 20 * 1024).micros()); duration = (TimeUnit(100) + 20_u16).into(); assert_eq!(duration, (120 * 1024).micros()); duration = (TimeUnit(100) + TimeUnit(20)).into(); assert_eq!(duration, (120 * 1024).micros()); } }
pub mod closures; pub mod collections; pub mod cow; pub mod cow_ii; pub mod display; pub mod fmt_arguments; pub mod generic_operators; pub mod hashing; pub mod indexes; pub mod io; pub mod iterators; pub mod operators; pub mod ops; pub mod concurrency;
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::MIMR { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct I2C_MIMR_IMR { bits: bool, } impl I2C_MIMR_IMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_IMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_IMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_CLKIMR { bits: bool, } impl I2C_MIMR_CLKIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_CLKIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_CLKIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_DMARXIMR { bits: bool, } impl I2C_MIMR_DMARXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_DMARXIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_DMARXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_DMATXIMR { bits: bool, } impl I2C_MIMR_DMATXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_DMATXIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_DMATXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_NACKIMR { bits: bool, } impl I2C_MIMR_NACKIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_NACKIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_NACKIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_STARTIMR { bits: bool, } impl I2C_MIMR_STARTIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_STARTIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_STARTIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_STOPIMR { bits: bool, } impl I2C_MIMR_STOPIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_STOPIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_STOPIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 6); self.w.bits |= ((value as u32) & 1) << 6; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_ARBLOSTIMR { bits: bool, } impl I2C_MIMR_ARBLOSTIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_ARBLOSTIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_ARBLOSTIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 7); self.w.bits |= ((value as u32) & 1) << 7; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_TXIMR { bits: bool, } impl I2C_MIMR_TXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_TXIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_TXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_RXIMR { bits: bool, } impl I2C_MIMR_RXIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_RXIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_RXIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_TXFEIMR { bits: bool, } impl I2C_MIMR_TXFEIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_TXFEIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_TXFEIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 10); self.w.bits |= ((value as u32) & 1) << 10; self.w } } #[doc = r"Value of the field"] pub struct I2C_MIMR_RXFFIMR { bits: bool, } impl I2C_MIMR_RXFFIMR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _I2C_MIMR_RXFFIMW<'a> { w: &'a mut W, } impl<'a> _I2C_MIMR_RXFFIMW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 11); self.w.bits |= ((value as u32) & 1) << 11; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Master Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_im(&self) -> I2C_MIMR_IMR { let bits = ((self.bits >> 0) & 1) != 0; I2C_MIMR_IMR { bits } } #[doc = "Bit 1 - Clock Timeout Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_clkim(&self) -> I2C_MIMR_CLKIMR { let bits = ((self.bits >> 1) & 1) != 0; I2C_MIMR_CLKIMR { bits } } #[doc = "Bit 2 - Receive DMA Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_dmarxim(&self) -> I2C_MIMR_DMARXIMR { let bits = ((self.bits >> 2) & 1) != 0; I2C_MIMR_DMARXIMR { bits } } #[doc = "Bit 3 - Transmit DMA Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_dmatxim(&self) -> I2C_MIMR_DMATXIMR { let bits = ((self.bits >> 3) & 1) != 0; I2C_MIMR_DMATXIMR { bits } } #[doc = "Bit 4 - Address/Data NACK Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_nackim(&self) -> I2C_MIMR_NACKIMR { let bits = ((self.bits >> 4) & 1) != 0; I2C_MIMR_NACKIMR { bits } } #[doc = "Bit 5 - START Detection Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_startim(&self) -> I2C_MIMR_STARTIMR { let bits = ((self.bits >> 5) & 1) != 0; I2C_MIMR_STARTIMR { bits } } #[doc = "Bit 6 - STOP Detection Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_stopim(&self) -> I2C_MIMR_STOPIMR { let bits = ((self.bits >> 6) & 1) != 0; I2C_MIMR_STOPIMR { bits } } #[doc = "Bit 7 - Arbitration Lost Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_arblostim(&self) -> I2C_MIMR_ARBLOSTIMR { let bits = ((self.bits >> 7) & 1) != 0; I2C_MIMR_ARBLOSTIMR { bits } } #[doc = "Bit 8 - Transmit FIFO Request Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_txim(&self) -> I2C_MIMR_TXIMR { let bits = ((self.bits >> 8) & 1) != 0; I2C_MIMR_TXIMR { bits } } #[doc = "Bit 9 - Receive FIFO Request Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_rxim(&self) -> I2C_MIMR_RXIMR { let bits = ((self.bits >> 9) & 1) != 0; I2C_MIMR_RXIMR { bits } } #[doc = "Bit 10 - Transmit FIFO Empty Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_txfeim(&self) -> I2C_MIMR_TXFEIMR { let bits = ((self.bits >> 10) & 1) != 0; I2C_MIMR_TXFEIMR { bits } } #[doc = "Bit 11 - Receive FIFO Full Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_rxffim(&self) -> I2C_MIMR_RXFFIMR { let bits = ((self.bits >> 11) & 1) != 0; I2C_MIMR_RXFFIMR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Master Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_im(&mut self) -> _I2C_MIMR_IMW { _I2C_MIMR_IMW { w: self } } #[doc = "Bit 1 - Clock Timeout Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_clkim(&mut self) -> _I2C_MIMR_CLKIMW { _I2C_MIMR_CLKIMW { w: self } } #[doc = "Bit 2 - Receive DMA Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_dmarxim(&mut self) -> _I2C_MIMR_DMARXIMW { _I2C_MIMR_DMARXIMW { w: self } } #[doc = "Bit 3 - Transmit DMA Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_dmatxim(&mut self) -> _I2C_MIMR_DMATXIMW { _I2C_MIMR_DMATXIMW { w: self } } #[doc = "Bit 4 - Address/Data NACK Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_nackim(&mut self) -> _I2C_MIMR_NACKIMW { _I2C_MIMR_NACKIMW { w: self } } #[doc = "Bit 5 - START Detection Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_startim(&mut self) -> _I2C_MIMR_STARTIMW { _I2C_MIMR_STARTIMW { w: self } } #[doc = "Bit 6 - STOP Detection Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_stopim(&mut self) -> _I2C_MIMR_STOPIMW { _I2C_MIMR_STOPIMW { w: self } } #[doc = "Bit 7 - Arbitration Lost Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_arblostim(&mut self) -> _I2C_MIMR_ARBLOSTIMW { _I2C_MIMR_ARBLOSTIMW { w: self } } #[doc = "Bit 8 - Transmit FIFO Request Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_txim(&mut self) -> _I2C_MIMR_TXIMW { _I2C_MIMR_TXIMW { w: self } } #[doc = "Bit 9 - Receive FIFO Request Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_rxim(&mut self) -> _I2C_MIMR_RXIMW { _I2C_MIMR_RXIMW { w: self } } #[doc = "Bit 10 - Transmit FIFO Empty Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_txfeim(&mut self) -> _I2C_MIMR_TXFEIMW { _I2C_MIMR_TXFEIMW { w: self } } #[doc = "Bit 11 - Receive FIFO Full Interrupt Mask"] #[inline(always)] pub fn i2c_mimr_rxffim(&mut self) -> _I2C_MIMR_RXFFIMW { _I2C_MIMR_RXFFIMW { w: self } } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. #[allow(unused_mut)] pub fn serialize_structure_tag( mut writer: smithy_query::QueryValueWriter, input: &crate::model::Tag, ) { #[allow(unused_mut)] let mut scope_1 = writer.prefix("Key"); if let Some(var_2) = &input.key { scope_1.string(var_2); } #[allow(unused_mut)] let mut scope_3 = writer.prefix("Value"); if let Some(var_4) = &input.value { scope_3.string(var_4); } } #[allow(unused_mut)] pub fn serialize_structure_scaling_configuration( mut writer: smithy_query::QueryValueWriter, input: &crate::model::ScalingConfiguration, ) { #[allow(unused_mut)] let mut scope_5 = writer.prefix("MinCapacity"); if let Some(var_6) = &input.min_capacity { scope_5.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_6).into()), ); } #[allow(unused_mut)] let mut scope_7 = writer.prefix("MaxCapacity"); if let Some(var_8) = &input.max_capacity { scope_7.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_8).into()), ); } #[allow(unused_mut)] let mut scope_9 = writer.prefix("AutoPause"); if let Some(var_10) = &input.auto_pause { scope_9.boolean(*var_10); } #[allow(unused_mut)] let mut scope_11 = writer.prefix("SecondsUntilAutoPause"); if let Some(var_12) = &input.seconds_until_auto_pause { scope_11.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_12).into()), ); } #[allow(unused_mut)] let mut scope_13 = writer.prefix("TimeoutAction"); if let Some(var_14) = &input.timeout_action { scope_13.string(var_14); } } #[allow(unused_mut)] pub fn serialize_structure_processor_feature( mut writer: smithy_query::QueryValueWriter, input: &crate::model::ProcessorFeature, ) { #[allow(unused_mut)] let mut scope_15 = writer.prefix("Name"); if let Some(var_16) = &input.name { scope_15.string(var_16); } #[allow(unused_mut)] let mut scope_17 = writer.prefix("Value"); if let Some(var_18) = &input.value { scope_17.string(var_18); } } #[allow(unused_mut)] pub fn serialize_structure_user_auth_config( mut writer: smithy_query::QueryValueWriter, input: &crate::model::UserAuthConfig, ) { #[allow(unused_mut)] let mut scope_19 = writer.prefix("Description"); if let Some(var_20) = &input.description { scope_19.string(var_20); } #[allow(unused_mut)] let mut scope_21 = writer.prefix("UserName"); if let Some(var_22) = &input.user_name { scope_21.string(var_22); } #[allow(unused_mut)] let mut scope_23 = writer.prefix("AuthScheme"); if let Some(var_24) = &input.auth_scheme { scope_23.string(var_24.as_str()); } #[allow(unused_mut)] let mut scope_25 = writer.prefix("SecretArn"); if let Some(var_26) = &input.secret_arn { scope_25.string(var_26); } #[allow(unused_mut)] let mut scope_27 = writer.prefix("IAMAuth"); if let Some(var_28) = &input.iam_auth { scope_27.string(var_28.as_str()); } } #[allow(unused_mut)] pub fn serialize_structure_filter( mut writer: smithy_query::QueryValueWriter, input: &crate::model::Filter, ) { #[allow(unused_mut)] let mut scope_29 = writer.prefix("Name"); if let Some(var_30) = &input.name { scope_29.string(var_30); } #[allow(unused_mut)] let mut scope_31 = writer.prefix("Values"); if let Some(var_32) = &input.values { let mut list_34 = scope_31.start_list(false, Some("Value")); for item_33 in var_32 { #[allow(unused_mut)] let mut entry_35 = list_34.entry(); entry_35.string(item_33); } list_34.finish(); } } #[allow(unused_mut)] pub fn serialize_structure_cloudwatch_logs_export_configuration( mut writer: smithy_query::QueryValueWriter, input: &crate::model::CloudwatchLogsExportConfiguration, ) { #[allow(unused_mut)] let mut scope_36 = writer.prefix("EnableLogTypes"); if let Some(var_37) = &input.enable_log_types { let mut list_39 = scope_36.start_list(false, None); for item_38 in var_37 { #[allow(unused_mut)] let mut entry_40 = list_39.entry(); entry_40.string(item_38); } list_39.finish(); } #[allow(unused_mut)] let mut scope_41 = writer.prefix("DisableLogTypes"); if let Some(var_42) = &input.disable_log_types { let mut list_44 = scope_41.start_list(false, None); for item_43 in var_42 { #[allow(unused_mut)] let mut entry_45 = list_44.entry(); entry_45.string(item_43); } list_44.finish(); } } #[allow(unused_mut)] pub fn serialize_structure_parameter( mut writer: smithy_query::QueryValueWriter, input: &crate::model::Parameter, ) { #[allow(unused_mut)] let mut scope_46 = writer.prefix("ParameterName"); if let Some(var_47) = &input.parameter_name { scope_46.string(var_47); } #[allow(unused_mut)] let mut scope_48 = writer.prefix("ParameterValue"); if let Some(var_49) = &input.parameter_value { scope_48.string(var_49); } #[allow(unused_mut)] let mut scope_50 = writer.prefix("Description"); if let Some(var_51) = &input.description { scope_50.string(var_51); } #[allow(unused_mut)] let mut scope_52 = writer.prefix("Source"); if let Some(var_53) = &input.source { scope_52.string(var_53); } #[allow(unused_mut)] let mut scope_54 = writer.prefix("ApplyType"); if let Some(var_55) = &input.apply_type { scope_54.string(var_55); } #[allow(unused_mut)] let mut scope_56 = writer.prefix("DataType"); if let Some(var_57) = &input.data_type { scope_56.string(var_57); } #[allow(unused_mut)] let mut scope_58 = writer.prefix("AllowedValues"); if let Some(var_59) = &input.allowed_values { scope_58.string(var_59); } #[allow(unused_mut)] let mut scope_60 = writer.prefix("IsModifiable"); if input.is_modifiable { scope_60.boolean(input.is_modifiable); } #[allow(unused_mut)] let mut scope_61 = writer.prefix("MinimumEngineVersion"); if let Some(var_62) = &input.minimum_engine_version { scope_61.string(var_62); } #[allow(unused_mut)] let mut scope_63 = writer.prefix("ApplyMethod"); if let Some(var_64) = &input.apply_method { scope_63.string(var_64.as_str()); } #[allow(unused_mut)] let mut scope_65 = writer.prefix("SupportedEngineModes"); if let Some(var_66) = &input.supported_engine_modes { let mut list_68 = scope_65.start_list(false, None); for item_67 in var_66 { #[allow(unused_mut)] let mut entry_69 = list_68.entry(); entry_69.string(item_67); } list_68.finish(); } } #[allow(unused_mut)] pub fn serialize_structure_connection_pool_configuration( mut writer: smithy_query::QueryValueWriter, input: &crate::model::ConnectionPoolConfiguration, ) { #[allow(unused_mut)] let mut scope_70 = writer.prefix("MaxConnectionsPercent"); if let Some(var_71) = &input.max_connections_percent { scope_70.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_71).into()), ); } #[allow(unused_mut)] let mut scope_72 = writer.prefix("MaxIdleConnectionsPercent"); if let Some(var_73) = &input.max_idle_connections_percent { scope_72.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_73).into()), ); } #[allow(unused_mut)] let mut scope_74 = writer.prefix("ConnectionBorrowTimeout"); if let Some(var_75) = &input.connection_borrow_timeout { scope_74.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_75).into()), ); } #[allow(unused_mut)] let mut scope_76 = writer.prefix("SessionPinningFilters"); if let Some(var_77) = &input.session_pinning_filters { let mut list_79 = scope_76.start_list(false, None); for item_78 in var_77 { #[allow(unused_mut)] let mut entry_80 = list_79.entry(); entry_80.string(item_78); } list_79.finish(); } #[allow(unused_mut)] let mut scope_81 = writer.prefix("InitQuery"); if let Some(var_82) = &input.init_query { scope_81.string(var_82); } } #[allow(unused_mut)] pub fn serialize_structure_option_configuration( mut writer: smithy_query::QueryValueWriter, input: &crate::model::OptionConfiguration, ) { #[allow(unused_mut)] let mut scope_83 = writer.prefix("OptionName"); if let Some(var_84) = &input.option_name { scope_83.string(var_84); } #[allow(unused_mut)] let mut scope_85 = writer.prefix("Port"); if let Some(var_86) = &input.port { scope_85.number( #[allow(clippy::useless_conversion)] smithy_types::Number::NegInt((*var_86).into()), ); } #[allow(unused_mut)] let mut scope_87 = writer.prefix("OptionVersion"); if let Some(var_88) = &input.option_version { scope_87.string(var_88); } #[allow(unused_mut)] let mut scope_89 = writer.prefix("DBSecurityGroupMemberships"); if let Some(var_90) = &input.db_security_group_memberships { let mut list_92 = scope_89.start_list(false, Some("DBSecurityGroupName")); for item_91 in var_90 { #[allow(unused_mut)] let mut entry_93 = list_92.entry(); entry_93.string(item_91); } list_92.finish(); } #[allow(unused_mut)] let mut scope_94 = writer.prefix("VpcSecurityGroupMemberships"); if let Some(var_95) = &input.vpc_security_group_memberships { let mut list_97 = scope_94.start_list(false, Some("VpcSecurityGroupId")); for item_96 in var_95 { #[allow(unused_mut)] let mut entry_98 = list_97.entry(); entry_98.string(item_96); } list_97.finish(); } #[allow(unused_mut)] let mut scope_99 = writer.prefix("OptionSettings"); if let Some(var_100) = &input.option_settings { let mut list_102 = scope_99.start_list(false, Some("OptionSetting")); for item_101 in var_100 { #[allow(unused_mut)] let mut entry_103 = list_102.entry(); crate::query_ser::serialize_structure_option_setting(entry_103, item_101); } list_102.finish(); } } #[allow(unused_mut)] pub fn serialize_structure_option_setting( mut writer: smithy_query::QueryValueWriter, input: &crate::model::OptionSetting, ) { #[allow(unused_mut)] let mut scope_104 = writer.prefix("Name"); if let Some(var_105) = &input.name { scope_104.string(var_105); } #[allow(unused_mut)] let mut scope_106 = writer.prefix("Value"); if let Some(var_107) = &input.value { scope_106.string(var_107); } #[allow(unused_mut)] let mut scope_108 = writer.prefix("DefaultValue"); if let Some(var_109) = &input.default_value { scope_108.string(var_109); } #[allow(unused_mut)] let mut scope_110 = writer.prefix("Description"); if let Some(var_111) = &input.description { scope_110.string(var_111); } #[allow(unused_mut)] let mut scope_112 = writer.prefix("ApplyType"); if let Some(var_113) = &input.apply_type { scope_112.string(var_113); } #[allow(unused_mut)] let mut scope_114 = writer.prefix("DataType"); if let Some(var_115) = &input.data_type { scope_114.string(var_115); } #[allow(unused_mut)] let mut scope_116 = writer.prefix("AllowedValues"); if let Some(var_117) = &input.allowed_values { scope_116.string(var_117); } #[allow(unused_mut)] let mut scope_118 = writer.prefix("IsModifiable"); if input.is_modifiable { scope_118.boolean(input.is_modifiable); } #[allow(unused_mut)] let mut scope_119 = writer.prefix("IsCollection"); if input.is_collection { scope_119.boolean(input.is_collection); } }
//! The **official asciii Handbook**. //! //! This user documentation has been ripped off straight from the [original //! README](https://github.com/ascii-dresden/ascii-invoicer/), so please forgive if you find any //! mistakes or unimplemented material, //! please **[file an issue immediately](https://github.com/ascii-dresden/asciii/issues/new)**. //! //! 1. [Introduction](#introduction) //! 1. [Installation](#installation) //! 1. [Usage](#usage) //! 1. [File Format](#file-format) //! 1. [File Structure](#file-structure) //! //! # ascii invoicer //! //! ## Introduction //! //! The ascii-invoicer is a command-line tool that manages projects and stores them not in a database but in folders. //! New projects can be created from templates and are stored in the working directory. //! Projects can be archived, each year will have its own archive. //! A project consists of a folder containing a yaml file describing it and a number of attached files, //! such tex files. //! Projects can contain products and personal. //! You can create preliminary offers and invoices from your projects. //! //! ## Installation //! //! ### Archlinux User Repository //! //! You find the AUR package [asciii-git](https://aur.archlinux.org/packages/asciii-git), or contact me personally about the inofficial repo with the binary packages. //! Debian and Windows packages are on the way. //! //! ### Build Requirements //! //! * rustc ≥ 1.11.0 //! * cargo //! * optionally: for full feature completeness you also need cmake to build libgit2 //! //! Just run `cargo build --release` or `cargo install --path .` //! //! ### Requirements //! //! * linux, mac osx, windows7+ //! * git for sync //! * pdflatex/xelatex to produce documents //! * an editor that can highlight yaml //! //! //! ## Usage //! //! You should be able to learn everything there is to know about the command line interface by just typing in `asciii help` //! Each of these sections starts with a list of commands. //! Read the help to each command with `asciii help [COMMAND]` to find out about all parameters, especially *list* has quite a few of them. //! //! ### Get started with //! //! ```bash //! asciii help [COMMAND] # Describe available commands or one specific command //! asciii list # List current Projects //! asciii show NAMES # Shows information about a project in different ways //! ``` //! //! ### Project Life-Cycle //! //! //! ```bash //! asciii new NAME # Creating a new project //! asciii edit NAMES # Edit project //! asciii make NAME # Creates an Offer //! //! asciii edit NAMES # Edit project //! asciii make NAME # Creates an Invoice //! //! asciii archive NAME # Move project to archive //! asciii unarchive YEAR NAME # reopen an archived project //! asciii delete NAME # If you really have to //! ``` //! //! ### GIT Features //! //! ```bash //! asciii add NAMES //! asciii commit //! asciii pull / push //! asciii cleanup //! asciii status, log, diff, stash, pop //! ``` //! //! These commands behave similar to the original git commands. //! The only difference is that you select projects just like you do with other ascii commands (see edit, display, offer, invoice). //! Commit uses -m (like in git) but unlike git does not (yet) open an editor if you leave out the message. //! //! #### CAREFUL: //! These commands are meant as a convenience, they ARE NOT however a *complete* replacement for git! //! You should always pull before you start working and push right after you are done in order to avoid merge conflicts. //! If you do run into such problems go to storage directory `cd $(ascii path)` and resolve them using git. //! //! Personal advice N°1: use `git pull --rebase` //! //! Personal advice N°2: add this to your `.bash_aliases`: //! `alias agit="git --git-dir=$(ascii path)/.git --work-tree=$(ascii path)"` //! //! ### More Details //! //! The commands `asciii list` and `asciii display` (equals `ascii show`) allow to display all sorts of details from a project. //! You can describe the exact field you wish to view via path like string. //! To display the clients email for instance //! //! ```yaml //! client: //! email: jon.doe@example.com //! ``` //! //! you pass in: //! //! ` //! asciii show -d client/email` will display the clients email. //! `asciii show -d invoice/date` will display the date of the invoice. //! //! `asciii list --details` will add columns to the table. //! For example try `asciii list --details client/email`. //! As some fields are computed you have to use a different syntax to access them, //! try for instance `asciii list -d ClientFullName`. //! For a full list run `asciii list --computed`. //! //! //! ### Exporting //! Currently `asciii` only supports csv export. //! You can export the entire list of projects in a year with //! //! ```bash //! asciii csv [year] # Prints a CSV list of current year into CSV //! asciii list --csv # prints the same configuration (sorted, filtered) as `list` would. //! ``` //! //! You can pipe the csv into column (`asciii csv | column -ts\;`) to display the table in you terminal. //! //! ### Miscellaneous //! //! ```bash //! asciii path # Return projects storage path //! asciii config -e # Edit configuration //! asciii templates # List or add templates //! asciii whoami # Invoke settings --show user/name //! asciii version # Display version //! ``` //! //! ## File Format //! //! Every project consists of a project folder containig at least a `.yml` file. //! [yaml](https://en.wikipedia.org/w/YAML)] is a structured file format, similar to json. //! Infact: it is a superset of json. //! //! ### Document structure //! //! A project file contains several sections, most of which you neither have to fill out manually nor right away be a valid project. The //! //! #### Client //! //! This describes the clients name and address. Please note that the field `client/address` mentions the clients name too. //! The field `client/title` is used to determine the clients gender, so the first word must be one of the listed options. //! `client/email` is not required though highly recommended. //! //! ```yaml //! client: //! title: Mr # or: "Mrs", "Ms", "Herr", "Frau" - after which anything can follow //! first_name: John //! last_name: Doe //! //! email: //! address: | //! John Doe //! Nöthnitzerstraße 46 //! 01187 Dresden //! ``` //! //! The event files can be filled //! //! * `event:` //! * `offer:` //! * `invoice:` //! * `products:` //! * `hours:` //! //! ### Products //! //! There are two alternative formats for describing separate products. //! The first ist the direct version, describing each product in situ. //! The second one makes use of the `cataloge` and only references entries. //! If you need to add a product for a separate occation, //! just use the direct format. //! If you want to make changes to the cataloge, please consider changing the [template](#templates). //! //! ```yaml //! "Sekt (0,75l)": //! amount: 4 //! price: 6.0 //! sold: 2 //! "Belegte Brötchen": //! amount: 90 //! price: 1.16 //! ``` //! //! ```yaml //! cataloge: //! product: &kaffee { name: Kaffee, price: 2.5, unit: 1l } //! //! products: //! *kaffee: //! amount: 60 //! ``` //! //! ## File Structure //! //! Your config-file is located in ~/.asciii.yml but you can also access it using `asciii config --edit`. //! The projects directory contains working, archive and templates. If you start with a blank slate you might want to put the templates folder into the storage folder (not well tested yet). //! //! By default in your `path` folder you fill find: //! //! ```bash //! caterings //! ├── archive //! │   ├── 2013 //! │   │   ├── Foobar1 //! │   │   │   └── Foobar1.yml //! │   │   └── Foobar2 //! │   │      ├── Foobar2.yml //! │   │      └── R007 Foobar2 2013-02-11.tex //! │   └── 2014 //! │   ├── canceled_foobar1 //! │   │   ├── A20141009-1 foobar.tex //! │   │   └── foobar1.yml //! │   ├── R029_foobar2 //! │   │   └── R029 foobar2 2014-09-10.tex //! │   └── R036_foobar3 //! │   ├── foobar3.yml //! │   └── R036 foobar3 2014-10-08.tex //! ├── templates //! │   ├── default.yml.erb //! │   └── document.tex.erb //! └── working //! ├── Foobar1 //! │   ├── A20141127-1 Foobar1.tex //! │   └── Foobar1.yml //! ├── Foobar2 //! │   ├── A20141124-1 Foobar2.tex //! │   └── Foobar2.yml //! └── Foobar3 //! ├── A20140325-1 Foobar3.tex //! ├── A20140327-1 Foobar3.tex //! ├── R008 Foobar3 2014-03-31.tex //! └── Foobar3.yml //! ``` //! //! ## Aliases //! //! // * `list`: `-l`, `l`, `ls`, `dir` //! // * `display`: `-d`, `show` //! // * `archive`: `close` //! // * `invoice`: `-l` //! // * `offer`: `-o` //! // * `settings`: `config` //! // * `log`: `history` //! //! ## Pro tips //! //! 1. Check out `repl asciii`! //! You should copy [repl-file](src/repl/ascii) into ~/.repl/ascii and install rlwrap to take advantage of all the repl goodness such as autocompletion and history. //! //! 2. Check out `xclip`! //! You can pipe the output of `ascii show` or `ascii show --csv` to xclip and paste to your email program or into a spreadsheet tool like libreoffice calc. //! //! //! ## Known Issues //! //! Some strings may cause problems when rendering latex, e.g. //! a client called `"ABC GmbH & Co. KG"`. //! The `"&"` causes latex to fail, `\&"` bugs the yaml parser but `"\\&"` will do the trick. //! asciii list -dCaterers -fCaterers:hendrik
use std::net::SocketAddr; use crate::pipe::{pipes, Pipes}; use crate::traits::{Readable, Writable}; pub struct SessionMeta { peer_addr: SocketAddr, } impl SessionMeta { pub fn get_peer_addr(&self) -> &SocketAddr { &self.peer_addr } } pub(crate) type Session<U, D> = (SessionMeta, Pipes<U, D>); pub(crate) fn create_session<U, D>( peer_addr: SocketAddr, upstream: U, downstream: D, ) -> Session<U, D> where U: Readable + Writable, D: Readable + Writable, { (SessionMeta { peer_addr }, pipes(upstream, downstream)) }
#![allow(unused_unsafe)] /* origin: FreeBSD /usr/src/lib/msun/src/k_rem_pio2.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ use super::floor; use super::scalbn; // initial value for jk const INIT_JK: [usize; 4] = [3, 4, 4, 6]; // Table of constants for 2/pi, 396 Hex digits (476 decimal) of 2/pi // // integer array, contains the (24*i)-th to (24*i+23)-th // bit of 2/pi after binary point. The corresponding // floating value is // // ipio2[i] * 2^(-24(i+1)). // // NB: This table must have at least (e0-3)/24 + jk terms. // For quad precision (e0 <= 16360, jk = 6), this is 686. #[cfg(any(target_pointer_width = "32", target_pointer_width = "16"))] const IPIO2: [i32; 66] = [ 0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, 0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, 0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, 0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41, 0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8, 0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF, 0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, 0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, 0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, 0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, 0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B, ]; #[cfg(target_pointer_width = "64")] const IPIO2: [i32; 690] = [ 0xA2F983, 0x6E4E44, 0x1529FC, 0x2757D1, 0xF534DD, 0xC0DB62, 0x95993C, 0x439041, 0xFE5163, 0xABDEBB, 0xC561B7, 0x246E3A, 0x424DD2, 0xE00649, 0x2EEA09, 0xD1921C, 0xFE1DEB, 0x1CB129, 0xA73EE8, 0x8235F5, 0x2EBB44, 0x84E99C, 0x7026B4, 0x5F7E41, 0x3991D6, 0x398353, 0x39F49C, 0x845F8B, 0xBDF928, 0x3B1FF8, 0x97FFDE, 0x05980F, 0xEF2F11, 0x8B5A0A, 0x6D1F6D, 0x367ECF, 0x27CB09, 0xB74F46, 0x3F669E, 0x5FEA2D, 0x7527BA, 0xC7EBE5, 0xF17B3D, 0x0739F7, 0x8A5292, 0xEA6BFB, 0x5FB11F, 0x8D5D08, 0x560330, 0x46FC7B, 0x6BABF0, 0xCFBC20, 0x9AF436, 0x1DA9E3, 0x91615E, 0xE61B08, 0x659985, 0x5F14A0, 0x68408D, 0xFFD880, 0x4D7327, 0x310606, 0x1556CA, 0x73A8C9, 0x60E27B, 0xC08C6B, 0x47C419, 0xC367CD, 0xDCE809, 0x2A8359, 0xC4768B, 0x961CA6, 0xDDAF44, 0xD15719, 0x053EA5, 0xFF0705, 0x3F7E33, 0xE832C2, 0xDE4F98, 0x327DBB, 0xC33D26, 0xEF6B1E, 0x5EF89F, 0x3A1F35, 0xCAF27F, 0x1D87F1, 0x21907C, 0x7C246A, 0xFA6ED5, 0x772D30, 0x433B15, 0xC614B5, 0x9D19C3, 0xC2C4AD, 0x414D2C, 0x5D000C, 0x467D86, 0x2D71E3, 0x9AC69B, 0x006233, 0x7CD2B4, 0x97A7B4, 0xD55537, 0xF63ED7, 0x1810A3, 0xFC764D, 0x2A9D64, 0xABD770, 0xF87C63, 0x57B07A, 0xE71517, 0x5649C0, 0xD9D63B, 0x3884A7, 0xCB2324, 0x778AD6, 0x23545A, 0xB91F00, 0x1B0AF1, 0xDFCE19, 0xFF319F, 0x6A1E66, 0x615799, 0x47FBAC, 0xD87F7E, 0xB76522, 0x89E832, 0x60BFE6, 0xCDC4EF, 0x09366C, 0xD43F5D, 0xD7DE16, 0xDE3B58, 0x929BDE, 0x2822D2, 0xE88628, 0x4D58E2, 0x32CAC6, 0x16E308, 0xCB7DE0, 0x50C017, 0xA71DF3, 0x5BE018, 0x34132E, 0x621283, 0x014883, 0x5B8EF5, 0x7FB0AD, 0xF2E91E, 0x434A48, 0xD36710, 0xD8DDAA, 0x425FAE, 0xCE616A, 0xA4280A, 0xB499D3, 0xF2A606, 0x7F775C, 0x83C2A3, 0x883C61, 0x78738A, 0x5A8CAF, 0xBDD76F, 0x63A62D, 0xCBBFF4, 0xEF818D, 0x67C126, 0x45CA55, 0x36D9CA, 0xD2A828, 0x8D61C2, 0x77C912, 0x142604, 0x9B4612, 0xC459C4, 0x44C5C8, 0x91B24D, 0xF31700, 0xAD43D4, 0xE54929, 0x10D5FD, 0xFCBE00, 0xCC941E, 0xEECE70, 0xF53E13, 0x80F1EC, 0xC3E7B3, 0x28F8C7, 0x940593, 0x3E71C1, 0xB3092E, 0xF3450B, 0x9C1288, 0x7B20AB, 0x9FB52E, 0xC29247, 0x2F327B, 0x6D550C, 0x90A772, 0x1FE76B, 0x96CB31, 0x4A1679, 0xE27941, 0x89DFF4, 0x9794E8, 0x84E6E2, 0x973199, 0x6BED88, 0x365F5F, 0x0EFDBB, 0xB49A48, 0x6CA467, 0x427271, 0x325D8D, 0xB8159F, 0x09E5BC, 0x25318D, 0x3974F7, 0x1C0530, 0x010C0D, 0x68084B, 0x58EE2C, 0x90AA47, 0x02E774, 0x24D6BD, 0xA67DF7, 0x72486E, 0xEF169F, 0xA6948E, 0xF691B4, 0x5153D1, 0xF20ACF, 0x339820, 0x7E4BF5, 0x6863B2, 0x5F3EDD, 0x035D40, 0x7F8985, 0x295255, 0xC06437, 0x10D86D, 0x324832, 0x754C5B, 0xD4714E, 0x6E5445, 0xC1090B, 0x69F52A, 0xD56614, 0x9D0727, 0x50045D, 0xDB3BB4, 0xC576EA, 0x17F987, 0x7D6B49, 0xBA271D, 0x296996, 0xACCCC6, 0x5414AD, 0x6AE290, 0x89D988, 0x50722C, 0xBEA404, 0x940777, 0x7030F3, 0x27FC00, 0xA871EA, 0x49C266, 0x3DE064, 0x83DD97, 0x973FA3, 0xFD9443, 0x8C860D, 0xDE4131, 0x9D3992, 0x8C70DD, 0xE7B717, 0x3BDF08, 0x2B3715, 0xA0805C, 0x93805A, 0x921110, 0xD8E80F, 0xAF806C, 0x4BFFDB, 0x0F9038, 0x761859, 0x15A562, 0xBBCB61, 0xB989C7, 0xBD4010, 0x04F2D2, 0x277549, 0xF6B6EB, 0xBB22DB, 0xAA140A, 0x2F2689, 0x768364, 0x333B09, 0x1A940E, 0xAA3A51, 0xC2A31D, 0xAEEDAF, 0x12265C, 0x4DC26D, 0x9C7A2D, 0x9756C0, 0x833F03, 0xF6F009, 0x8C402B, 0x99316D, 0x07B439, 0x15200C, 0x5BC3D8, 0xC492F5, 0x4BADC6, 0xA5CA4E, 0xCD37A7, 0x36A9E6, 0x9492AB, 0x6842DD, 0xDE6319, 0xEF8C76, 0x528B68, 0x37DBFC, 0xABA1AE, 0x3115DF, 0xA1AE00, 0xDAFB0C, 0x664D64, 0xB705ED, 0x306529, 0xBF5657, 0x3AFF47, 0xB9F96A, 0xF3BE75, 0xDF9328, 0x3080AB, 0xF68C66, 0x15CB04, 0x0622FA, 0x1DE4D9, 0xA4B33D, 0x8F1B57, 0x09CD36, 0xE9424E, 0xA4BE13, 0xB52333, 0x1AAAF0, 0xA8654F, 0xA5C1D2, 0x0F3F0B, 0xCD785B, 0x76F923, 0x048B7B, 0x721789, 0x53A6C6, 0xE26E6F, 0x00EBEF, 0x584A9B, 0xB7DAC4, 0xBA66AA, 0xCFCF76, 0x1D02D1, 0x2DF1B1, 0xC1998C, 0x77ADC3, 0xDA4886, 0xA05DF7, 0xF480C6, 0x2FF0AC, 0x9AECDD, 0xBC5C3F, 0x6DDED0, 0x1FC790, 0xB6DB2A, 0x3A25A3, 0x9AAF00, 0x9353AD, 0x0457B6, 0xB42D29, 0x7E804B, 0xA707DA, 0x0EAA76, 0xA1597B, 0x2A1216, 0x2DB7DC, 0xFDE5FA, 0xFEDB89, 0xFDBE89, 0x6C76E4, 0xFCA906, 0x70803E, 0x156E85, 0xFF87FD, 0x073E28, 0x336761, 0x86182A, 0xEABD4D, 0xAFE7B3, 0x6E6D8F, 0x396795, 0x5BBF31, 0x48D784, 0x16DF30, 0x432DC7, 0x356125, 0xCE70C9, 0xB8CB30, 0xFD6CBF, 0xA200A4, 0xE46C05, 0xA0DD5A, 0x476F21, 0xD21262, 0x845CB9, 0x496170, 0xE0566B, 0x015299, 0x375550, 0xB7D51E, 0xC4F133, 0x5F6E13, 0xE4305D, 0xA92E85, 0xC3B21D, 0x3632A1, 0xA4B708, 0xD4B1EA, 0x21F716, 0xE4698F, 0x77FF27, 0x80030C, 0x2D408D, 0xA0CD4F, 0x99A520, 0xD3A2B3, 0x0A5D2F, 0x42F9B4, 0xCBDA11, 0xD0BE7D, 0xC1DB9B, 0xBD17AB, 0x81A2CA, 0x5C6A08, 0x17552E, 0x550027, 0xF0147F, 0x8607E1, 0x640B14, 0x8D4196, 0xDEBE87, 0x2AFDDA, 0xB6256B, 0x34897B, 0xFEF305, 0x9EBFB9, 0x4F6A68, 0xA82A4A, 0x5AC44F, 0xBCF82D, 0x985AD7, 0x95C7F4, 0x8D4D0D, 0xA63A20, 0x5F57A4, 0xB13F14, 0x953880, 0x0120CC, 0x86DD71, 0xB6DEC9, 0xF560BF, 0x11654D, 0x6B0701, 0xACB08C, 0xD0C0B2, 0x485551, 0x0EFB1E, 0xC37295, 0x3B06A3, 0x3540C0, 0x7BDC06, 0xCC45E0, 0xFA294E, 0xC8CAD6, 0x41F3E8, 0xDE647C, 0xD8649B, 0x31BED9, 0xC397A4, 0xD45877, 0xC5E369, 0x13DAF0, 0x3C3ABA, 0x461846, 0x5F7555, 0xF5BDD2, 0xC6926E, 0x5D2EAC, 0xED440E, 0x423E1C, 0x87C461, 0xE9FD29, 0xF3D6E7, 0xCA7C22, 0x35916F, 0xC5E008, 0x8DD7FF, 0xE26A6E, 0xC6FDB0, 0xC10893, 0x745D7C, 0xB2AD6B, 0x9D6ECD, 0x7B723E, 0x6A11C6, 0xA9CFF7, 0xDF7329, 0xBAC9B5, 0x5100B7, 0x0DB2E2, 0x24BA74, 0x607DE5, 0x8AD874, 0x2C150D, 0x0C1881, 0x94667E, 0x162901, 0x767A9F, 0xBEFDFD, 0xEF4556, 0x367ED9, 0x13D9EC, 0xB9BA8B, 0xFC97C4, 0x27A831, 0xC36EF1, 0x36C594, 0x56A8D8, 0xB5A8B4, 0x0ECCCF, 0x2D8912, 0x34576F, 0x89562C, 0xE3CE99, 0xB920D6, 0xAA5E6B, 0x9C2A3E, 0xCC5F11, 0x4A0BFD, 0xFBF4E1, 0x6D3B8E, 0x2C86E2, 0x84D4E9, 0xA9B4FC, 0xD1EEEF, 0xC9352E, 0x61392F, 0x442138, 0xC8D91B, 0x0AFC81, 0x6A4AFB, 0xD81C2F, 0x84B453, 0x8C994E, 0xCC2254, 0xDC552A, 0xD6C6C0, 0x96190B, 0xB8701A, 0x649569, 0x605A26, 0xEE523F, 0x0F117F, 0x11B5F4, 0xF5CBFC, 0x2DBC34, 0xEEBC34, 0xCC5DE8, 0x605EDD, 0x9B8E67, 0xEF3392, 0xB817C9, 0x9B5861, 0xBC57E1, 0xC68351, 0x103ED8, 0x4871DD, 0xDD1C2D, 0xA118AF, 0x462C21, 0xD7F359, 0x987AD9, 0xC0549E, 0xFA864F, 0xFC0656, 0xAE79E5, 0x362289, 0x22AD38, 0xDC9367, 0xAAE855, 0x382682, 0x9BE7CA, 0xA40D51, 0xB13399, 0x0ED7A9, 0x480569, 0xF0B265, 0xA7887F, 0x974C88, 0x36D1F9, 0xB39221, 0x4A827B, 0x21CF98, 0xDC9F40, 0x5547DC, 0x3A74E1, 0x42EB67, 0xDF9DFE, 0x5FD45E, 0xA4677B, 0x7AACBA, 0xA2F655, 0x23882B, 0x55BA41, 0x086E59, 0x862A21, 0x834739, 0xE6E389, 0xD49EE5, 0x40FB49, 0xE956FF, 0xCA0F1C, 0x8A59C5, 0x2BFA94, 0xC5C1D3, 0xCFC50F, 0xAE5ADB, 0x86C547, 0x624385, 0x3B8621, 0x94792C, 0x876110, 0x7B4C2A, 0x1A2C80, 0x12BF43, 0x902688, 0x893C78, 0xE4C4A8, 0x7BDBE5, 0xC23AC4, 0xEAF426, 0x8A67F7, 0xBF920D, 0x2BA365, 0xB1933D, 0x0B7CBD, 0xDC51A4, 0x63DD27, 0xDDE169, 0x19949A, 0x9529A8, 0x28CE68, 0xB4ED09, 0x209F44, 0xCA984E, 0x638270, 0x237C7E, 0x32B90F, 0x8EF5A7, 0xE75614, 0x08F121, 0x2A9DB5, 0x4D7E6F, 0x5119A5, 0xABF9B5, 0xD6DF82, 0x61DD96, 0x023616, 0x9F3AC4, 0xA1A283, 0x6DED72, 0x7A8D39, 0xA9B882, 0x5C326B, 0x5B2746, 0xED3400, 0x7700D2, 0x55F4FC, 0x4D5901, 0x8071E0, ]; const PIO2: [f64; 8] = [ 1.57079625129699707031e+00, /* 0x3FF921FB, 0x40000000 */ 7.54978941586159635335e-08, /* 0x3E74442D, 0x00000000 */ 5.39030252995776476554e-15, /* 0x3CF84698, 0x80000000 */ 3.28200341580791294123e-22, /* 0x3B78CC51, 0x60000000 */ 1.27065575308067607349e-29, /* 0x39F01B83, 0x80000000 */ 1.22933308981111328932e-36, /* 0x387A2520, 0x40000000 */ 2.73370053816464559624e-44, /* 0x36E38222, 0x80000000 */ 2.16741683877804819444e-51, /* 0x3569F31D, 0x00000000 */ ]; // fn rem_pio2_large(x : &[f64], y : &mut [f64], e0 : i32, prec : usize) -> i32 // // Input parameters: // x[] The input value (must be positive) is broken into nx // pieces of 24-bit integers in double precision format. // x[i] will be the i-th 24 bit of x. The scaled exponent // of x[0] is given in input parameter e0 (i.e., x[0]*2^e0 // match x's up to 24 bits. // // Example of breaking a double positive z into x[0]+x[1]+x[2]: // e0 = ilogb(z)-23 // z = scalbn(z,-e0) // for i = 0,1,2 // x[i] = floor(z) // z = (z-x[i])*2**24 // // y[] ouput result in an array of double precision numbers. // The dimension of y[] is: // 24-bit precision 1 // 53-bit precision 2 // 64-bit precision 2 // 113-bit precision 3 // The actual value is the sum of them. Thus for 113-bit // precison, one may have to do something like: // // long double t,w,r_head, r_tail; // t = (long double)y[2] + (long double)y[1]; // w = (long double)y[0]; // r_head = t+w; // r_tail = w - (r_head - t); // // e0 The exponent of x[0]. Must be <= 16360 or you need to // expand the ipio2 table. // // prec an integer indicating the precision: // 0 24 bits (single) // 1 53 bits (double) // 2 64 bits (extended) // 3 113 bits (quad) // // Here is the description of some local variables: // // jk jk+1 is the initial number of terms of ipio2[] needed // in the computation. The minimum and recommended value // for jk is 3,4,4,6 for single, double, extended, and quad. // jk+1 must be 2 larger than you might expect so that our // recomputation test works. (Up to 24 bits in the integer // part (the 24 bits of it that we compute) and 23 bits in // the fraction part may be lost to cancelation before we // recompute.) // // jz local integer variable indicating the number of // terms of ipio2[] used. // // jx nx - 1 // // jv index for pointing to the suitable ipio2[] for the // computation. In general, we want // ( 2^e0*x[0] * ipio2[jv-1]*2^(-24jv) )/8 // is an integer. Thus // e0-3-24*jv >= 0 or (e0-3)/24 >= jv // Hence jv = max(0,(e0-3)/24). // // jp jp+1 is the number of terms in PIo2[] needed, jp = jk. // // q[] double array with integral value, representing the // 24-bits chunk of the product of x and 2/pi. // // q0 the corresponding exponent of q[0]. Note that the // exponent for q[i] would be q0-24*i. // // PIo2[] double precision array, obtained by cutting pi/2 // into 24 bits chunks. // // f[] ipio2[] in floating point // // iq[] integer array by breaking up q[] in 24-bits chunk. // // fq[] final product of x*(2/pi) in fq[0],..,fq[jk] // // ih integer. If >0 it indicates q[] is >= 0.5, hence // it also indicates the *sign* of the result. /// Return the last three digits of N with y = x - N*pi/2 /// so that |y| < pi/2. /// /// The method is to compute the integer (mod 8) and fraction parts of /// (2/pi)*x without doing the full multiplication. In general we /// skip the part of the product that are known to be a huge integer ( /// more accurately, = 0 mod 8 ). Thus the number of operations are /// independent of the exponent of the input. #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub(crate) fn rem_pio2_large(x: &[f64], y: &mut [f64], e0: i32, prec: usize) -> i32 { let x1p24 = f64::from_bits(0x4170000000000000); // 0x1p24 === 2 ^ 24 let x1p_24 = f64::from_bits(0x3e70000000000000); // 0x1p_24 === 2 ^ (-24) #[cfg(all(target_pointer_width = "64", feature = "checked"))] assert!(e0 <= 16360); let nx = x.len(); let mut fw: f64; let mut n: i32; let mut ih: i32; let mut z: f64; let mut f: [f64; 20] = [0.; 20]; let mut fq: [f64; 20] = [0.; 20]; let mut q: [f64; 20] = [0.; 20]; let mut iq: [i32; 20] = [0; 20]; /* initialize jk*/ let jk = i!(INIT_JK, prec); let jp = jk; /* determine jx,jv,q0, note that 3>q0 */ let jx = nx - 1; let mut jv = div!(e0 - 3, 24); if jv < 0 { jv = 0; } let mut q0 = e0 - 24 * (jv + 1); let jv = jv as usize; /* set up f[0] to f[jx+jk] where f[jx+jk] = ipio2[jv+jk] */ let mut j = (jv as i32) - (jx as i32); let m = jx + jk; for i in 0..=m { i!(f, i, =, if j < 0 { 0. } else { i!(IPIO2, j as usize) as f64 }); j += 1; } /* compute q[0],q[1],...q[jk] */ for i in 0..=jk { fw = 0f64; for j in 0..=jx { fw += i!(x, j) * i!(f, jx + i - j); } i!(q, i, =, fw); } let mut jz = jk; 'recompute: loop { /* distill q[] into iq[] reversingly */ let mut i = 0i32; z = i!(q, jz); for j in (1..=jz).rev() { fw = (x1p_24 * z) as i32 as f64; i!(iq, i as usize, =, (z - x1p24 * fw) as i32); z = i!(q, j - 1) + fw; i += 1; } /* compute n */ z = scalbn(z, q0); /* actual value of z */ z -= 8.0 * floor(z * 0.125); /* trim off integer >= 8 */ n = z as i32; z -= n as f64; ih = 0; if q0 > 0 { /* need iq[jz-1] to determine n */ i = i!(iq, jz - 1) >> (24 - q0); n += i; i!(iq, jz - 1, -=, i << (24 - q0)); ih = i!(iq, jz - 1) >> (23 - q0); } else if q0 == 0 { ih = i!(iq, jz - 1) >> 23; } else if z >= 0.5 { ih = 2; } if ih > 0 { /* q > 0.5 */ n += 1; let mut carry = 0i32; for i in 0..jz { /* compute 1-q */ let j = i!(iq, i); if carry == 0 { if j != 0 { carry = 1; i!(iq, i, =, 0x1000000 - j); } } else { i!(iq, i, =, 0xffffff - j); } } if q0 > 0 { /* rare case: chance is 1 in 12 */ match q0 { 1 => { i!(iq, jz - 1, &=, 0x7fffff); } 2 => { i!(iq, jz - 1, &=, 0x3fffff); } _ => {} } } if ih == 2 { z = 1. - z; if carry != 0 { z -= scalbn(1., q0); } } } /* check if recomputation is needed */ if z == 0. { let mut j = 0; for i in (jk..=jz - 1).rev() { j |= i!(iq, i); } if j == 0 { /* need recomputation */ let mut k = 1; while i!(iq, jk - k, ==, 0) { k += 1; /* k = no. of terms needed */ } for i in (jz + 1)..=(jz + k) { /* add q[jz+1] to q[jz+k] */ i!(f, jx + i, =, i!(IPIO2, jv + i) as f64); fw = 0f64; for j in 0..=jx { fw += i!(x, j) * i!(f, jx + i - j); } i!(q, i, =, fw); } jz += k; continue 'recompute; } } break; } /* chop off zero terms */ if z == 0. { jz -= 1; q0 -= 24; while i!(iq, jz) == 0 { jz -= 1; q0 -= 24; } } else { /* break z into 24-bit if necessary */ z = scalbn(z, -q0); if z >= x1p24 { fw = (x1p_24 * z) as i32 as f64; i!(iq, jz, =, (z - x1p24 * fw) as i32); jz += 1; q0 += 24; i!(iq, jz, =, fw as i32); } else { i!(iq, jz, =, z as i32); } } /* convert integer "bit" chunk to floating-point value */ fw = scalbn(1., q0); for i in (0..=jz).rev() { i!(q, i, =, fw * (i!(iq, i) as f64)); fw *= x1p_24; } /* compute PIo2[0,...,jp]*q[jz,...,0] */ for i in (0..=jz).rev() { fw = 0f64; let mut k = 0; while (k <= jp) && (k <= jz - i) { fw += i!(PIO2, k) * i!(q, i + k); k += 1; } i!(fq, jz - i, =, fw); } /* compress fq[] into y[] */ match prec { 0 => { fw = 0f64; for i in (0..=jz).rev() { fw += i!(fq, i); } i!(y, 0, =, if ih == 0 { fw } else { -fw }); } 1 | 2 => { fw = 0f64; for i in (0..=jz).rev() { fw += i!(fq, i); } // TODO: drop excess precision here once double_t is used fw = fw as f64; i!(y, 0, =, if ih == 0 { fw } else { -fw }); fw = i!(fq, 0) - fw; for i in 1..=jz { fw += i!(fq, i); } i!(y, 1, =, if ih == 0 { fw } else { -fw }); } 3 => { /* painful */ for i in (1..=jz).rev() { fw = i!(fq, i - 1) + i!(fq, i); i!(fq, i, +=, i!(fq, i - 1) - fw); i!(fq, i - 1, =, fw); } for i in (2..=jz).rev() { fw = i!(fq, i - 1) + i!(fq, i); i!(fq, i, +=, i!(fq, i - 1) - fw); i!(fq, i - 1, =, fw); } fw = 0f64; for i in (2..=jz).rev() { fw += i!(fq, i); } if ih == 0 { i!(y, 0, =, i!(fq, 0)); i!(y, 1, =, i!(fq, 1)); i!(y, 2, =, fw); } else { i!(y, 0, =, -i!(fq, 0)); i!(y, 1, =, -i!(fq, 1)); i!(y, 2, =, -fw); } } #[cfg(debug_assertions)] _ => unreachable!(), #[cfg(not(debug_assertions))] _ => {} } n & 7 }
use serde::{Deserialize, Serialize}; use saoleile_derive::NetworkEvent; use crate::event::NetworkEvent; use crate::scene::{Entity, Scene}; use crate::util::{Tick, Id}; #[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)] pub struct SnapshotEvent { pub authority: Id, pub is_correction: bool, pub tick: Tick, pub events: Vec<Box<dyn NetworkEvent>>, } #[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)] pub struct AddSceneEvent { pub scene_id: Id, pub scene: Scene, } #[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)] pub struct RemoveSceneEvent { pub scene_id: Id, } #[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)] pub struct AddEntityEvent { pub scene_id: Id, pub entity_id: Id, pub entity: Entity, } #[derive(Clone, Debug, Deserialize, NetworkEvent, Serialize)] pub struct RemoveEntityEvent { pub scene_id: Id, pub entity_id: Id, }
// Copyright (c) 2018-2022 Ministerio de Fomento // Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>, // Daniel Jiménez González <dani@ietcc.csic.es>, // Marta Sorribes Gil <msorribes@ietcc.csic.es> /*! CteEPBD ======= This crate provides a library and binary that **implements most of the ISO EN 52000-1 standard** *Energy performance of buildings - Overarching EPB assessment - General framework and procedures* (under version EN ISO 52000-1:2017). This is oriented towards the assessment of the energy performance of buildings under the spanish building code (CTE) and, thus, uses specific naming conventions and default values best suited for that purpose. It also holds the following assumptions: - constant weighting factors through all timesteps - no priority is defined for energy production (average step A weighting factor f_we_el_stepA) - all on-site produced energy from non cogeneration sources is considered as delivered - on-site produced energy is not compensated on a service by service basis, but on a carrier basis - unit and constant load matching factor Some restrictions may be lifted in the future. Specifically: - implement a load matching factor (f_match_t) following formula B.32 in appendix B - allow the imputation to a specific service for produced energy - allow setting priorities for energy production Este *crate* proporciona una biblioteca y un programa que **implementa una parte sustancial del estándar EN ISO 52000-1**: *Eficiencia energética de los edificios - Evaluación global de la EPB - Parte 1: Marco general y procedimientos* (versión EN ISO 52000-1:2017). Este software está orientado a la evaluación de la eficiencia energética de los edificios dentro del marco de la normativa española de edificación (Código Técnico de la Edificación CTE, DB-HE) y, así, adopta nomenclatura y valores por defecto adaptados a ese propósito. También realiza los siguientes supuestos: - factores de paso constantes en todo el periodo de cálculo - no se definen prioridades para la producción de energía - se considera como suministrada toda la energía producida procedente de fuentes distintas a la cogeneración - la energía producida in situ se compensa por vector energético y no por servicios - factor de coincidencia de cargas igual a la unidad Algunas restricciones pueden revisarse en el futuro, tales como: - implementación del factor de coincidencia de cargas según fórmula B.32 del apéndice B - imputación de energía generada a servicios específicos - fijación de prioridades para la producción de energía # Ejemplo ```rust use std::fs::{read_to_string, File}; use cteepbd::*; // lectura de un archivo de componentes energéticos let components = read_to_string("test_data/cte_test_carriers.csv") .unwrap() .parse::<Components>() .unwrap(); // Definición de los factores de usuario y sus valores por defecto let user_wf = UserWF { red1: Some((1.0, 0.0, 0.0).into()), red2: None, }; // Factores definidos por el usuario let default_user_wf = cte::CTE_USERWF; // Valores por defecto de factores de paso del usuario // Factores de usuario reglamentarios según localización y factores de usuario let fp = cte::wfactors_from_loc("PENINSULA", &cte::CTE_LOCWF_RITE2014, user_wf, default_user_wf ).unwrap(); // Factor de exportación y área de referencia let kexp = cte::KEXP_DEFAULT; // factor de exportación [-] let arearef = 200.0; // superficie de referencia [m2] // Cálculo del balance global según EN ISO 52000-1:2017 let load_matching = false; let ep = energy_performance(&components, &fp, kexp, arearef, load_matching).unwrap(); // Visualización compacta println!("{}", &ep.to_plain()); ``` */ #![deny(missing_docs)] #[cfg(test)] // <-- not needed in examples + integration tests #[macro_use] extern crate pretty_assertions; mod asctexml; mod asplain; mod balance; mod components; mod vecops; mod wfactors; pub mod cte; pub mod error; pub mod types; pub use asctexml::*; pub use asplain::*; pub use balance::*; pub use components::*; pub use wfactors::*; /// Número de versión de la librería /// /// Version number pub static VERSION: &str = env!("CARGO_PKG_VERSION");
extern crate clap; extern crate poe_api as poe; use clap::{App, Arg}; fn main() { let matches = App::new("PoE Character Window") .about("Path of Exile Character Window CLI.") .arg(Arg::with_name("ACCOUNT_NAME") .help("PoE Account Name") .required(true) .index(1)) .arg(Arg::with_name("CHARACTER") .help("PoE Character Name") .required(true) .index(2)) .arg(Arg::with_name("DETAIL") .help("PoE Character Detail - items, passives or stash") .required(true) .index(3)) .get_matches(); let account_name = matches.value_of("ACCOUNT_NAME").unwrap(); let characeter = matches.value_of("CHARACTER").unwrap(); let detail = matches.value_of("DETAIL").unwrap(); match detail { "items" => { let items = poe::character_and_items(account_name, characeter) .expect("Failed to get data."); println!("{:#?}", items); }, "passives" => { // let passives = poe::character_and_passives(account_name, characeter) // .expect("Failed to get data."); // // println!("{:#?}", passives); }, "stash" => { // let stash = poe::character_and_stash(account_name, characeter) // .expect("Failed to get data."); // // println!("{:#?}", stash); }, _ => { println!("Sorry but cannot help with that request.") } } }
pub mod required; pub mod extra;
use proconio::input; fn main() { input! { mut a: [u64; 3], }; a.sort(); if a[0] + a[1] >= a[2] { println!("{}", a[2]); } else { println!("-1"); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentAction(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentAction { type Vtable = ITargetedContentAction_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd75b691e_6cd6_4ca0_9d8f_4728b0b7e6b6); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentAction_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentAvailabilityChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentAvailabilityChangedEventArgs { type Vtable = ITargetedContentAvailabilityChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0f59d26_5927_4450_965c_1ceb7becde65); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentAvailabilityChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentChangedEventArgs { type Vtable = ITargetedContentChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x99d488c9_587e_4586_8ef7_b54ca9453a16); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentCollection(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentCollection { type Vtable = ITargetedContentCollection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2d4b66c5_f163_44ba_9f6e_e1a4c2bb559d); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentCollection_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, interaction: TargetedContentInteraction) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, custominteractionname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentContainer(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentContainer { type Vtable = ITargetedContentContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc2494c9_8837_47c2_850f_d79d64595926); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentContainer_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TargetedContentAvailability) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, path: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentContainerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentContainerStatics { type Vtable = ITargetedContentContainerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5b47e7fb_2140_4c1f_a736_c59583f227d8); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentContainerStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, contentid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentImage(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentImage { type Vtable = ITargetedContentImage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa7a585d9_779f_4b1e_bbb1_8eaf53fbeab2); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentImage_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentItem(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentItem { type Vtable = ITargetedContentItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38168dc4_276c_4c32_96ba_565c6e406e74); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentItem_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, interaction: TargetedContentInteraction) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, custominteractionname: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentItemState(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentItemState { type Vtable = ITargetedContentItemState_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x73935454_4c65_4b47_a441_472de53c79b6); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentItemState_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TargetedContentAppInstallationState) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentObject(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentObject { type Vtable = ITargetedContentObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x041d7969_2212_42d1_9dfa_88a8e3033aa3); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentObject_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TargetedContentObjectKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentStateChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentStateChangedEventArgs { type Vtable = ITargetedContentStateChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a1cef3d_8073_4416_8df2_546835a6414f); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentStateChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentSubscription(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentSubscription { type Vtable = ITargetedContentSubscription_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x882c2c49_c652_4c7a_acad_1f7fa2986c73); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentSubscription_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cookie: super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentSubscriptionOptions(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentSubscriptionOptions { type Vtable = ITargetedContentSubscriptionOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x61ee6ad0_2c83_421b_8467_413eaf1aeb97); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentSubscriptionOptions_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentSubscriptionStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentSubscriptionStatics { type Vtable = ITargetedContentSubscriptionStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfaddfe80_360d_4916_b53c_7ea27090d02a); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentSubscriptionStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, subscriptionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, subscriptionid: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct ITargetedContentValue(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ITargetedContentValue { type Vtable = ITargetedContentValue_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaafde4b3_4215_4bf8_867f_43f04865f9bf); } #[repr(C)] #[doc(hidden)] pub struct ITargetedContentValue_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut TargetedContentValueKind) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Storage_Streams")))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentAction(pub ::windows::core::IInspectable); impl TargetedContentAction { #[cfg(feature = "Foundation")] pub fn InvokeAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncAction>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentAction { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentAction;{d75b691e-6cd6-4ca0-9d8f-4728b0b7e6b6})"); } unsafe impl ::windows::core::Interface for TargetedContentAction { type Vtable = ITargetedContentAction_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd75b691e_6cd6_4ca0_9d8f_4728b0b7e6b6); } impl ::windows::core::RuntimeName for TargetedContentAction { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentAction"; } impl ::core::convert::From<TargetedContentAction> for ::windows::core::IUnknown { fn from(value: TargetedContentAction) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentAction> for ::windows::core::IUnknown { fn from(value: &TargetedContentAction) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentAction { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentAction { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentAction> for ::windows::core::IInspectable { fn from(value: TargetedContentAction) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentAction> for ::windows::core::IInspectable { fn from(value: &TargetedContentAction) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentAction { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentAction { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentAction {} unsafe impl ::core::marker::Sync for TargetedContentAction {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TargetedContentAppInstallationState(pub i32); impl TargetedContentAppInstallationState { pub const NotApplicable: TargetedContentAppInstallationState = TargetedContentAppInstallationState(0i32); pub const NotInstalled: TargetedContentAppInstallationState = TargetedContentAppInstallationState(1i32); pub const Installed: TargetedContentAppInstallationState = TargetedContentAppInstallationState(2i32); } impl ::core::convert::From<i32> for TargetedContentAppInstallationState { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TargetedContentAppInstallationState { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TargetedContentAppInstallationState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.TargetedContent.TargetedContentAppInstallationState;i4)"); } impl ::windows::core::DefaultType for TargetedContentAppInstallationState { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TargetedContentAvailability(pub i32); impl TargetedContentAvailability { pub const None: TargetedContentAvailability = TargetedContentAvailability(0i32); pub const Partial: TargetedContentAvailability = TargetedContentAvailability(1i32); pub const All: TargetedContentAvailability = TargetedContentAvailability(2i32); } impl ::core::convert::From<i32> for TargetedContentAvailability { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TargetedContentAvailability { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TargetedContentAvailability { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.TargetedContent.TargetedContentAvailability;i4)"); } impl ::windows::core::DefaultType for TargetedContentAvailability { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentAvailabilityChangedEventArgs(pub ::windows::core::IInspectable); impl TargetedContentAvailabilityChangedEventArgs { #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentAvailabilityChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentAvailabilityChangedEventArgs;{e0f59d26-5927-4450-965c-1ceb7becde65})"); } unsafe impl ::windows::core::Interface for TargetedContentAvailabilityChangedEventArgs { type Vtable = ITargetedContentAvailabilityChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe0f59d26_5927_4450_965c_1ceb7becde65); } impl ::windows::core::RuntimeName for TargetedContentAvailabilityChangedEventArgs { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentAvailabilityChangedEventArgs"; } impl ::core::convert::From<TargetedContentAvailabilityChangedEventArgs> for ::windows::core::IUnknown { fn from(value: TargetedContentAvailabilityChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentAvailabilityChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &TargetedContentAvailabilityChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentAvailabilityChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentAvailabilityChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentAvailabilityChangedEventArgs> for ::windows::core::IInspectable { fn from(value: TargetedContentAvailabilityChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentAvailabilityChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &TargetedContentAvailabilityChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentAvailabilityChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentAvailabilityChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentAvailabilityChangedEventArgs {} unsafe impl ::core::marker::Sync for TargetedContentAvailabilityChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentChangedEventArgs(pub ::windows::core::IInspectable); impl TargetedContentChangedEventArgs { #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__) } } pub fn HasPreviousContentExpired(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentChangedEventArgs;{99d488c9-587e-4586-8ef7-b54ca9453a16})"); } unsafe impl ::windows::core::Interface for TargetedContentChangedEventArgs { type Vtable = ITargetedContentChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x99d488c9_587e_4586_8ef7_b54ca9453a16); } impl ::windows::core::RuntimeName for TargetedContentChangedEventArgs { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentChangedEventArgs"; } impl ::core::convert::From<TargetedContentChangedEventArgs> for ::windows::core::IUnknown { fn from(value: TargetedContentChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &TargetedContentChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentChangedEventArgs> for ::windows::core::IInspectable { fn from(value: TargetedContentChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &TargetedContentChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentChangedEventArgs {} unsafe impl ::core::marker::Sync for TargetedContentChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentCollection(pub ::windows::core::IInspectable); impl TargetedContentCollection { pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ReportInteraction(&self, interaction: TargetedContentInteraction) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), interaction).ok() } } pub fn ReportCustomInteraction<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, custominteractionname: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), custominteractionname.into_param().abi()).ok() } } pub fn Path(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, TargetedContentValue>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, TargetedContentValue>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Collections(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentCollection>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentCollection>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Items(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentItem>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentItem>>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentCollection { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentCollection;{2d4b66c5-f163-44ba-9f6e-e1a4c2bb559d})"); } unsafe impl ::windows::core::Interface for TargetedContentCollection { type Vtable = ITargetedContentCollection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2d4b66c5_f163_44ba_9f6e_e1a4c2bb559d); } impl ::windows::core::RuntimeName for TargetedContentCollection { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentCollection"; } impl ::core::convert::From<TargetedContentCollection> for ::windows::core::IUnknown { fn from(value: TargetedContentCollection) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentCollection> for ::windows::core::IUnknown { fn from(value: &TargetedContentCollection) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentCollection> for ::windows::core::IInspectable { fn from(value: TargetedContentCollection) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentCollection> for ::windows::core::IInspectable { fn from(value: &TargetedContentCollection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentCollection {} unsafe impl ::core::marker::Sync for TargetedContentCollection {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentContainer(pub ::windows::core::IInspectable); impl TargetedContentContainer { pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::DateTime>(result__) } } pub fn Availability(&self) -> ::windows::core::Result<TargetedContentAvailability> { let this = self; unsafe { let mut result__: TargetedContentAvailability = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentAvailability>(result__) } } pub fn Content(&self) -> ::windows::core::Result<TargetedContentCollection> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentCollection>(result__) } } pub fn SelectSingleObject<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, path: Param0) -> ::windows::core::Result<TargetedContentObject> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), path.into_param().abi(), &mut result__).from_abi::<TargetedContentObject>(result__) } } #[cfg(feature = "Foundation")] pub fn GetAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(contentid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<TargetedContentContainer>> { Self::ITargetedContentContainerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), contentid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<TargetedContentContainer>>(result__) }) } pub fn ITargetedContentContainerStatics<R, F: FnOnce(&ITargetedContentContainerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TargetedContentContainer, ITargetedContentContainerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentContainer { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentContainer;{bc2494c9-8837-47c2-850f-d79d64595926})"); } unsafe impl ::windows::core::Interface for TargetedContentContainer { type Vtable = ITargetedContentContainer_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbc2494c9_8837_47c2_850f_d79d64595926); } impl ::windows::core::RuntimeName for TargetedContentContainer { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentContainer"; } impl ::core::convert::From<TargetedContentContainer> for ::windows::core::IUnknown { fn from(value: TargetedContentContainer) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentContainer> for ::windows::core::IUnknown { fn from(value: &TargetedContentContainer) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentContainer> for ::windows::core::IInspectable { fn from(value: TargetedContentContainer) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentContainer> for ::windows::core::IInspectable { fn from(value: &TargetedContentContainer) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentContainer { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentContainer {} unsafe impl ::core::marker::Sync for TargetedContentContainer {} #[cfg(feature = "Storage_Streams")] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentFile(pub ::windows::core::IInspectable); #[cfg(feature = "Storage_Streams")] impl TargetedContentFile { #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn OpenReadAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Storage::Streams::IRandomAccessStreamWithContentType>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Storage::Streams::IRandomAccessStreamWithContentType>>(result__) } } } #[cfg(feature = "Storage_Streams")] unsafe impl ::windows::core::RuntimeType for TargetedContentFile { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentFile;{33ee3134-1dd6-4e3a-8067-d1c162e8642b})"); } #[cfg(feature = "Storage_Streams")] unsafe impl ::windows::core::Interface for TargetedContentFile { type Vtable = super::super::Storage::Streams::IRandomAccessStreamReference_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x33ee3134_1dd6_4e3a_8067_d1c162e8642b); } #[cfg(feature = "Storage_Streams")] impl ::windows::core::RuntimeName for TargetedContentFile { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentFile"; } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<TargetedContentFile> for ::windows::core::IUnknown { fn from(value: TargetedContentFile) -> Self { value.0 .0 } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<&TargetedContentFile> for ::windows::core::IUnknown { fn from(value: &TargetedContentFile) -> Self { value.0 .0.clone() } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<TargetedContentFile> for ::windows::core::IInspectable { fn from(value: TargetedContentFile) -> Self { value.0 } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<&TargetedContentFile> for ::windows::core::IInspectable { fn from(value: &TargetedContentFile) -> Self { value.0.clone() } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<TargetedContentFile> for super::super::Storage::Streams::IRandomAccessStreamReference { fn from(value: TargetedContentFile) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::From<&TargetedContentFile> for super::super::Storage::Streams::IRandomAccessStreamReference { fn from(value: &TargetedContentFile) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference> for TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, super::super::Storage::Streams::IRandomAccessStreamReference> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference> for &TargetedContentFile { fn into_param(self) -> ::windows::core::Param<'a, super::super::Storage::Streams::IRandomAccessStreamReference> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Storage_Streams")] unsafe impl ::core::marker::Send for TargetedContentFile {} #[cfg(feature = "Storage_Streams")] unsafe impl ::core::marker::Sync for TargetedContentFile {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentImage(pub ::windows::core::IInspectable); impl TargetedContentImage { pub fn Height(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } pub fn Width(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn OpenReadAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Storage::Streams::IRandomAccessStreamWithContentType>> { let this = &::windows::core::Interface::cast::<super::super::Storage::Streams::IRandomAccessStreamReference>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Storage::Streams::IRandomAccessStreamWithContentType>>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentImage { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentImage;{a7a585d9-779f-4b1e-bbb1-8eaf53fbeab2})"); } unsafe impl ::windows::core::Interface for TargetedContentImage { type Vtable = ITargetedContentImage_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa7a585d9_779f_4b1e_bbb1_8eaf53fbeab2); } impl ::windows::core::RuntimeName for TargetedContentImage { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentImage"; } impl ::core::convert::From<TargetedContentImage> for ::windows::core::IUnknown { fn from(value: TargetedContentImage) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentImage> for ::windows::core::IUnknown { fn from(value: &TargetedContentImage) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentImage> for ::windows::core::IInspectable { fn from(value: TargetedContentImage) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentImage> for ::windows::core::IInspectable { fn from(value: &TargetedContentImage) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::TryFrom<TargetedContentImage> for super::super::Storage::Streams::IRandomAccessStreamReference { type Error = ::windows::core::Error; fn try_from(value: TargetedContentImage) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } #[cfg(feature = "Storage_Streams")] impl ::core::convert::TryFrom<&TargetedContentImage> for super::super::Storage::Streams::IRandomAccessStreamReference { type Error = ::windows::core::Error; fn try_from(value: &TargetedContentImage) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference> for TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, super::super::Storage::Streams::IRandomAccessStreamReference> { ::windows::core::IntoParam::into_param(&self) } } #[cfg(feature = "Storage_Streams")] impl<'a> ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStreamReference> for &TargetedContentImage { fn into_param(self) -> ::windows::core::Param<'a, super::super::Storage::Streams::IRandomAccessStreamReference> { ::core::convert::TryInto::<super::super::Storage::Streams::IRandomAccessStreamReference>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for TargetedContentImage {} unsafe impl ::core::marker::Sync for TargetedContentImage {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TargetedContentInteraction(pub i32); impl TargetedContentInteraction { pub const Impression: TargetedContentInteraction = TargetedContentInteraction(0i32); pub const ClickThrough: TargetedContentInteraction = TargetedContentInteraction(1i32); pub const Hover: TargetedContentInteraction = TargetedContentInteraction(2i32); pub const Like: TargetedContentInteraction = TargetedContentInteraction(3i32); pub const Dislike: TargetedContentInteraction = TargetedContentInteraction(4i32); pub const Dismiss: TargetedContentInteraction = TargetedContentInteraction(5i32); pub const Ineligible: TargetedContentInteraction = TargetedContentInteraction(6i32); pub const Accept: TargetedContentInteraction = TargetedContentInteraction(7i32); pub const Decline: TargetedContentInteraction = TargetedContentInteraction(8i32); pub const Defer: TargetedContentInteraction = TargetedContentInteraction(9i32); pub const Canceled: TargetedContentInteraction = TargetedContentInteraction(10i32); pub const Conversion: TargetedContentInteraction = TargetedContentInteraction(11i32); pub const Opportunity: TargetedContentInteraction = TargetedContentInteraction(12i32); } impl ::core::convert::From<i32> for TargetedContentInteraction { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TargetedContentInteraction { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TargetedContentInteraction { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.TargetedContent.TargetedContentInteraction;i4)"); } impl ::windows::core::DefaultType for TargetedContentInteraction { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentItem(pub ::windows::core::IInspectable); impl TargetedContentItem { pub fn Path(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn ReportInteraction(&self, interaction: TargetedContentInteraction) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), interaction).ok() } } pub fn ReportCustomInteraction<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, custominteractionname: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), custominteractionname.into_param().abi()).ok() } } pub fn State(&self) -> ::windows::core::Result<TargetedContentItemState> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentItemState>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Properties(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, TargetedContentValue>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, TargetedContentValue>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Collections(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentCollection>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentCollection>>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentItem { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentItem;{38168dc4-276c-4c32-96ba-565c6e406e74})"); } unsafe impl ::windows::core::Interface for TargetedContentItem { type Vtable = ITargetedContentItem_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38168dc4_276c_4c32_96ba_565c6e406e74); } impl ::windows::core::RuntimeName for TargetedContentItem { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentItem"; } impl ::core::convert::From<TargetedContentItem> for ::windows::core::IUnknown { fn from(value: TargetedContentItem) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentItem> for ::windows::core::IUnknown { fn from(value: &TargetedContentItem) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentItem> for ::windows::core::IInspectable { fn from(value: TargetedContentItem) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentItem> for ::windows::core::IInspectable { fn from(value: &TargetedContentItem) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentItem { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentItem {} unsafe impl ::core::marker::Sync for TargetedContentItem {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentItemState(pub ::windows::core::IInspectable); impl TargetedContentItemState { pub fn ShouldDisplay(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn AppInstallationState(&self) -> ::windows::core::Result<TargetedContentAppInstallationState> { let this = self; unsafe { let mut result__: TargetedContentAppInstallationState = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentAppInstallationState>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentItemState { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentItemState;{73935454-4c65-4b47-a441-472de53c79b6})"); } unsafe impl ::windows::core::Interface for TargetedContentItemState { type Vtable = ITargetedContentItemState_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x73935454_4c65_4b47_a441_472de53c79b6); } impl ::windows::core::RuntimeName for TargetedContentItemState { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentItemState"; } impl ::core::convert::From<TargetedContentItemState> for ::windows::core::IUnknown { fn from(value: TargetedContentItemState) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentItemState> for ::windows::core::IUnknown { fn from(value: &TargetedContentItemState) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentItemState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentItemState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentItemState> for ::windows::core::IInspectable { fn from(value: TargetedContentItemState) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentItemState> for ::windows::core::IInspectable { fn from(value: &TargetedContentItemState) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentItemState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentItemState { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentItemState {} unsafe impl ::core::marker::Sync for TargetedContentItemState {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentObject(pub ::windows::core::IInspectable); impl TargetedContentObject { pub fn ObjectKind(&self) -> ::windows::core::Result<TargetedContentObjectKind> { let this = self; unsafe { let mut result__: TargetedContentObjectKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentObjectKind>(result__) } } pub fn Collection(&self) -> ::windows::core::Result<TargetedContentCollection> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentCollection>(result__) } } pub fn Item(&self) -> ::windows::core::Result<TargetedContentItem> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentItem>(result__) } } pub fn Value(&self) -> ::windows::core::Result<TargetedContentValue> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentValue>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentObject { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentObject;{041d7969-2212-42d1-9dfa-88a8e3033aa3})"); } unsafe impl ::windows::core::Interface for TargetedContentObject { type Vtable = ITargetedContentObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x041d7969_2212_42d1_9dfa_88a8e3033aa3); } impl ::windows::core::RuntimeName for TargetedContentObject { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentObject"; } impl ::core::convert::From<TargetedContentObject> for ::windows::core::IUnknown { fn from(value: TargetedContentObject) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentObject> for ::windows::core::IUnknown { fn from(value: &TargetedContentObject) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentObject> for ::windows::core::IInspectable { fn from(value: TargetedContentObject) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentObject> for ::windows::core::IInspectable { fn from(value: &TargetedContentObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentObject {} unsafe impl ::core::marker::Sync for TargetedContentObject {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TargetedContentObjectKind(pub i32); impl TargetedContentObjectKind { pub const Collection: TargetedContentObjectKind = TargetedContentObjectKind(0i32); pub const Item: TargetedContentObjectKind = TargetedContentObjectKind(1i32); pub const Value: TargetedContentObjectKind = TargetedContentObjectKind(2i32); } impl ::core::convert::From<i32> for TargetedContentObjectKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TargetedContentObjectKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TargetedContentObjectKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.TargetedContent.TargetedContentObjectKind;i4)"); } impl ::windows::core::DefaultType for TargetedContentObjectKind { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentStateChangedEventArgs(pub ::windows::core::IInspectable); impl TargetedContentStateChangedEventArgs { #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentStateChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentStateChangedEventArgs;{9a1cef3d-8073-4416-8df2-546835a6414f})"); } unsafe impl ::windows::core::Interface for TargetedContentStateChangedEventArgs { type Vtable = ITargetedContentStateChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9a1cef3d_8073_4416_8df2_546835a6414f); } impl ::windows::core::RuntimeName for TargetedContentStateChangedEventArgs { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentStateChangedEventArgs"; } impl ::core::convert::From<TargetedContentStateChangedEventArgs> for ::windows::core::IUnknown { fn from(value: TargetedContentStateChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentStateChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &TargetedContentStateChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentStateChangedEventArgs> for ::windows::core::IInspectable { fn from(value: TargetedContentStateChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentStateChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &TargetedContentStateChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentStateChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentStateChangedEventArgs {} unsafe impl ::core::marker::Sync for TargetedContentStateChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentSubscription(pub ::windows::core::IInspectable); impl TargetedContentSubscription { pub fn Id(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn GetContentContainerAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<TargetedContentContainer>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<TargetedContentContainer>>(result__) } } #[cfg(feature = "Foundation")] pub fn ContentChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<TargetedContentSubscription, TargetedContentChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveContentChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn AvailabilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<TargetedContentSubscription, TargetedContentAvailabilityChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveAvailabilityChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn StateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<TargetedContentSubscription, TargetedContentStateChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveStateChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, cookie: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), cookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn GetAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(subscriptionid: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<TargetedContentSubscription>> { Self::ITargetedContentSubscriptionStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), subscriptionid.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<TargetedContentSubscription>>(result__) }) } pub fn GetOptions<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(subscriptionid: Param0) -> ::windows::core::Result<TargetedContentSubscriptionOptions> { Self::ITargetedContentSubscriptionStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), subscriptionid.into_param().abi(), &mut result__).from_abi::<TargetedContentSubscriptionOptions>(result__) }) } pub fn ITargetedContentSubscriptionStatics<R, F: FnOnce(&ITargetedContentSubscriptionStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<TargetedContentSubscription, ITargetedContentSubscriptionStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentSubscription { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentSubscription;{882c2c49-c652-4c7a-acad-1f7fa2986c73})"); } unsafe impl ::windows::core::Interface for TargetedContentSubscription { type Vtable = ITargetedContentSubscription_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x882c2c49_c652_4c7a_acad_1f7fa2986c73); } impl ::windows::core::RuntimeName for TargetedContentSubscription { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentSubscription"; } impl ::core::convert::From<TargetedContentSubscription> for ::windows::core::IUnknown { fn from(value: TargetedContentSubscription) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentSubscription> for ::windows::core::IUnknown { fn from(value: &TargetedContentSubscription) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentSubscription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentSubscription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentSubscription> for ::windows::core::IInspectable { fn from(value: TargetedContentSubscription) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentSubscription> for ::windows::core::IInspectable { fn from(value: &TargetedContentSubscription) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentSubscription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentSubscription { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentSubscription {} unsafe impl ::core::marker::Sync for TargetedContentSubscription {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentSubscriptionOptions(pub ::windows::core::IInspectable); impl TargetedContentSubscriptionOptions { pub fn SubscriptionId(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn AllowPartialContentAvailability(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetAllowPartialContentAvailability(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn CloudQueryParameters(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMap<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn LocalFilters(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<::windows::core::HSTRING>>(result__) } } pub fn Update(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for TargetedContentSubscriptionOptions { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentSubscriptionOptions;{61ee6ad0-2c83-421b-8467-413eaf1aeb97})"); } unsafe impl ::windows::core::Interface for TargetedContentSubscriptionOptions { type Vtable = ITargetedContentSubscriptionOptions_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x61ee6ad0_2c83_421b_8467_413eaf1aeb97); } impl ::windows::core::RuntimeName for TargetedContentSubscriptionOptions { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentSubscriptionOptions"; } impl ::core::convert::From<TargetedContentSubscriptionOptions> for ::windows::core::IUnknown { fn from(value: TargetedContentSubscriptionOptions) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentSubscriptionOptions> for ::windows::core::IUnknown { fn from(value: &TargetedContentSubscriptionOptions) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentSubscriptionOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentSubscriptionOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentSubscriptionOptions> for ::windows::core::IInspectable { fn from(value: TargetedContentSubscriptionOptions) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentSubscriptionOptions> for ::windows::core::IInspectable { fn from(value: &TargetedContentSubscriptionOptions) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentSubscriptionOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentSubscriptionOptions { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentSubscriptionOptions {} unsafe impl ::core::marker::Sync for TargetedContentSubscriptionOptions {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct TargetedContentValue(pub ::windows::core::IInspectable); impl TargetedContentValue { pub fn ValueKind(&self) -> ::windows::core::Result<TargetedContentValueKind> { let this = self; unsafe { let mut result__: TargetedContentValueKind = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentValueKind>(result__) } } pub fn Path(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn String(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn Uri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Uri>(result__) } } pub fn Number(&self) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__) } } pub fn Boolean(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn File(&self) -> ::windows::core::Result<TargetedContentFile> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentFile>(result__) } } pub fn ImageFile(&self) -> ::windows::core::Result<TargetedContentImage> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentImage>(result__) } } pub fn Action(&self) -> ::windows::core::Result<TargetedContentAction> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TargetedContentAction>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Strings(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn Uris(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<super::super::Foundation::Uri>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<super::super::Foundation::Uri>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Numbers(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<f64>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<f64>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Booleans(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<bool>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<bool>>(result__) } } #[cfg(all(feature = "Foundation_Collections", feature = "Storage_Streams"))] pub fn Files(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentFile>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentFile>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn ImageFiles(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentImage>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentImage>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Actions(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<TargetedContentAction>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<TargetedContentAction>>(result__) } } } unsafe impl ::windows::core::RuntimeType for TargetedContentValue { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Services.TargetedContent.TargetedContentValue;{aafde4b3-4215-4bf8-867f-43f04865f9bf})"); } unsafe impl ::windows::core::Interface for TargetedContentValue { type Vtable = ITargetedContentValue_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaafde4b3_4215_4bf8_867f_43f04865f9bf); } impl ::windows::core::RuntimeName for TargetedContentValue { const NAME: &'static str = "Windows.Services.TargetedContent.TargetedContentValue"; } impl ::core::convert::From<TargetedContentValue> for ::windows::core::IUnknown { fn from(value: TargetedContentValue) -> Self { value.0 .0 } } impl ::core::convert::From<&TargetedContentValue> for ::windows::core::IUnknown { fn from(value: &TargetedContentValue) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TargetedContentValue { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a TargetedContentValue { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<TargetedContentValue> for ::windows::core::IInspectable { fn from(value: TargetedContentValue) -> Self { value.0 } } impl ::core::convert::From<&TargetedContentValue> for ::windows::core::IInspectable { fn from(value: &TargetedContentValue) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TargetedContentValue { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a TargetedContentValue { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for TargetedContentValue {} unsafe impl ::core::marker::Sync for TargetedContentValue {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct TargetedContentValueKind(pub i32); impl TargetedContentValueKind { pub const String: TargetedContentValueKind = TargetedContentValueKind(0i32); pub const Uri: TargetedContentValueKind = TargetedContentValueKind(1i32); pub const Number: TargetedContentValueKind = TargetedContentValueKind(2i32); pub const Boolean: TargetedContentValueKind = TargetedContentValueKind(3i32); pub const File: TargetedContentValueKind = TargetedContentValueKind(4i32); pub const ImageFile: TargetedContentValueKind = TargetedContentValueKind(5i32); pub const Action: TargetedContentValueKind = TargetedContentValueKind(6i32); pub const Strings: TargetedContentValueKind = TargetedContentValueKind(7i32); pub const Uris: TargetedContentValueKind = TargetedContentValueKind(8i32); pub const Numbers: TargetedContentValueKind = TargetedContentValueKind(9i32); pub const Booleans: TargetedContentValueKind = TargetedContentValueKind(10i32); pub const Files: TargetedContentValueKind = TargetedContentValueKind(11i32); pub const ImageFiles: TargetedContentValueKind = TargetedContentValueKind(12i32); pub const Actions: TargetedContentValueKind = TargetedContentValueKind(13i32); } impl ::core::convert::From<i32> for TargetedContentValueKind { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for TargetedContentValueKind { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for TargetedContentValueKind { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Services.TargetedContent.TargetedContentValueKind;i4)"); } impl ::windows::core::DefaultType for TargetedContentValueKind { type DefaultType = Self; }
use abstutil::{FileWithProgress, Timer}; use geom::{GPSBounds, HashablePt2D, LonLat, Polygon, Pt2D}; use map_model::{osm, raw_data, AreaType}; use osm_xml; use std::collections::{BTreeMap, HashMap, HashSet}; use std::fs::File; use std::io::{BufRead, BufReader}; pub fn extract_osm( osm_path: &str, maybe_clip_path: &Option<String>, timer: &mut Timer, ) -> ( raw_data::Map, // Un-split roads Vec<raw_data::Road>, // Traffic signals HashSet<HashablePt2D>, // OSM Node IDs HashMap<HashablePt2D, i64>, ) { let (reader, done) = FileWithProgress::new(osm_path).unwrap(); let doc = osm_xml::OSM::parse(reader).expect("OSM parsing failed"); println!( "OSM doc has {} nodes, {} ways, {} relations", doc.nodes.len(), doc.ways.len(), doc.relations.len() ); done(timer); let mut map = if let Some(ref path) = maybe_clip_path { read_osmosis_polygon(path) } else { let mut m = raw_data::Map::blank(abstutil::basename(osm_path)); for node in doc.nodes.values() { m.gps_bounds.update(LonLat::new(node.lon, node.lat)); } m.boundary_polygon = m.gps_bounds.to_bounds().get_rectangle(); m }; let mut id_to_way: HashMap<i64, Vec<Pt2D>> = HashMap::new(); let mut roads: Vec<raw_data::Road> = Vec::new(); let mut traffic_signals: HashSet<HashablePt2D> = HashSet::new(); let mut osm_node_ids = HashMap::new(); timer.start_iter("processing OSM nodes", doc.nodes.len()); for node in doc.nodes.values() { timer.next(); let pt = Pt2D::forcibly_from_gps(LonLat::new(node.lon, node.lat), &map.gps_bounds).to_hashable(); osm_node_ids.insert(pt, node.id); let tags = tags_to_map(&node.tags); if tags.get(osm::HIGHWAY) == Some(&"traffic_signals".to_string()) { traffic_signals.insert(pt); } } timer.start_iter("processing OSM ways", doc.ways.len()); for way in doc.ways.values() { timer.next(); let mut valid = true; let mut gps_pts = Vec::new(); for node_ref in &way.nodes { match doc.resolve_reference(node_ref) { osm_xml::Reference::Node(node) => { gps_pts.push(LonLat::new(node.lon, node.lat)); } // Don't handle nested ways/relations yet _ => { valid = false; } } } if !valid { continue; } let pts = map.gps_bounds.forcibly_convert(&gps_pts); let mut tags = tags_to_map(&way.tags); tags.insert(osm::OSM_WAY_ID.to_string(), way.id.to_string()); if is_road(&tags) { roads.push(raw_data::Road { osm_way_id: way.id, center_points: pts, orig_id: raw_data::OriginalRoad { osm_way_id: way.id, pt1: gps_pts[0], pt2: *gps_pts.last().unwrap(), }, osm_tags: tags, // We'll fill this out later i1: raw_data::StableIntersectionID(0), i2: raw_data::StableIntersectionID(0), }); } else if is_bldg(&tags) { let deduped = Pt2D::approx_dedupe(pts, geom::EPSILON_DIST); if deduped.len() < 3 { continue; } let id = raw_data::StableBuildingID(map.buildings.len()); map.buildings.insert( id, raw_data::Building { osm_way_id: way.id, polygon: Polygon::new(&deduped), osm_tags: tags, parking: None, }, ); } else if let Some(at) = get_area_type(&tags) { if pts.len() < 3 { continue; } map.areas.push(raw_data::Area { area_type: at, osm_id: way.id, polygon: Polygon::new(&pts), osm_tags: tags, }); } else { // The way might be part of a relation later. id_to_way.insert(way.id, pts); } } timer.start_iter("processing OSM relations", doc.relations.len()); for rel in doc.relations.values() { timer.next(); let mut tags = tags_to_map(&rel.tags); tags.insert(osm::OSM_REL_ID.to_string(), rel.id.to_string()); if let Some(at) = get_area_type(&tags) { if tags.get("type") == Some(&"multipolygon".to_string()) { let mut ok = true; let mut pts_per_way: Vec<Vec<Pt2D>> = Vec::new(); for member in &rel.members { match member { osm_xml::Member::Way(osm_xml::UnresolvedReference::Way(id), ref role) => { // If the way is clipped out, that's fine if let Some(pts) = id_to_way.get(id) { if role == "outer" { pts_per_way.push(pts.to_vec()); } else { println!( "Relation {} has unhandled member role {}, ignoring it", rel.id, role ); } } } _ => { println!("Relation {} refers to {:?}", rel.id, member); ok = false; } } } if ok { let polygons = glue_multipolygon(pts_per_way); if polygons.is_empty() { println!("Relation {} failed to glue multipolygon", rel.id); } else { for polygon in polygons { map.areas.push(raw_data::Area { area_type: at, osm_id: rel.id, polygon, osm_tags: tags.clone(), }); } } } } } else if tags.get("type") == Some(&"restriction".to_string()) { let mut from_way_id: Option<i64> = None; let mut to_way_id: Option<i64> = None; for member in &rel.members { if let osm_xml::Member::Way(osm_xml::UnresolvedReference::Way(id), ref role) = member { if role == "from" { from_way_id = Some(*id); } else if role == "to" { to_way_id = Some(*id); } } } if let (Some(from_way_id), Some(to_way_id)) = (from_way_id, to_way_id) { if let Some(restriction) = tags.get("restriction") { map.turn_restrictions .entry(from_way_id) .or_insert_with(Vec::new) .push((restriction.to_string(), to_way_id)); } } } } (map, roads, traffic_signals, osm_node_ids) } fn tags_to_map(raw_tags: &[osm_xml::Tag]) -> BTreeMap<String, String> { raw_tags .iter() .filter_map(|tag| { // Toss out really useless metadata. if tag.key.starts_with("tiger:") || tag.key.starts_with("old_name:") { None } else { Some((tag.key.clone(), tag.val.clone())) } }) .collect() } fn is_road(tags: &BTreeMap<String, String>) -> bool { if !tags.contains_key(osm::HIGHWAY) { return false; } // https://github.com/Project-OSRM/osrm-backend/blob/master/profiles/car.lua is another // potential reference for &value in &[ // List of non-car types from https://wiki.openstreetmap.org/wiki/Key:highway // TODO Footways are very useful, but they need more work to associate with main roads "footway", "living_street", "pedestrian", "track", "bus_guideway", "escape", "raceway", "bridleway", "steps", "path", "cycleway", "proposed", "construction", // This one's debatable. Includes alleys. "service", // more discovered manually "abandoned", "elevator", "planned", "razed", ] { if tags.get(osm::HIGHWAY) == Some(&String::from(value)) { return false; } } true } fn is_bldg(tags: &BTreeMap<String, String>) -> bool { tags.contains_key("building") } fn get_area_type(tags: &BTreeMap<String, String>) -> Option<AreaType> { if tags.get("leisure") == Some(&"park".to_string()) { return Some(AreaType::Park); } if tags.get("leisure") == Some(&"golf_course".to_string()) { return Some(AreaType::Park); } if tags.get("natural") == Some(&"wood".to_string()) { return Some(AreaType::Park); } if tags.get("landuse") == Some(&"cemetery".to_string()) { return Some(AreaType::Park); } if tags.get("natural") == Some(&"water".to_string()) { return Some(AreaType::Water); } None } // The result could be more than one disjoint polygon. fn glue_multipolygon(mut pts_per_way: Vec<Vec<Pt2D>>) -> Vec<Polygon> { // First deal with all of the closed loops. let mut polygons: Vec<Polygon> = Vec::new(); pts_per_way.retain(|pts| { if pts[0] == *pts.last().unwrap() { polygons.push(Polygon::new(pts)); false } else { true } }); if pts_per_way.is_empty() { return polygons; } // The main polygon let mut result = pts_per_way.pop().unwrap(); let mut reversed = false; while !pts_per_way.is_empty() { let glue_pt = *result.last().unwrap(); if let Some(idx) = pts_per_way .iter() .position(|pts| pts[0] == glue_pt || *pts.last().unwrap() == glue_pt) { let mut append = pts_per_way.remove(idx); if append[0] != glue_pt { append.reverse(); } result.pop(); result.extend(append); } else { if reversed { // Totally filter the thing out, since something clearly broke. return Vec::new(); } else { reversed = true; result.reverse(); // Try again! } } } // Some ways of the multipolygon are clipped out. Connect the ends in the most straightforward // way. Later polygon clipping will trim to the boundary. if result[0] != *result.last().unwrap() { result.push(result[0]); } polygons.push(Polygon::new(&result)); polygons } fn read_osmosis_polygon(path: &str) -> raw_data::Map { let mut pts: Vec<LonLat> = Vec::new(); let mut gps_bounds = GPSBounds::new(); for (idx, maybe_line) in BufReader::new(File::open(path).unwrap()) .lines() .enumerate() { if idx == 0 || idx == 1 { continue; } let line = maybe_line.unwrap(); if line == "END" { break; } let parts: Vec<&str> = line.trim_start().split(" ").collect(); assert!(parts.len() == 2); let pt = LonLat::new( parts[0].parse::<f64>().unwrap(), parts[1].parse::<f64>().unwrap(), ); pts.push(pt); gps_bounds.update(pt); } let mut map = raw_data::Map::blank(abstutil::basename(path)); map.boundary_polygon = Polygon::new(&gps_bounds.must_convert(&pts)); map.gps_bounds = gps_bounds; map }
fn main() { let _v: Vec<i32> = Vec::new(); // type annotation required because no values inside let mut v = vec![1, 2, 3]; // type annotation not required println!("v = {:?}", v); // adding elements v.push(5); v.push(7); println!("v = {:?}", v); // reading elements // 1. via index let third: &i32 = &v[2]; // panic if element not found println!("Third element is {}", third); // 2. via get method match v.get(3) { // safe way to get even if element not found - no panic Some(fourth) => println!("Fourth is {}", fourth), None => println!("No fourth found"), } // Iterating for i in &v { println!("{}", i); } let mut v1 = vec![10, 20, 30]; for i in &mut v1 { *i += 3; // * is dereference operator } println!("modified v1 is {:?}", v1); } // vector is dropped when it goes out of scope
use core::alloc::Layout; use core::ptr::NonNull; use crate::erts::exception::AllocResult; use crate::erts::process::alloc::*; use crate::erts::term::prelude::*; use super::{Generation, Sweep, Sweepable, Sweeper}; /// Represents a collection algorithm that sweeps for references in `Target` /// into `Source`, and moving them into `Target` pub trait CollectionType: HeapAlloc { type Source: Heap + VirtualAlloc; type Target: Heap + VirtualAlloc; // Obtain immutable reference to underlying source heap fn source(&self) -> &Self::Source; // Obtain mutable reference to underlying source heap fn source_mut(&self) -> &mut Self::Source; // Obtain immutable reference to underlying target heap fn target(&self) -> &Self::Target; // Obtain mutable reference to underlying target heap fn target_mut(&self) -> &mut Self::Target; /// Performs a collection using an instance of this type fn collect(&mut self) -> usize; } /// An implementation of `CollectionType` for full-sweep collections, where /// references in the target to either generation in the old heap, are swept /// into the new heap represented by `target`. It is expected that the root /// set has already been swept into `target` pub struct FullCollection<'a, S, T> where S: GenerationalHeap, T: Heap, { source: &'a mut S, target: &'a mut T, } impl<'a, S, T> FullCollection<'a, S, T> where S: GenerationalHeap, T: Heap + VirtualAlloc, { pub fn new(source: &'a mut S, target: &'a mut T) -> Self { Self { source, target } } } impl<'a, S, T> HeapAlloc for FullCollection<'a, S, T> where S: GenerationalHeap, T: Heap + VirtualAlloc, { #[inline] unsafe fn alloc_layout(&mut self, layout: Layout) -> AllocResult<NonNull<Term>> { self.target.alloc_layout(layout) } } impl<'a, S, T> CollectionType for FullCollection<'a, S, T> where S: GenerationalHeap, T: Heap + VirtualAlloc, { type Source = S; type Target = T; fn source(&self) -> &Self::Source { self.source } fn source_mut(&self) -> &mut Self::Source { unsafe { &mut *(self.source as *const S as *mut S) } } fn target(&self) -> &Self::Target { self.target } fn target_mut(&self) -> &mut Self::Target { unsafe { &mut *(self.target as *const T as *mut T) } } fn collect(&mut self) -> usize { let mut moved = 0; for term in self.target.iter_mut() { moved += unsafe { sweep_term(self, term) }; } moved } } /// An implementation of `CollectionType` for minor collections, where /// references in the young generation of `target` to `source` are swept /// into either the old generation or young generation of `target`, depending /// on object maturity. It is expected that the root set has already been swept /// into the young generation of `target`. pub struct MinorCollection<'a, S, T> where S: Heap, T: GenerationalHeap, { source: &'a mut S, target: &'a mut T, mode: Generation, } impl<'a, S, T> MinorCollection<'a, S, T> where S: Heap + VirtualAlloc, T: GenerationalHeap, { pub fn new(source: &'a mut S, target: &'a mut T) -> Self { Self { source, target, mode: Generation::Young, } } /// Determine the generation to move the given pointer to /// /// If `None`, then no move is required fn get_generation<P: ?Sized>(&self, ptr: *mut P) -> Option<Generation> { use liblumen_core::util::pointer::in_area; // In a minor collection, we move mature objects into the old generation, // otherwise they are moved into the young generation. Objects already in // the young/old generation do not need to be moved if self.target.contains(ptr) { return None; } // Checking maturity to select destination if in_area(ptr, self.source.heap_start(), self.source.high_water_mark()) { return Some(Generation::Old); } // If the object isn't in the mature region, and isn't in the target, then // it must be moved into the young generation Some(Generation::Young) } } impl<'a, S, T> HeapAlloc for MinorCollection<'a, S, T> where S: Heap + VirtualAlloc, T: GenerationalHeap, { #[inline] unsafe fn alloc_layout(&mut self, layout: Layout) -> AllocResult<NonNull<Term>> { match self.mode { Generation::Young => self.target.young_generation_mut().alloc_layout(layout), Generation::Old => self.target.old_generation_mut().alloc_layout(layout), } } } impl<'a, S, T> CollectionType for MinorCollection<'a, S, T> where S: Heap + VirtualAlloc, T: GenerationalHeap, { type Source = S; type Target = T; fn source(&self) -> &Self::Source { self.source } fn source_mut(&self) -> &mut Self::Source { unsafe { &mut *(self.source as *const S as *mut S) } } fn target(&self) -> &Self::Target { self.target } fn target_mut(&self) -> &mut Self::Target { unsafe { &mut *(self.target as *const T as *mut T) } } fn collect(&mut self) -> usize { let mut moved = 0; let young = self.target.young_generation_mut(); for term in young.iter_mut() { moved += unsafe { sweep_term(self, term) }; } moved } } impl<'a, S, T> Sweeper for MinorCollection<'a, S, T> where S: Heap + VirtualAlloc, T: GenerationalHeap, { /// To avoid a redundant check, we always return true here, /// and then use our opportunity to check based on generation /// in the implementation of `sweep` #[inline(always)] fn should_sweep(&self, _raw: *mut Term) -> bool { true } } unsafe impl<'a, S, T, P> Sweep<P> for MinorCollection<'a, S, T> where S: Heap + VirtualAlloc, T: GenerationalHeap, P: Sweepable<Self>, { #[inline] unsafe fn sweep(&mut self, ptr: P) -> Option<(*mut Term, usize)> { match self.get_generation(ptr.into()) { Some(mode) => { let prev_mode = self.mode; self.mode = mode; let result = P::sweep(ptr, self); self.mode = prev_mode; Some(result) } None => None, } } } /// Collect all references from `Target` into `Source` by moving the /// referenced values into `Target`. This is essentially a full collection, /// but more general as it doesn't assume that the source is a generational /// heap pub struct ReferenceCollection<'a, S, T> { source: &'a mut S, target: &'a mut T, } impl<'a, S, T> ReferenceCollection<'a, S, T> where S: Heap + VirtualAlloc, T: Heap + VirtualAlloc, { pub fn new(source: &'a mut S, target: &'a mut T) -> Self { Self { source, target } } } impl<'a, S, T> HeapAlloc for ReferenceCollection<'a, S, T> where S: Heap + VirtualAlloc, T: Heap + VirtualAlloc, { #[inline] unsafe fn alloc_layout(&mut self, layout: Layout) -> AllocResult<NonNull<Term>> { self.target.alloc_layout(layout) } } impl<'a, S, T> CollectionType for ReferenceCollection<'a, S, T> where S: Heap + VirtualAlloc, T: Heap + VirtualAlloc, { type Source = S; type Target = T; fn source(&self) -> &Self::Source { self.source } fn source_mut(&self) -> &mut Self::Source { unsafe { &mut *(self.source as *const S as *mut S) } } fn target(&self) -> &Self::Target { self.target } fn target_mut(&self) -> &mut Self::Target { unsafe { &mut *(self.target as *const T as *mut T) } } fn collect(&mut self) -> usize { let mut moved = 0; for term in self.target.iter_mut() { moved += unsafe { sweep_term(self, term) }; } moved } } // This function contains the sweeping logic applied to terms in // the root set. These are different than the terms swept by `sweep_term` // in that they can be pointers to pointers, so we need to sweep the inner // term and also update the root itself in those cases. // // Internally this delegates to `sweep_term` to do the sweep of the inner value pub(super) unsafe fn sweep_root<G>(sweeper: &mut G, term: &mut Term) -> usize where G: Sweeper + Sweep<*mut Term> + Sweep<Boxed<ProcBin>> + Sweep<Boxed<SubBinary>> + Sweep<Boxed<MatchContext>> + Sweep<Boxed<Cons>>, { let pos = term as *mut Term; // We're sweeping roots, these should all be pointers debug_assert!(term.is_boxed() || term.is_non_empty_list()); if term.is_boxed() { let term_ptr: *mut Term = term.dyn_cast(); let inner_term = &mut *term_ptr; // If this is a pointer to a pointer, delegate to sweep_term, // then update the original root pointer if inner_term.is_boxed() { let moved = sweep_term(sweeper, inner_term); // Fetch forwarding address from marker let new_term = *term_ptr; debug_assert!(new_term.is_boxed()); // Update root pos.write(new_term); moved } else if inner_term.is_non_empty_list() { let moved = sweep_term(sweeper, inner_term); // Fetch forwarding address from marker let marker = &*(term_ptr as *mut Cons); let new_term = marker.tail; debug_assert!(new_term.is_non_empty_list()); // Update root pos.write(new_term); moved } else { assert!(inner_term.is_header()); // This is just a pointer, not a pointer to a pointer, // so sweep it normally sweep_term(sweeper, term) } } else { assert!( term.is_non_empty_list(), "Term ({:?}) is not a non-empty list", term ); // This is just a list pointer, not a pointer to a list pointer, // so sweep it normally sweep_term(sweeper, term) } } // This function contains the generic default sweeping logic applied against // a given term on the heap, using the provided context to execute any // required moves. // // This is invoked by collectors/collection types to kick off the sweep of // a single term. Once the type of the term is determined, type-specific sweeps // are handled by implementations of the `Sweepable` trait. pub(super) unsafe fn sweep_term<G>(sweeper: &mut G, term: &mut Term) -> usize where G: Sweeper + Sweep<*mut Term> + Sweep<Boxed<ProcBin>> + Sweep<Boxed<SubBinary>> + Sweep<Boxed<MatchContext>> + Sweep<Boxed<Cons>>, { let pos = term as *mut Term; if term.is_boxed() { // Skip pointers to literals if term.is_literal() { return 0; } // Check if this is a move marker let box_ptr: *mut Term = (*pos).dyn_cast(); let unboxed = &*box_ptr; if unboxed.is_boxed() { // Overwrite the move marker with the forwarding address pos.write(*unboxed); return 0; } assert!(unboxed.is_header()); if unboxed.is_procbin() { let bin: Boxed<ProcBin> = Boxed::new_unchecked(box_ptr as *mut ProcBin); if let Some((new_ptr, moved)) = sweeper.sweep(bin) { // Write marker let marker: Term = new_ptr.into(); pos.write(marker); return moved; } return 0; } if unboxed.is_subbinary() { let bin: Boxed<SubBinary> = Boxed::new_unchecked(box_ptr as *mut SubBinary); if let Some((new_ptr, moved)) = sweeper.sweep(bin) { // Write marker let marker: Term = new_ptr.into(); pos.write(marker); return moved; } return 0; } if let Some((new_ptr, moved)) = sweeper.sweep(box_ptr) { let marker: Term = new_ptr.into(); pos.write(marker); return moved; } return 0; } if term.is_non_empty_list() { // Skip pointers to literals if term.is_literal() { return 0; } // Check if this is a move marker let ptr: Boxed<Cons> = (*pos).dyn_cast(); let cons = ptr.as_ref(); if cons.is_move_marker() { // Overwrite the move marker with the forwarding address pos.write(cons.tail); return 0; } // Move the pointed-to value if let Some((new_ptr, moved)) = sweeper.sweep(ptr) { // For cons cells only, we need to make sure we encode the pointer as a list type let marker: Term = (new_ptr as *mut Cons).into(); pos.write(marker); return moved; } return 0; } // When we encounter a header for a match context, check if we should also move its referenced // binary if term.is_match_context() { let bin: Boxed<MatchContext> = Boxed::new_unchecked(pos as *mut MatchContext); if let Some((new_ptr, moved)) = sweeper.sweep(bin) { let marker: Term = new_ptr.into(); pos.write(marker); return moved; } return 0; } // For all other headers, perform a simple move if let Some((new_ptr, moved)) = sweeper.sweep(pos) { let marker: Term = new_ptr.into(); pos.write(marker); return moved; } return 0; }
use crate::{ResourceVersion, Tags, ViewPath}; use serde::{Deserialize, Serialize}; use smart_default::SmartDefault; #[derive(Debug, Serialize, Deserialize, SmartDefault, PartialEq, Clone)] #[serde(rename_all = "camelCase")] pub struct Script { /// Is this used in DragNDrop? Hopefully not! that would get messy. pub is_dn_d: bool, /// Is this an autogenerated compatibility script? pub is_compatibility: bool, /// The parent in the Gms2 virtual file system, ie. the parent which /// a user would see in the Navigation Pane in Gms2. This has no /// relationship to the actual operating system's filesystem. pub parent: ViewPath, /// The resource version of this yy file. At default 1.0. pub resource_version: ResourceVersion, /// The name of the object. This is the human readable name used in the IDE. pub name: String, /// The tags given to the object. pub tags: Tags, /// Const id tag of the object, given by Gms2. pub resource_type: ConstGmScript, } #[derive(Debug, Copy, Serialize, Deserialize, SmartDefault, PartialEq, Eq, Clone)] pub enum ConstGmScript { #[serde(rename = "GMScript")] #[default] Const, } #[cfg(test)] mod tests { use super::*; use crate::{utils::TrailingCommaUtility, ViewPathLocation}; use include_dir::{include_dir, Dir, DirEntry}; use pretty_assertions::assert_eq; #[test] fn trivial_sprite_parsing() { let all_objects: Dir = include_dir!("data/scripts"); let tcu = TrailingCommaUtility::new(); for object_file in all_objects.find("**/*.yy").unwrap() { if let DirEntry::File(file) = object_file { println!("parsing {}", file.path); let our_str = std::str::from_utf8(file.contents()).unwrap(); let our_str = tcu.clear_trailing_comma(our_str); serde_json::from_str::<Script>(&our_str).unwrap(); } } } #[test] fn deep_equality() { let script_raw = include_str!("../../data/scripts/CameraClass.yy"); let script_parsed: Script = serde_json::from_str(&TrailingCommaUtility::clear_trailing_comma_once(script_raw)) .unwrap(); let script = Script { is_dn_d: false, is_compatibility: false, parent: ViewPath { name: "Camera".to_string(), path: ViewPathLocation("folders/Scripts/Gameplay Systems/Camera.yy".to_string()), }, resource_version: ResourceVersion::default(), name: "CameraClass".to_string(), tags: vec![], resource_type: ConstGmScript::Const, }; assert_eq!(script_parsed, script); } }
use cosmwasm_std::StdError; use thiserror::Error; #[derive(Error, Debug)] pub enum ContractError { #[error("{0}")] Std(#[from] StdError), #[error("not enough deposit")] NotEnoughDeposit, #[error("wrong deposit coin")] WrongDepositCoin, #[error("plan not exists")] PlanNotExists, #[error("invalid expires")] InvalidExpires, #[error("subscription expired")] SubscriptionExpired, #[error("subscription exists")] SubscriptionExists, #[error("invalid timezone offset")] InvalidTimeZoneOffset, #[error("the sender is not plan owner")] NotPlanOwner, #[error("invalid input coins")] InvalidCoins, #[error("plan title too long")] TitleTooLong, #[error("plan description too long")] DescriptionTooLong, #[error("invalid collection time")] InvalidCollectionTime, }
use std::collections::{HashMap, HashSet, VecDeque}; use proconio::input; fn main() { input! { n: usize, ab: [(usize, usize); n], }; let mut g = HashMap::<usize, Vec<usize>>::new(); g.insert(1, Vec::new()); for (a, b) in ab { g.entry(a).or_insert(Vec::new()).push(b); g.entry(b).or_insert(Vec::new()).push(a); } let mut seen = HashSet::new(); let mut que = VecDeque::new(); seen.insert(1); que.push_back(1); while let Some(cur) = que.pop_front() { for &next in &g[&cur] { if seen.contains(&next) { continue; } seen.insert(next); que.push_back(next); } } let ans = seen.iter().max().copied().unwrap(); println!("{}", ans); }
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test that we can't call random fns in a const fn or do other bad things. #![feature(const_fn)] use std::mem::transmute; fn random() -> u32 { 0 } const fn sub(x: &u32) -> usize { unsafe { transmute(x) } //~ ERROR E0015 } const fn sub1() -> u32 { random() //~ ERROR E0015 } static Y: u32 = 0; const fn get_Y() -> u32 { Y //~^ ERROR E0013 } const fn get_Y_addr() -> &'static u32 { &Y //~^ ERROR E0013 } const fn get() -> u32 { let x = 22; //~^ ERROR let bindings in constant functions are unstable //~| ERROR statements in constant functions are unstable let y = 44; //~^ ERROR let bindings in constant functions are unstable //~| ERROR statements in constant functions are unstable x + y //~^ ERROR let bindings in constant functions are unstable //~| ERROR let bindings in constant functions are unstable } fn main() {}
use std::cmp::Ordering; use std::default::Default; use async_trait::async_trait; use tokio::task::spawn_blocking; use tracing::{debug, info_span, warn, Instrument}; use h3ron::collections::{H3CellSet, HashMap}; use h3ron::iter::change_resolution; use h3ron::{H3Cell, Index}; use h3ron_polars::frame::H3DataFrame; use itertools::join; use polars::prelude::{DataFrame, NamedFrom, Series}; pub use tableset::{Table, TableSet, TableSpec}; use ukis_clickhouse_arrow_grpc::{ArrowInterface, QueryInfo}; pub use crate::clickhouse::compacted_tables::insert::InsertOptions; use crate::clickhouse::compacted_tables::insert::Inserter; use crate::clickhouse::compacted_tables::optimize::deduplicate_full; use crate::clickhouse::compacted_tables::schema::CompactedTableSchema; use crate::clickhouse::compacted_tables::select::BuildCellQueryString; pub use crate::clickhouse::compacted_tables::select::TableSetQuery; use crate::clickhouse::compacted_tables::tableset::{find_tablesets, LoadTableSet}; use crate::Error; mod insert; mod optimize; pub mod schema; mod select; pub mod tableset; pub mod temporary_key; pub mod traversal; /// the column name which must be used for h3indexes. pub const COL_NAME_H3INDEX: &str = "h3index"; pub struct QueryOptions { pub query: TableSetQuery, pub cells: Vec<H3Cell>, pub h3_resolution: u8, pub do_uncompact: bool, } impl QueryOptions { pub fn new(query: TableSetQuery, cells: Vec<H3Cell>, h3_resolution: u8) -> Self { // TODO: make cells an iterator with borrow and normalize to `h3_resolution` Self { query, cells, h3_resolution, do_uncompact: true, } } } #[async_trait] pub trait CompactedTablesStore { async fn list_tablesets<S>( &mut self, database_name: S, ) -> Result<HashMap<String, TableSet>, Error> where S: AsRef<str> + Sync + Send; async fn get_tableset<S1, S2>( &mut self, database_name: S1, tableset_name: S2, ) -> Result<TableSet, Error> where S1: AsRef<str> + Sync + Send, S2: AsRef<str> + Send + Sync, { self.list_tablesets(database_name) .await? .remove(tableset_name.as_ref()) .ok_or_else(|| Error::TableSetNotFound(tableset_name.as_ref().to_string())) } async fn drop_tableset<S, TS>(&mut self, database_name: S, tableset: TS) -> Result<(), Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync; async fn create_tableset<S>( &mut self, database_name: S, schema: &CompactedTableSchema, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send; async fn insert_h3dataframe_into_tableset<S>( &mut self, database_name: S, schema: &CompactedTableSchema, h3df: H3DataFrame<H3Cell>, options: InsertOptions, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send; async fn deduplicate_schema<S>( &mut self, database_name: S, schema: &CompactedTableSchema, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send; async fn query_tableset_cells<S, TS>( &mut self, database_name: S, tableset: TS, query_options: QueryOptions, ) -> Result<H3DataFrame<H3Cell>, Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync; /// get stats about the number of cells and compacted cells in all the /// resolutions of the tableset async fn tableset_stats<S, TS>( &mut self, database_name: S, tableset: TS, ) -> Result<DataFrame, Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync; } #[async_trait] impl<C> CompactedTablesStore for C where C: ArrowInterface + Send + Clone + Sync, { async fn list_tablesets<S>( &mut self, database_name: S, ) -> Result<HashMap<String, TableSet>, Error> where S: AsRef<str> + Sync + Send, { let mut tablesets = { let tableset_df = self .execute_into_dataframe(QueryInfo { query: format!( "select table from system.columns where name = '{}' and database = currentDatabase()", COL_NAME_H3INDEX ), database: database_name.as_ref().to_string(), ..Default::default() }) .await?; let tablenames: Vec<String> = tableset_df .column("table")? .utf8()? .into_iter() .flatten() .map(|table_name| table_name.to_string()) .collect(); find_tablesets(&tablenames) }; // find the columns for the tablesets for (ts_name, ts) in tablesets.iter_mut() { let set_table_names = itertools::join( ts.tables() .iter() .map(|t| format!("'{}'", t.to_table_name())), ", ", ); let columns_df = self .execute_into_dataframe(QueryInfo { query: format!( "select name, type, count(*) as c from system.columns where table in ({}) and database = currentDatabase() and not startsWith(name, '{}') group by name, type", set_table_names, COL_NAME_H3INDEX ), database: database_name.as_ref().to_string(), ..Default::default() }) .await?; for ((column_name, table_count_with_column), column_type) in columns_df .column("name")? .utf8()? .into_iter() .zip(columns_df.column("c")?.u64()?.into_iter()) .zip(columns_df.column("type")?.utf8()?.into_iter()) { if let (Some(column_name), Some(table_count_with_column), Some(column_type)) = (column_name, table_count_with_column, column_type) { // column must be present in all tables of the set, or it is not usable if table_count_with_column == ts.num_tables() as u64 { ts.columns .insert(column_name.to_string(), column_type.to_string()); } else { warn!("column {} is not present using the same type in all tables of set {}. ignoring this column", column_name, ts_name); } } } } Ok(tablesets) } async fn drop_tableset<S, TS>(&mut self, database_name: S, tableset: TS) -> Result<(), Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync, { return match tableset .load_tableset_from_store(self, database_name.as_ref()) .await { Ok(tableset) => { for table in tableset .base_tables() .iter() .chain(tableset.compacted_tables().iter()) { self.execute_query_checked(QueryInfo { query: format!("drop table if exists {}", table.to_table_name()), database: database_name.as_ref().to_string(), ..Default::default() }) .await?; } Ok(()) } Err(e) => match e { Error::TableSetNotFound(_) => Ok(()), _ => Err(e), }, }; } async fn create_tableset<S>( &mut self, database_name: S, schema: &CompactedTableSchema, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send, { for stmt in schema.build_create_statements(&None)? { self.execute_query_checked(QueryInfo { query: stmt, database: database_name.as_ref().to_string(), ..Default::default() }) .await?; } Ok(()) } async fn insert_h3dataframe_into_tableset<S>( &mut self, database_name: S, schema: &CompactedTableSchema, h3df: H3DataFrame<H3Cell>, options: InsertOptions, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send, { if h3df.dataframe().is_empty() { return Ok(()); } let h3df_shape = h3df.dataframe().shape(); let mut inserter = Inserter::new( self.clone(), schema.clone(), database_name.as_ref().to_string(), options, ); let insert_result = inserter .insert(h3df) .instrument(info_span!( "Inserting CellFrame into tableset", num_rows = h3df_shape.0, num_cols = h3df_shape.1, schema = schema.name.as_str(), )) .await; // always attempt to cleanup regardless if how the insert went let finish_result = inserter .finish() .instrument(info_span!( "Finishing CellFrame inserter", num_rows = h3df_shape.0, num_cols = h3df_shape.1, schema = schema.name.as_str(), )) .await; // return the earliest-occurred error if insert_result.is_err() { insert_result } else { finish_result } } async fn deduplicate_schema<S>( &mut self, database_name: S, schema: &CompactedTableSchema, ) -> Result<(), Error> where S: AsRef<str> + Sync + Send, { let resolution_metadata = schema.get_resolution_metadata()?; deduplicate_full(self, database_name, schema, &resolution_metadata) .instrument(info_span!( "De-duplicating complete schema", schema = schema.name.as_str() )) .await } async fn query_tableset_cells<S, TS>( &mut self, database_name: S, tableset: TS, query_options: QueryOptions, ) -> Result<H3DataFrame<H3Cell>, Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync, { let tableset = tableset .load_tableset_from_store(self, database_name.as_ref()) .await?; let (query_string, cells) = spawn_blocking(move || { query_options .query .build_cell_query_string( &tableset, query_options.h3_resolution, &query_options.cells, ) .map(|query_string| (query_string, query_options.cells)) }) .await??; let df = self .execute_into_dataframe(QueryInfo { query: query_string, database: database_name.as_ref().to_string(), ..Default::default() }) .await?; let h3df = H3DataFrame::from_dataframe(df, COL_NAME_H3INDEX)?; let out_h3df = if query_options.do_uncompact { debug!( "Un-compacting queried H3DataFrame to target_resolution {}", query_options.h3_resolution ); spawn_blocking(move || uncompact(h3df, cells, query_options.h3_resolution)).await?? } else { debug!("returning queried H3DataFrame without un-compaction"); h3df }; Ok(out_h3df) } async fn tableset_stats<S, TS>( &mut self, database_name: S, tableset: TS, ) -> Result<DataFrame, Error> where S: AsRef<str> + Send + Sync, TS: LoadTableSet + Send + Sync, { let tableset = tableset .load_tableset_from_store(self, database_name.as_ref()) .await?; let compacted_counts = { let df = self .execute_into_dataframe(compacted_counts_stmt(&tableset, database_name.as_ref())) .await?; let cc: Vec<_> = df .column("r")? .u8()? .into_iter() .zip(df.column("num_cells_stored_compacted")?.u64()?.into_iter()) .map(|(r, count)| (r.unwrap(), count.unwrap())) .collect(); cc }; let mut df = self .execute_into_dataframe(uncompacted_counts_stmt(&tableset, database_name.as_ref())) .await?; let mut num_cells_stored_compacted = Vec::with_capacity(df.shape().0); let mut num_cells = Vec::with_capacity(df.shape().0); let mut num_cells_stored_at_resolution = Vec::with_capacity(df.shape().0); for (r, n_uncompacted) in df.column("resolution")?.u8()?.into_iter().zip( df.column("num_cells_stored_at_resolution")? .u64()? .into_iter(), ) { let r = r.unwrap(); let n_uncompacted = n_uncompacted.unwrap(); let mut n_stored_compacted = 0u64; let mut n_cells_at_resolution = n_uncompacted; let mut n_cells = n_uncompacted; for (r_c, c_c) in compacted_counts.iter() { match r_c.cmp(&r) { Ordering::Less => { n_stored_compacted += c_c; n_cells += c_c * 7u64.pow((r - r_c) as u32); } Ordering::Equal => { n_cells_at_resolution += c_c; n_cells += c_c; } Ordering::Greater => (), } } num_cells_stored_compacted.push(n_stored_compacted); num_cells.push(n_cells); num_cells_stored_at_resolution.push(n_cells_at_resolution); } df.with_column(Series::new( "num_cells_stored_compacted", num_cells_stored_compacted, ))?; df.with_column(Series::new("num_cells", num_cells))?; df.with_column(Series::new( "num_cells_stored_at_resolution", num_cells_stored_at_resolution, ))?; df.sort_in_place(["resolution"], vec![false])?; Ok(df) } } fn uncompact( h3df: H3DataFrame<H3Cell>, cell_subset: Vec<H3Cell>, target_resolution: u8, ) -> Result<H3DataFrame<H3Cell>, Error> { // use restricted uncompacting to filter by input cells so we // avoid over-fetching in case of large, compacted cells. let cells: H3CellSet = change_resolution( cell_subset .into_iter() .filter(|c| c.resolution() <= target_resolution), target_resolution, ) .filter_map(|c| c.ok()) .collect(); h3df.h3_uncompact_dataframe_subset(target_resolution, &cells) .map_err(Error::from) } fn compacted_counts_stmt(ts: &TableSet, database_name: &str) -> QueryInfo { let query = join( ts.compacted_tables().into_iter().map(|table| { format!( "select cast({} as UInt8) as r, count(*) as num_cells_stored_compacted from {}", table.spec.h3_resolution, table.to_table_name() ) }), " union all ", ); QueryInfo { query, database: database_name.to_string(), ..Default::default() } } fn uncompacted_counts_stmt(ts: &TableSet, database_name: &str) -> QueryInfo { let query = join( ts.base_tables().into_iter().map(|table| { format!( "select cast({} as UInt8) as resolution, count(*) as num_cells_stored_at_resolution from {}", table.spec.h3_resolution, table.to_table_name() ) }), " union all ", ); QueryInfo { query, database: database_name.to_string(), ..Default::default() } }
pub use source::*; pub mod kbstat; mod mousestat; mod source;
//! The `Style` type is a simplified view of the various //! attributes offered by the `term` library. These are //! enumerated as bits so they can be easily or'd together //! etc. use std::default::Default; use term::{self, Terminal}; #[derive(Copy, Clone, Default, PartialEq, Eq)] pub struct Style { bits: u64, } macro_rules! declare_styles { ($($style:ident,)*) => { #[derive(Copy, Clone)] #[allow(non_camel_case_types)] enum StyleBit { $($style,)* } $( pub const $style: Style = Style { bits: 1 << (StyleBit::$style as u64) }; )* } } pub const DEFAULT: Style = Style { bits: 0 }; declare_styles! { // Foreground colors: FG_BLACK, FG_BLUE, FG_BRIGHT_BLACK, FG_BRIGHT_BLUE, FG_BRIGHT_CYAN, FG_BRIGHT_GREEN, FG_BRIGHT_MAGENTA, FG_BRIGHT_RED, FG_BRIGHT_WHITE, FG_BRIGHT_YELLOW, FG_CYAN, FG_GREEN, FG_MAGENTA, FG_RED, FG_WHITE, FG_YELLOW, // Background colors: BG_BLACK, BG_BLUE, BG_BRIGHT_BLACK, BG_BRIGHT_BLUE, BG_BRIGHT_CYAN, BG_BRIGHT_GREEN, BG_BRIGHT_MAGENTA, BG_BRIGHT_RED, BG_BRIGHT_WHITE, BG_BRIGHT_YELLOW, BG_CYAN, BG_GREEN, BG_MAGENTA, BG_RED, BG_WHITE, BG_YELLOW, // Other: BOLD, DIM, ITALIC, UNDERLINE, BLINK, STANDOUT, REVERSE, SECURE, } impl Style { pub fn new() -> Style { Style::default() } pub fn with(self, other_style: Style) -> Style { Style { bits: self.bits | other_style.bits, } } pub fn contains(self, other_style: Style) -> bool { self.with(other_style) == self } /// Attempts to apply the given style to the given terminal. If /// the style is not supported, either there is no effect or else /// a similar, substitute style may be applied. pub fn apply<T: Terminal + ?Sized>(self, term: &mut T) -> term::Result<()> { term.reset()?; macro_rules! fg_color { ($color:expr, $term_color:ident) => { if self.contains($color) { if term.supports_color() { term.fg(term::color::$term_color)?; } } }; } fg_color!(FG_BLACK, BLACK); fg_color!(FG_BLUE, BLUE); fg_color!(FG_BRIGHT_BLACK, BRIGHT_BLACK); fg_color!(FG_BRIGHT_BLUE, BRIGHT_BLUE); fg_color!(FG_BRIGHT_CYAN, BRIGHT_CYAN); fg_color!(FG_BRIGHT_GREEN, BRIGHT_GREEN); fg_color!(FG_BRIGHT_MAGENTA, BRIGHT_MAGENTA); fg_color!(FG_BRIGHT_RED, BRIGHT_RED); fg_color!(FG_BRIGHT_WHITE, BRIGHT_WHITE); fg_color!(FG_BRIGHT_YELLOW, BRIGHT_YELLOW); fg_color!(FG_CYAN, CYAN); fg_color!(FG_GREEN, GREEN); fg_color!(FG_MAGENTA, MAGENTA); fg_color!(FG_RED, RED); fg_color!(FG_WHITE, WHITE); fg_color!(FG_YELLOW, YELLOW); macro_rules! bg_color { ($color:expr, $term_color:ident) => { if self.contains($color) { if term.supports_color() { term.bg(term::color::$term_color)?; } } }; } bg_color!(BG_BLACK, BLACK); bg_color!(BG_BLUE, BLUE); bg_color!(BG_BRIGHT_BLACK, BRIGHT_BLACK); bg_color!(BG_BRIGHT_BLUE, BRIGHT_BLUE); bg_color!(BG_BRIGHT_CYAN, BRIGHT_CYAN); bg_color!(BG_BRIGHT_GREEN, BRIGHT_GREEN); bg_color!(BG_BRIGHT_MAGENTA, BRIGHT_MAGENTA); bg_color!(BG_BRIGHT_RED, BRIGHT_RED); bg_color!(BG_BRIGHT_WHITE, BRIGHT_WHITE); bg_color!(BG_BRIGHT_YELLOW, BRIGHT_YELLOW); bg_color!(BG_CYAN, CYAN); bg_color!(BG_GREEN, GREEN); bg_color!(BG_MAGENTA, MAGENTA); bg_color!(BG_RED, RED); bg_color!(BG_WHITE, WHITE); bg_color!(BG_YELLOW, YELLOW); macro_rules! attr { ($attr:expr, $term_attr:expr) => { if self.contains($attr) { let attr = $term_attr; if term.supports_attr(attr) { term.attr(attr)?; } } }; } attr!(BOLD, term::Attr::Bold); attr!(DIM, term::Attr::Dim); attr!(ITALIC, term::Attr::Italic(true)); attr!(UNDERLINE, term::Attr::Underline(true)); attr!(BLINK, term::Attr::Blink); attr!(STANDOUT, term::Attr::Standout(true)); attr!(REVERSE, term::Attr::Reverse); attr!(SECURE, term::Attr::Secure); Ok(()) } } /////////////////////////////////////////////////////////////////////////// pub struct StyleCursor<'term, T: ?Sized + Terminal> { current_style: Style, term: &'term mut T, } impl<'term, T: ?Sized + Terminal> StyleCursor<'term, T> { pub fn new(term: &'term mut T) -> term::Result<StyleCursor<'term, T>> { let current_style = Style::default(); current_style.apply(term)?; Ok(StyleCursor { current_style: current_style, term: term, }) } pub fn term(&mut self) -> &mut T { self.term } pub fn set_style(&mut self, style: Style) -> term::Result<()> { if style != self.current_style { style.apply(self.term)?; self.current_style = style; } Ok(()) } }
use ifs::{Eqn, IFS}; use imgui::{ImGui, ImGuiCond, Ui}; /// State controllable by GUI /// /// Internally represents the IFS as an IFS struct but with all values scaled /// by 100 because ImGui slider_float's can't have a step specified yet #[derive(Debug, Clone)] pub struct State { pub sys: IFS, pub num_points: f32, pub fps: f32, } impl Default for State { fn default() -> State { State { sys: IFS::new(vec![ Eqn { a: 85.0, b: 4.0, c: -4.0, d: 85.0, e: 0.0, f: 160.0, p: 85.0, }, Eqn { a: 0.0, b: 0.0, c: 0.0, d: 16.0, e: 0.0, f: 0.0, p: 1.0, }, Eqn { a: 20.0, b: -26.0, c: 23.0, d: 22.0, e: 0.0, f: 160.0, p: 7.0, }, Eqn { a: -15.0, b: 28.0, c: 26.0, d: 24.0, e: 0.0, f: 44.0, p: 7.0, }, ]), num_points: 1_000_000.0, fps: 0.0, } } } impl State { pub fn get_sys(&self) -> IFS { IFS::new(self.sys.eqns.iter().map(|e| norm(*e)).collect()) } } fn norm(e: Eqn) -> Eqn { Eqn { a: e.a / 100.0, b: e.b / 100.0, c: e.c / 100.0, d: e.d / 100.0, e: e.e / 100.0, f: e.f / 100.0, ..e } } /// Helper to draw a Eqn's sliders fn ui_eqn<'a>(ui: &Ui<'a>, eqn: &mut Eqn, id: usize) { ui.slider_float(im_str!("{}a", id), &mut eqn.a, -100.0, 100.0) .display_format(im_str!("a: %.0f")) .build(); ui.slider_float(im_str!("{}b", id), &mut eqn.b, -100.0, 100.0) .display_format(im_str!("b: %.0f")) .build(); ui.slider_float(im_str!("{}c", id), &mut eqn.c, -100.0, 100.0) .display_format(im_str!("c: %.0f")) .build(); ui.slider_float(im_str!("{}d", id), &mut eqn.d, -100.0, 100.0) .display_format(im_str!("d: %.0f")) .build(); ui.slider_float(im_str!("{}e", id), &mut eqn.e, -100.0, 100.0) .display_format(im_str!("e: %.0f")) .build(); ui.slider_float(im_str!("{}f", id), &mut eqn.f, -100.0, 100.0) .display_format(im_str!("f: %.0f")) .build(); ui.slider_float(im_str!("{}p", id), &mut eqn.p, 1.0, 100.0) .display_format(im_str!("%.0f")) .build(); } /// Main GUI draw function pub fn draw_gui<'a>(ui: &Ui<'a>, state: &mut State) { ui.window(im_str!("Equation Parameters")) .size((300.0, 500.0), ImGuiCond::FirstUseEver) .build(|| { ui.text(im_str!("x = a * x + b * y + e")); ui.text(im_str!("y = c * x + d * y + f")); ui.slider_float( im_str!("NumPoints"), &mut state.num_points, 0.0, 10_000_000.0, ) .power(10.0) .display_format(im_str!("a: %.0f")) .build(); ui.text(im_str!("FPS: {:.1}", state.fps)); ui.separator(); if ui.small_button(im_str!("Add Equation")) { state.sys.eqns.push(Eqn::default()); } let mut del = None; for (i, mut eq) in state.sys.eqns.iter_mut().enumerate() { if ui.collapsing_header(im_str!("Eqn {}", i)).build() { ui_eqn(ui, &mut eq, i); if ui.small_button(im_str!("Delete##eqn{}", i)) { del = Some(i); break; } } } if let Some(i) = del { state.sys.eqns.remove(i); } }); } /// Keeps track of mouse position for ImGui /// Coordinates are in LogicalPosition so we don't have to deal with hidpi #[derive(Copy, Clone, PartialEq, Debug, Default)] pub struct MouseState { pub pos: (f32, f32), pub pressed: (bool, bool, bool), pub wheel: f32, } impl MouseState { /// Sets ImGui's mouse state to match the MouseState struct pub fn update_imgui(&mut self, imgui: &mut ImGui) { imgui.set_mouse_pos(self.pos.0, self.pos.1); imgui.set_mouse_down([self.pressed.0, self.pressed.1, self.pressed.2, false, false]); imgui.set_mouse_wheel(self.wheel); self.wheel = 0.0; } }
pub mod compile; pub mod golang; pub mod rust;
use std::fs::File; use std::io::Read; use std::collections::HashSet; fn play(path: &str, players: usize) -> usize { let mut active = 0; let mut xs: Vec<i32> = vec![0; players]; let mut ys: Vec<i32> = vec![0; players]; let mut seen: HashSet<(i32, i32)> = HashSet::new(); seen.insert((0, 0)); for p in path.chars() { xs[active] += match p { '<' => -1, '>' => 1, _ => 0, }; ys[active] += match p { '^' => 1, 'v' => -1, _ => 0, }; seen.insert((xs[active], ys[active])); active = (active + 1) % players; } seen.len() } fn main() { let mut f = File::open("inputs/day03.in").unwrap(); let mut contents = String::new(); f.read_to_string(&mut contents).unwrap(); let contents = contents.trim(); println!("{}", play(contents, 1)); println!("{}", play(contents, 2)); }
#![feature(plugin)] #![feature(custom_derive)] #![feature(extern_prelude)] #![plugin(rocket_codegen)] extern crate dotenv; extern crate rocket; extern crate regex; #[macro_use] extern crate mysql; extern crate rand; use rocket::fairing; use rocket::response::{Redirect,status}; use rand::{Rng}; mod db; mod documents; #[get("/")] fn index()->&'static str{ "Welcome to use URL Shortener! GitHub: https://github.com/moesoha/url-shortener" } #[get("/<short_token>")] fn short_token(mut conn:db::DbConn,short_token:String)->Result<Redirect,status::NotFound<String>>{ match documents::find_token(&mut *conn,&short_token){ Option::Some(token_result)=>{ Result::Ok(Redirect::to(&token_result.target.unwrap())) }, Option::None=>{ Result::Err(status::NotFound(format!("No such short token `{}`, please check the URL.",short_token).to_string())) } } } #[derive(FromForm,Debug)] struct NewShortTokenBody{ token: Option<String>, url: String } static TOKEN_STRING:[char;48]=['a','A','b','B','c','D','d','e','E','f','F','G','g','H','h','i','J','j','K','k','L','M','m','N','n','p','Q','q','R','r','s','t','T','u','v','w','x','y','Y','z','2','3','4','5','6','7','8','9']; const TOKEN_DEFAULT_LENGTH:i32=7; #[put("/",data="<thebody>")] /* PUT / url=https://sohaj.in&token=sohajin Params in body: url Redirect to there token (Optional) custom short token */ fn new_token(mut conn:db::DbConn,thebody:rocket::request::Form<NewShortTokenBody>)->Result<String,status::BadRequest<String>>{ let body=thebody.get(); let mut rng=rand::thread_rng(); let new_token_doc=documents::ShortToken{ token: match body.token.clone(){ Some(token)=>{ if token.len()<(TOKEN_DEFAULT_LENGTH as usize){ return Result::Err(status::BadRequest(Some("Custom token too short!".to_string()))); } match documents::find_token(&mut *conn,&token){ Some(_)=>{ return Result::Err(status::BadRequest(Some("Custom token has already been registered!".to_string()))); }, None=>Some(token) } }, None=>{ let mut gen_ok=false; let mut tkn=String::new(); while !gen_ok{ for _ in 0..TOKEN_DEFAULT_LENGTH{ tkn.push(*rng.choose(&TOKEN_STRING).unwrap()); } match documents::find_token(&mut *conn,&tkn){ Some(_)=>{ tkn=String::new() }, None=>{ gen_ok=true; } } } Some(tkn) } }, target: Some(body.url.clone()) }; conn.prep_exec("INSERT INTO `short_token` (`token`,`target`) VALUES (:token,:target)",params!{ "token"=>&new_token_doc.token, "target"=>&new_token_doc.target }).unwrap(); Result::Ok(new_token_doc.token.unwrap()) } fn main(){ rocket::ignite() .manage(db::connect()) .attach(fairing::AdHoc::on_response(|_,res|{ res.set_raw_header("X-Powered-By","url-shortener/0.1"); res.set_raw_header("X-Developed-By","Tianhai_IT/tianhai.info Soha_Jin/sohaj.in"); res.set_raw_header("X-Git-Repo","https://github.com/moesoha/url-shortener"); })) .mount("/",routes![ index, short_token, new_token ]) .launch(); }
//! Parsing BER-encoded data. //! //! This modules provides the means to parse BER-encoded data. //! //! The basic idea is that for each type a function exists that knows how //! to decode one value of that type. For constructed types, this function //! in turn relies on similar functions provided for its consituent types. //! For a detailed introduction to how to write these functions, please //! refer to the [decode section of the guide]. //! //! The two most important types of this module are [`Primitive`] and //! [`Constructed`], representing the content octets of a value in primitive //! and constructed encoding, respectively. Each provides a number of methods //! allowing to parse the content. //! //! You will never create a value of either type. Rather, you get handed a //! reference to one as an argument to a closure or function argument to be //! provided to these methods. //! //! The enum [`Content`] is used for cases where a value can be either //! primitive or constructed such as most string types. //! //! Decoding is jumpstarted by providing a data source to parse data from. //! This is any value that implements the [`Source`] trait. //! //! [decode section of the guide]: ../guide/decode/index.html //! [`Primitive`]: struct.Primitive.html //! [`Constructed`]: struct.Constructed.html //! [`Content`]: enum.Content.html //! [`Source`]: trait.Source.html pub use self::content::{Content, Constructed, Primitive}; pub use self::error::Error; pub use self::error::Error::{Malformed, Unimplemented}; pub use self::source::{CaptureSource, LimitedSource, Source}; mod content; mod error; mod source;
use std::fmt::Debug; use std::io; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; use std::pin::Pin; use std::task::{Context, Poll}; /// A UDP socket. pub trait UdpSocket: Debug + Send + Sync { /// Returns the local address that this listener is bound to. /// /// This can be useful, for example, when binding to port 0 to figure out /// which port was actually bound. fn local_addr(&self) -> io::Result<SocketAddr>; /// Sends data on the IO interface to the specified target. /// /// On success, returns the number of bytes written. fn poll_send_to( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], receiver: &SocketAddr, ) -> Poll<io::Result<usize>>; /// Receives data from the IO interface. /// /// On success, returns the number of bytes read and the target from whence /// the data came. fn poll_recv_from( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<io::Result<(usize, SocketAddr)>>; /// Gets the value of the `SO_BROADCAST` option for this socket. fn broadcast(&self) -> io::Result<bool>; /// Sets the value of the `SO_BROADCAST` option for this socket. fn set_broadcast(&self, on: bool) -> io::Result<()>; /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. fn multicast_loop_v4(&self) -> io::Result<bool>; /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. fn set_multicast_loop_v4(&self, on: bool) -> io::Result<()>; /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. fn multicast_ttl_v4(&self) -> io::Result<u32>; /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. fn set_multicast_ttl_v4(&self, ttl: u32) -> io::Result<()>; /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. fn multicast_loop_v6(&self) -> io::Result<bool>; /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. fn set_multicast_loop_v6(&self, on: bool) -> io::Result<()>; /// Gets the value of the `IP_TTL` option for this socket. fn ttl(&self) -> io::Result<u32>; /// Sets the value for the `IP_TTL` option on this socket. fn set_ttl(&self, ttl: u32) -> io::Result<()>; /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>; /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>; /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()>; /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()>; /// Extracts the raw file descriptor. #[cfg(unix)] fn as_raw_fd(&self) -> std::os::unix::io::RawFd; }
use std::io::{Read, Result as IOResult}; use crate::PrimitiveRead; pub struct StripHeader { pub indices_count: i32, pub index_offset: i32, pub verts_count: i32, pub vert_offset: i32, pub bones_count: i16, pub flags: u8, pub bone_state_changes_count: i32, pub bone_state_change_offset: i32 } impl StripHeader { pub fn read(read: &mut dyn Read) -> IOResult<Self> { let indices_count = read.read_i32()?; let index_offset = read.read_i32()?; let verts_count = read.read_i32()?; let vert_offset = read.read_i32()?; let bones_count = read.read_i16()?; let flags = read.read_u8()?; let bone_state_changes_count = read.read_i32()?; let bone_state_change_offset = read.read_i32()?; Ok(Self { indices_count, index_offset, verts_count, vert_offset, bones_count, flags, bone_state_changes_count, bone_state_change_offset }) } }
#![feature(proc_macro_hygiene, decl_macro)] #[macro_use] extern crate rocket; use rocket::http::Status; use rocket::response::Result; use rocket_json::catchers; #[get("/<status_code>")] fn error<'r>(status_code: u16) -> Result<'r> { Err(Status::raw(status_code)) } fn main() { rocket::ignite() .register(catchers::All()) .mount("/", routes![error]) .launch(); }
use std::sync::atomic::{ AtomicBool, Ordering, }; use std::sync::{ Arc, Condvar, Mutex, MutexGuard, }; use crossbeam_channel::{ unbounded, Sender, }; use instant::Duration; use legion::systems::Builder; use legion::{ Entity, Resources, World, }; use log::trace; use sourcerenderer_core::atomic_refcell::AtomicRefCell; use sourcerenderer_core::graphics::{ Backend, Swapchain, }; use sourcerenderer_core::platform::{ Event, Platform, ThreadHandle, }; use sourcerenderer_core::{ Console, Matrix4, }; use super::ecs::{ DirectionalLightComponent, PointLightComponent, RendererInterface, }; use super::{ LateLatching, StaticRenderableComponent, }; use crate::asset::AssetManager; use crate::input::Input; use crate::renderer::command::RendererCommand; use crate::renderer::RendererInternal; use crate::transform::interpolation::InterpolatedTransform; use crate::ui::UIDrawData; enum RendererImpl<P: Platform> { MultiThreaded(P::ThreadHandle), SingleThreaded(Box<RendererInternal<P>>), Uninitialized, } unsafe impl<P: Platform> Send for RendererImpl<P> {} unsafe impl<P: Platform> Sync for RendererImpl<P> {} pub struct Renderer<P: Platform> { sender: Sender<RendererCommand<P::GraphicsBackend>>, window_event_sender: Sender<Event<P>>, instance: Arc<<P::GraphicsBackend as Backend>::Instance>, device: Arc<<P::GraphicsBackend as Backend>::Device>, queued_frames_counter: Mutex<u32>, surface: Mutex<Arc<<P::GraphicsBackend as Backend>::Surface>>, is_running: AtomicBool, input: Arc<Input>, late_latching: Option<Arc<dyn LateLatching<P::GraphicsBackend>>>, cond_var: Condvar, renderer_impl: AtomicRefCell<RendererImpl<P>>, } impl<P: Platform> Renderer<P> { fn new( sender: Sender<RendererCommand<P::GraphicsBackend>>, window_event_sender: Sender<Event<P>>, instance: &Arc<<P::GraphicsBackend as Backend>::Instance>, device: &Arc<<P::GraphicsBackend as Backend>::Device>, surface: &Arc<<P::GraphicsBackend as Backend>::Surface>, input: &Arc<Input>, late_latching: Option<&Arc<dyn LateLatching<P::GraphicsBackend>>>, ) -> Self { Self { sender, instance: instance.clone(), device: device.clone(), queued_frames_counter: Mutex::new(0), surface: Mutex::new(surface.clone()), is_running: AtomicBool::new(true), window_event_sender, late_latching: late_latching.cloned(), input: input.clone(), cond_var: Condvar::new(), renderer_impl: AtomicRefCell::new(RendererImpl::Uninitialized), } } pub fn run( platform: &P, instance: &Arc<<P::GraphicsBackend as Backend>::Instance>, device: &Arc<<P::GraphicsBackend as Backend>::Device>, swapchain: &Arc<<P::GraphicsBackend as Backend>::Swapchain>, asset_manager: &Arc<AssetManager<P>>, input: &Arc<Input>, late_latching: Option<&Arc<dyn LateLatching<P::GraphicsBackend>>>, console: &Arc<Console>, ) -> Arc<Renderer<P>> { let (sender, receiver) = unbounded::<RendererCommand<P::GraphicsBackend>>(); let (window_event_sender, window_event_receiver) = unbounded(); let renderer = Arc::new(Renderer::new( sender.clone(), window_event_sender, instance, device, swapchain.surface(), input, late_latching, )); let c_device = device.clone(); let c_renderer = renderer.clone(); let c_swapchain = swapchain.clone(); let c_asset_manager = asset_manager.clone(); let c_console = console.clone(); if cfg!(feature = "threading") { let thread_handle = platform.start_thread("RenderThread", move || { trace!("Started renderer thread"); let mut internal = RendererInternal::new( &c_device, &c_swapchain, &c_asset_manager, sender, window_event_receiver, receiver, &c_console, ); loop { if !c_renderer.is_running.load(Ordering::SeqCst) { break; } internal.render(&c_renderer); } c_renderer.is_running.store(false, Ordering::SeqCst); trace!("Stopped renderer thread"); }); let mut thread_handle_guard = renderer.renderer_impl.borrow_mut(); *thread_handle_guard = RendererImpl::MultiThreaded(thread_handle); } else { let internal = RendererInternal::new( &c_device, &c_swapchain, &c_asset_manager, sender, window_event_receiver, receiver, &c_console, ); let mut thread_handle_guard = renderer.renderer_impl.borrow_mut(); *thread_handle_guard = RendererImpl::SingleThreaded(Box::new(internal)); } renderer } pub fn install( self: &Arc<Renderer<P>>, _world: &mut World, _resources: &mut Resources, systems: &mut Builder, ) { crate::renderer::ecs::install::<P, Arc<Renderer<P>>>(systems, self.clone()); } pub(crate) fn change_surface(&self, surface: &Arc<<P::GraphicsBackend as Backend>::Surface>) { let mut surface_guard = self.surface.lock().unwrap(); *surface_guard = surface.clone(); } pub fn surface(&self) -> MutexGuard<Arc<<P::GraphicsBackend as Backend>::Surface>> { self.surface.lock().unwrap() } pub(super) fn dec_queued_frames_counter(&self) { let mut counter_guard = self.queued_frames_counter.lock().unwrap(); *counter_guard -= 1; self.cond_var.notify_all(); } pub(crate) fn instance(&self) -> &Arc<<P::GraphicsBackend as Backend>::Instance> { &self.instance } pub(crate) fn unblock_game_thread(&self) { self.cond_var.notify_all(); } pub fn stop(&self) { trace!("Stopping renderer"); if cfg!(feature = "threading") { let was_running = self.is_running.swap(false, Ordering::SeqCst); if !was_running { return; } let end_frame_res = self.sender.send(RendererCommand::<P::GraphicsBackend>::EndFrame); if end_frame_res.is_err() { log::error!("Render thread crashed."); } let mut renderer_impl = self.renderer_impl.borrow_mut(); if let RendererImpl::Uninitialized = &*renderer_impl { return; } self.unblock_game_thread(); let renderer_impl = std::mem::replace(&mut *renderer_impl, RendererImpl::Uninitialized); match renderer_impl { RendererImpl::MultiThreaded(thread_handle) => { if let Err(e) = thread_handle.join() { log::error!("Renderer thread did not exit cleanly: {:?}", e); } } RendererImpl::Uninitialized => { panic!("Renderer was already stopped."); } _ => {} } } } pub fn dispatch_window_event(&self, event: Event<P>) { self.window_event_sender.send(event).unwrap(); } pub fn late_latching(&self) -> Option<&dyn LateLatching<P::GraphicsBackend>> { self.late_latching.as_ref().map(|l| l.as_ref()) } pub fn input(&self) -> &Input { &self.input } pub fn device(&self) -> &Arc<<P::GraphicsBackend as Backend>::Device> { &self.device } pub fn render(&self) { let mut renderer_impl = self.renderer_impl.borrow_mut(); if let RendererImpl::SingleThreaded(renderer) = &mut *renderer_impl { renderer.render(self); } } } impl<P: Platform> RendererInterface<P> for Arc<Renderer<P>> { fn register_static_renderable( &self, entity: Entity, transform: &InterpolatedTransform, renderable: &StaticRenderableComponent, ) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::RegisterStatic { entity, transform: transform.0, model_path: renderable.model_path.to_string(), receive_shadows: renderable.receive_shadows, cast_shadows: renderable.cast_shadows, can_move: renderable.can_move, }); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn unregister_static_renderable(&self, entity: Entity) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::UnregisterStatic(entity)); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn register_point_light( &self, entity: Entity, transform: &InterpolatedTransform, component: &PointLightComponent, ) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::RegisterPointLight { entity, transform: transform.0, intensity: component.intensity, }); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn unregister_point_light(&self, entity: Entity) { let result = self .sender .send(RendererCommand::UnregisterPointLight(entity)); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn register_directional_light( &self, entity: Entity, transform: &InterpolatedTransform, component: &DirectionalLightComponent, ) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::RegisterDirectionalLight { entity, transform: transform.0, intensity: component.intensity, }); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn unregister_directional_light(&self, entity: Entity) { let result = self .sender .send(RendererCommand::UnregisterDirectionalLight(entity)); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn update_camera_transform(&self, camera_transform_mat: Matrix4, fov: f32) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::UpdateCameraTransform { camera_transform_mat, fov, }); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn update_transform(&self, entity: Entity, transform: Matrix4) { let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::UpdateTransform { entity, transform_mat: transform, }); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn end_frame(&self) { let mut queued_guard = self.queued_frames_counter.lock().unwrap(); *queued_guard += 1; let result = self.sender.send(RendererCommand::<P::GraphicsBackend>::EndFrame); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn update_lightmap(&self, path: &str) { let result = self .sender .send(RendererCommand::<P::GraphicsBackend>::SetLightmap(path.to_string())); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } fn wait_until_available(&self, timeout: Duration) { let queued_guard = self.queued_frames_counter.lock().unwrap(); #[cfg(not(target_arch = "wasm32"))] let _ = self .cond_var .wait_timeout_while(queued_guard, timeout, |queued| { *queued > 1 || !self.is_running() }) .unwrap(); #[cfg(target_arch = "wasm32")] let _ = self .cond_var .wait_while(queued_guard, |queued| *queued > 1) .unwrap(); } fn is_saturated(&self) -> bool { let queued_guard = self.queued_frames_counter.lock().unwrap(); *queued_guard > 1 } fn is_running(&self) -> bool { self.is_running.load(Ordering::SeqCst) } fn update_ui(&self, ui_data: UIDrawData<P::GraphicsBackend>) { let result = self.sender.send(RendererCommand::RenderUI(ui_data)); if let Result::Err(err) = result { panic!("Sending message to render thread failed {:?}", err); } } }
pub mod prelude { pub use super::camera::CameraSettings; pub use super::debug::DebugSettings; pub use super::enemies::{EnemiesSettings, EnemySettings}; pub use super::level_manager::{LevelManagerSettings, LevelSettings}; pub use super::misc::MiscSettings; pub use super::music::MusicSettings; pub use super::player::{ PlayerAnimationSizes, PlayerJumpSettings, PlayerSettings, }; pub use super::savefile::SavefileSettings; pub use super::timer::TimerSettings; pub use super::Settings; } mod camera; mod debug; mod enemies; mod level_manager; mod misc; mod music; mod player; mod savefile; mod timer; use prelude::*; #[derive(Clone, Deserialize)] pub struct Settings { pub camera: CameraSettings, pub player: PlayerSettings, pub enemies: EnemiesSettings, pub savefile: SavefileSettings, pub level_manager: LevelManagerSettings, pub music: MusicSettings, pub timer: TimerSettings, pub misc: MiscSettings, pub debug: DebugSettings, }
use super::db::Bank; use regex::Regex; use std::process::Command; lazy_static! { pub static ref DEVICE: String = get_devices().expect("未连接设备"); static ref RE_POSITION: Regex = Regex::new(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]").unwrap(); } #[cfg(target_os = "windows")] static ADB: &'static str = "./resource/ADB/adb"; #[cfg(not(target_os = "windows"))] static ADB: &'static str = "adb"; pub fn swipe(x0: usize, y0: usize, x1: usize, y1: usize, duration: usize) { Command::new(ADB) .args( format!( "shell input swipe {:} {:} {:} {:} {:}", x0, y0, x1, y1, duration ) .split_whitespace(), ) .output() .expect("failed"); } pub fn tap(x: usize, y: usize) { swipe(x, y, x, y, 50); } pub fn draw() { let xml = xpath("//hierarchy/node/@bounds"); let s = xml.get(0).expect("draw failed: xpath 错误"); let caps = RE_POSITION.captures(s).unwrap(); let x: usize = caps[3].parse().unwrap(); let y: usize = caps[4].parse().unwrap(); let (height, width) = (x, y); // 中点 三分之一点 三分之二点 let (x0, x1) = (width / 2, width / 2); let (y0, y1) = (height / 4, height / 4 * 3); swipe(x1, y1, x0, y0, 500); } pub fn back() { Command::new(ADB) .args(format!("-s {:} shell input keyevent 4", DEVICE.as_str()).split_whitespace()) .output() .expect("failed"); } pub fn input(msg: &str) { Command::new(ADB) .args(&[ "-s", &DEVICE, "shell", "am", "broadcast", "-a", "ADB_INPUT_TEXT", "--es", "msg", msg, ]) .output() .expect("failed"); } pub fn connect(host: &str, port: &str) { Command::new(ADB) .args(format!("connect {:}:{:}", host, port).split_whitespace()) .output() .expect("failed"); } pub fn _disconnect(host: &str, port: &str) { Command::new(ADB) .args(format!("disconnect {:}:{:}", host, port).split_whitespace()) .output() .expect("failed"); } pub fn set_ime(ime: &str) { Command::new(ADB) .args(format!("-s {} shell ime set {}", DEVICE.as_str(), ime).split_whitespace()) .output() .expect("failed"); } pub fn get_ime() -> Option<String> { let output = Command::new(ADB) .args(format!("-s {} shell ime list -s", DEVICE.as_str()).split_whitespace()) .output() .expect("获取输入法失败"); let output = String::from_utf8_lossy(&output.stdout); let imes: Vec<_> = output.split_whitespace().collect(); dbg!(&imes); //.map(|x| x.to_string()) Some(imes[0].to_string()) } pub fn get_devices() -> Option<String> { let output = Command::new(ADB).arg("devices").output().unwrap(); let output = String::from_utf8_lossy(&output.stdout); output .lines() .filter(|&line| line.ends_with("\tdevice")) .map(|line| line.trim_end_matches("\tdevice")) .next() .map(ToString::to_string) } pub fn uiautomator() { Command::new(ADB) .args( format!( "-s {:} shell uiautomator dump /sdcard/ui.xml", DEVICE.as_str() ) .split_whitespace(), ) .output() .expect("failed"); Command::new(ADB) .args(&["pull", "/sdcard/ui.xml", "./resource/ui.xml"]) .output() .expect("failed"); } pub fn xpath(xpath_rule: &str) -> Vec<String> { let xml = std::fs::read_to_string("./resource/ui.xml").expect("读取xml文件失败"); let res = amxml::dom::new_document(&xml) .expect("解析xml文件失败") .root_element() .get_nodeset(xpath_rule) .expect("xpath 执行失败"); let v: Vec<String> = res .iter() .map(|x| x.value().replace('\u{a0}', " ")) .map(|x| if x == "" { " ".to_string() } else { x }) .collect(); return v; } pub fn content_options_positons( content: &str, options: &str, positions: &str, ) -> (String, String, Vec<(usize, usize)>) { uiautomator(); let content = xpath(content)[0].clone(); let options = xpath(options).join("|"); let positions = xpath(positions); let positions = positions .iter() .map(|s| { let caps = RE_POSITION.captures(&s).unwrap(); let s: Vec<usize> = caps .iter() .filter_map(|x| x) .filter_map(|x| x.as_str().parse().ok()) .collect(); ((s[0] + s[2]) / 2, (s[1] + s[3]) / 2) }) .collect(); return (content, options, positions); } pub fn load<P: AsRef<std::path::Path>>(path: P) -> Vec<Bank> { let s = std::fs::read_to_string(path).unwrap(); let v: Vec<Bank> = serde_json::from_str(&s).unwrap(); return v; } pub fn dump<P: AsRef<std::path::Path>>(path: P, banks: &Vec<Bank>) { let f = std::fs::File::create(path).unwrap(); serde_json::to_writer_pretty(f, banks).unwrap(); } pub fn sleep(second: u64) { std::thread::sleep(std::time::Duration::from_secs(second)); } pub trait Xpath { fn click(&self); fn texts(&self) -> Vec<String>; fn positions(&self) -> Vec<(usize, usize)>; } impl Xpath for String { fn texts(&self) -> Vec<String> { uiautomator(); xpath(&self) } fn positions(&self) -> Vec<(usize, usize)> { self.texts() .iter() .map(|s| { let caps = RE_POSITION.captures(&s).unwrap(); let s: Vec<usize> = caps .iter() .filter_map(|x| x) .filter_map(|x| x.as_str().parse().ok()) .collect(); ((s[0] + s[2]) / 2, (s[1] + s[3]) / 2) }) .collect() } fn click(&self) { for _ in 0..10 { if let [(x, y)] = &*self.positions() { tap(*x, *y); return; }; } dbg!(&self); panic!("click failed"); } }
use crate::math::Vec3; use crate::Hittable; use crate::Material; use rand::RngCore; use rand_distr::{Distribution, Uniform, UnitDisc}; use std::sync::Arc; pub struct Ray { pub origin: Vec3, pub direction: Vec3, pub time: f64, } impl Ray { pub fn at(&self, t: f64) -> Vec3 { self.origin + t * self.direction } } pub struct HitRecord<'a> { pub t: f64, pub p: Vec3, pub normal: Vec3, pub front_facing: bool, pub material: &'a dyn Material, pub u: f64, pub v: f64, } impl<'a> HitRecord<'a> { pub fn set_face_normal(incoming: Vec3, outward_normal: Vec3) -> (bool, Vec3) { let front_facing = incoming.dot(&outward_normal) < 0.0; let normal = { if front_facing { outward_normal } else { -outward_normal } }; (front_facing, normal) } pub fn from( t: f64, p: Vec3, incoming: Vec3, normal: Vec3, material: &dyn Material, ) -> HitRecord { let (front_facing, normal) = HitRecord::set_face_normal(incoming, normal); HitRecord { t, p, normal, front_facing, material, u: 0.0, v: 0.0, } } pub fn from_uv( t: f64, p: Vec3, incoming: Vec3, normal: Vec3, material: &dyn Material, u: f64, v: f64, ) -> HitRecord { let (front_facing, normal) = HitRecord::set_face_normal(incoming, normal); HitRecord { t, p, normal, front_facing, material, u, v, } } } #[derive(Copy, Clone)] pub struct Camera { pub origin: Vec3, pub horizontal: Vec3, pub vertical: Vec3, pub lower_left_corner: Vec3, pub u: Vec3, pub v: Vec3, pub w: Vec3, pub lens_radius: f64, pub time_begin: f64, pub time_end: f64, } impl Camera { pub fn new( eye: Vec3, target: Vec3, up: Vec3, vertical_fov: f64, aspect_ratio: f64, aperture: f64, focus_distance: f64, time_0: f64, time_1: f64, ) -> Camera { let theta = vertical_fov.to_radians(); let h = (theta / 2.0).tan(); let viewport_height = 2.0 * h; let viewport_width = viewport_height * aspect_ratio; let w = (eye - target).normalize(); let u = (up.cross(&w)).normalize(); let v = w.cross(&u); let horizontal = focus_distance * viewport_width * u; let vertical = focus_distance * viewport_height * v; Camera { origin: eye, horizontal, vertical, u, v, w, lower_left_corner: eye - horizontal / 2. - vertical / 2. - focus_distance * w, lens_radius: aperture / 2., time_begin: time_0, time_end: time_1, } } pub fn get_ray(&self, s: f64, t: f64, rng: &mut impl RngCore) -> Ray { let rd: [f64; 2] = UnitDisc.sample(rng); let offset = (self.u * rd[0] + self.v * rd[1]) * self.lens_radius; // TODO seedable shutter time let shutter_time = Uniform::from(self.time_begin..self.time_end).sample(rng); Ray { origin: self.origin + offset, direction: self.lower_left_corner + s * self.horizontal + t * self.vertical - self.origin - offset, time: shutter_time, } } } pub struct Subregion { pub x: usize, pub y: usize, pub width: usize, pub height: usize, } impl Subregion { pub fn grid_cell( x: usize, y: usize, cells_x: usize, cells_y: usize, render_width: usize, render_height: usize, ) -> Subregion { let base_cell_width = render_width / cells_x; let current_cell_width = { if x == cells_x - 1 { render_width - (base_cell_width * (cells_x - 1)) } else { base_cell_width } }; let base_cell_height = render_height / cells_y; let current_cell_height = { if y == cells_y - 1 { render_height - (base_cell_height * (cells_y - 1)) } else { base_cell_height } }; Subregion { x: base_cell_width * x, y: base_cell_height * y, width: current_cell_width, height: current_cell_height, } } pub fn slice_vertically( y: usize, cells_y: usize, render_width: usize, render_height: usize, ) -> Subregion { let base_cell_height = render_height / cells_y; let current_cell_height = { if y == cells_y - 1 { render_height - (base_cell_height * (cells_y - 1)) } else { base_cell_height } }; Subregion { x: 0, y: base_cell_height * y, width: render_width, height: current_cell_height, } } pub fn area(&self) -> usize { self.width * self.height } } pub struct RenderTile { pub region: Subregion, pub buffer: Vec<Vec3>, pub scene: Arc<dyn Hittable>, pub camera: Camera, } impl RenderTile { pub fn new(region: Subregion, scene: Arc<dyn Hittable>, camera: Camera) -> RenderTile { let buffer_size = region.area(); RenderTile { region, buffer: vec![Vec3::zeros(); buffer_size], scene, camera, } } }
use std; use na::*; use math::*; use renderer::*; use alga::general::SupersetOf; pub struct VoxelGrid3<T : Real + Copy>{ pub a : T, pub size_x : usize, pub size_y : usize, pub size_z : usize, pub grid : Vec<T>, } impl<T : Real + SupersetOf<f32>> VoxelGrid3<T>{ pub fn vertices_x(&self) -> usize {self.size_x + 1} pub fn vertices_y(&self) -> usize {self.size_y + 1} pub fn vertices_z(&self) -> usize {self.size_z + 1} pub fn new(a : T, size_x : usize, size_y : usize, size_z : usize) -> VoxelGrid3<T>{ let grid = vec![convert(0.0);(size_x + 1) * (size_y + 1) * (size_z + 1)]; VoxelGrid3{a,size_x, size_y, size_z, grid} } pub fn get(&self, x : usize, y : usize, z : usize) -> T{ self.grid[z * self.vertices_y() * self.vertices_x() + y * self.vertices_x() + x] } pub fn set(&mut self, x : usize, y : usize, z : usize, value : T){ let vx = self.vertices_x(); let vy = self.vertices_y(); self.grid[z * vy * vx + y * vx + x] = value; } pub fn get_point(&self, x : usize, y : usize, z : usize) -> Vector3<T>{ Vector3::new(self.a * convert::<f32, T>(x as f32), self.a * convert::<f32, T>(y as f32), self.a * convert::<f32, T>(z as f32)) } //bounding box of the cube pub fn square3(&self, x : usize, y : usize, z : usize) -> Square3<T>{ Square3{center : Vector3::new(convert::<f32,T>(x as f32 + 0.5) * self.a, convert::<f32,T>(y as f32 + 0.5) * self.a, convert::<f32,T>(z as f32 + 0.5) * self.a), extent: self.a / convert(2.0)} } } fn calc_qef(point : &Vector3<f32>, planes : &Vec<Plane<f32>>) -> f32{ let mut qef : f32 = 0.0; for plane in planes{ let dist_signed = plane.normal.dot(&(point - plane.point)); qef += dist_signed * dist_signed; } qef } fn const_sign(a : f32, b : f32) -> bool { if a > 0.0 { b > 0.0} else {b <= 0.0} } fn sample_qef_brute(square : Square3<f32>, n : usize, planes : &Vec<Plane<f32>>) -> Vector3<f32> { let ext = Vector3::new(square.extent, square.extent, square.extent); let min = square.center - ext; let mut best_qef = std::f32::MAX; let mut best_point = min; for i in 0..n{ for j in 0..n{ for k in 0..n{ let point = min + Vector3::new(ext.x * (2.0 * (i as f32) + 1.0) / (n as f32), ext.y * (2.0 * (j as f32) + 1.0) / (n as f32), ext.z * (2.0 * (k as f32) + 1.0) / (n as f32)); let qef = calc_qef(&point, &planes); if qef < best_qef{ best_qef = qef; best_point = point; } } } } best_point } //in the feature density functions will not be present at all times (as the world can be saved to disk, generator-density function is not saved) //so the algorithm should use some interpolation methods assuming the surface is smooth(does not change too much within one cube of the grid) //interpolation can operate on 8 corner vertices of the cube //TODO or maybe save generator to disk ??, in case of random(presudo-random) generator - its seed can be saved fn sample_intersection_brute(line : Line3<f32>, n_ : usize, f : &DenFn3<f32>) -> Vector3<f32>{ let ext = line.end - line.start; let norm = ext.norm(); let dir = ext / norm; //let mut best_abs = std::f32::MAX; //let mut best_point : Option<Vector3<f32>> = None; let mut center = line.start + ext * 0.5; let mut cur_ext = norm * 0.25; let n = (n_ as f32).log2() as usize + 1; for i in 0..n { let point1 = center - dir * cur_ext; let point2 = center + dir * cur_ext; let den1 = f(point1).abs(); let den2 = f(point2).abs(); if den1 <= den2 { center = point1; }else{ center = point2; } cur_ext *= 0.5; } center } //why haven't I come up with this one at the start ? :) pub fn sample_normal(point : &Vector3<f32>, eps : f32, f : &DenFn3<f32>) -> Vector3<f32>{ Vector3::new( f(Vector3::new(point.x + eps, point.y, point.z)) - f(Vector3::new(point.x - eps, point.y, point.z)), f(Vector3::new(point.x, point.y + eps, point.z)) - f(Vector3::new(point.x, point.y - eps, point.z)), f(Vector3::new(point.x, point.y, point.z + eps)) - f(Vector3::new(point.x, point.y, point.z - eps)) ).normalize() } //works not so well pub fn sample_normal1(sphere : &Sphere<f32>, n : usize, f : &DenFn3<f32>) -> Vector3<f32>{ let den_at_center = f(sphere.center); let mut best = 0.0; let mut normal_point = sphere.center; let slice2_ = std::f32::consts::PI / n as f32; let slice1_ = slice2_ * 2.0; for i in 0..n{ let slice1 = slice1_ * (i as f32); for j in 0..n{ let slice2 = slice2_ * (j as f32); let y = slice2.cos() * sphere.rad; let x = slice1.cos() * slice2.sin().abs() * sphere.rad; let z = -slice1.sin() * slice2.sin().abs() * sphere.rad; let point = sphere.center + Vector3::new(x,y,z); let den = f(point); let attempt = den - den_at_center; if attempt > best{ best = attempt; normal_point = point; } } } (normal_point - sphere.center).normalize() } pub fn test_sample_normal(){ let test_sph = Sphere{center : Vector3::new(0.0, 0.0, 0.0), rad : 1.0}; let test_point = Sphere{center : Vector3::new(0.0, 0.0, 1.0), rad : 0.01}; let test_solid = mk_sphere(test_sph); let res = sample_normal(&test_point.center, 0.001, &test_solid); println!("{}", res); //result should approach {0.0,0.0,1.0} increasing accuracy } //voxel grid is an array like structure (in the feature it should be upgraded to an octree) that contains density information at each vertex of each cube of the grid //feature is a vertex that may or may not be calculated for each cube of the grid. It is calculated for each cube that exhibits a sign change(this means that the cube // intersects the surface) and not calculated otherwise fn calc_feature(vg : &VoxelGrid3<f32>, x : usize, y : usize, z : usize, f : &DenFn3<f32>, accuracy : usize, contour_data : &mut ContourData, debug_render : &mut RendererVertFragDef) -> Option<Vector3<f32>>{ //let epsilon = vg.a / accuracy as f32; let p00 = vg.get(x, y, z); let p01 = vg.get(x + 1, y, z); let p02 = vg.get(x, y + 1, z); let p03 = vg.get(x + 1, y + 1, z); let p10 = vg.get(x, y, z + 1); let p11 = vg.get(x + 1, y, z + 1); let p12 = vg.get(x, y + 1, z + 1); let p13 = vg.get(x + 1, y + 1, z + 1); let v00 = vg.get_point(x, y, z); let v01 = vg.get_point(x + 1, y, z); let v02 = vg.get_point(x, y + 1, z); let v03 = vg.get_point(x + 1, y + 1, z); let v10 = vg.get_point(x,y, z + 1); let v11 = vg.get_point(x + 1, y, z + 1); let v12 = vg.get_point(x, y + 1, z + 1); let v13 = vg.get_point(x + 1, y + 1, z + 1); let mut edge_info = 0; if !const_sign(p00, p01){edge_info |= 1;} if !const_sign(p01, p03){edge_info |= 2;} if !const_sign(p03, p02){edge_info |= 4;} //z if !const_sign(p02, p00){edge_info |= 8;} if !const_sign(p10, p11){edge_info |= 16;} if !const_sign(p11, p13){edge_info |= 32;} //z + 1 if !const_sign(p13, p12){edge_info |= 64;} if !const_sign(p12, p10){edge_info |= 128;} if !const_sign(p00, p10){edge_info |= 256;} if !const_sign(p01, p11){edge_info |= 512;} if !const_sign(p02, p12){edge_info |= 1024;} //edges in between of 2 z-levels if !const_sign(p03, p13){edge_info |= 2048;} let rad_for_normal = vg.a / 100.0; //TODO will not work if vg.a is too small (f32 precision) if edge_info > 0{ //let mut normals = Vec::<f32>::new(); //let mut intersections = Vec::<f32>::new(); let mut planes = Vec::new(); { let mut worker = |edge_id : usize, v_a : Vector3<f32>, v_b : Vector3<f32>, p_a : f32, p_b : f32|{//goes through each edge of the cube if (edge_info & edge_id) > 0{ let ip = sample_intersection_brute(Line3{start : v_a, end : v_b}, accuracy, f);//intersecion point //let full = if p_a <= 0.0 {v_a} else {v_b}; //let normal = sample_normal(&Sphere{center : ip, rad : rad_for_normal}, accuracy, f); let normal = sample_normal(&ip, rad_for_normal, f); //intersections.push(ip.x); //intersections.push(ip.y); //intersections.push(ip.z); //normals.push(normal.x); //normals.push(normal.y); //normals.push(normal.z); planes.push(Plane{point : ip, normal}); //calculate feature vertices of 3 other cubes containing this edge then create a quad from maximum of 4 those feature vertices. //this is done in make_contour } }; worker(1, v00, v01, p00, p01); worker(2, v01, v03, p01, p03); worker(4, v03, v02, p03, p02); worker(8, v02, v00, p02, p00); worker(16, v10, v11, p10, p11); worker(32, v11, v13, p11, p13); worker(64, v13, v12, p13, p12); worker(128, v12, v10, p12, p10); worker(256, v00, v10, p00, p10); worker(512, v01, v11, p01, p11); worker(1024, v02, v12, p02, p12); worker(2048, v03, v13, p03, p13); } /* let mut product = Vec::with_capacity(normals.len()); for i in 0..normals.len()/3{ product.push(normals[3 * i] * intersections[3 * i] + normals[3 * i + 1] * intersections[3 * i + 1] + normals[3 * i + 2] * intersections[3 * i + 2]); } //let feature_vertex = Vector3::new(0.0,0.0,0.0);//sample_qef_brute(vg.square3(x,y,z), accuracy, &normals.zip);//TODO let A = DMatrix::from_row_slice(normals.len() / 3, 3, normals.as_slice()); let ATA = (&A).transpose() * &A; let b = DMatrix::from_row_slice(product.len(), 1, product.as_slice()); let ATb = (&A).transpose() * &b; */ //println!("{:?} {}", normals.as_slice(), A); let feature_vertex = sample_qef_brute(vg.square3(x, y, z), accuracy, &planes); let t = z * vg.size_y * vg.size_x + y * vg.size_x + x; contour_data.features[t] = Some(feature_vertex); //contour_data.normals[t] = Some(sample_normal(&Sphere{center : feature_vertex, rad : rad_for_normal}, accuracy, f)); contour_data.normals[t] = Some(sample_normal(&feature_vertex, vg.a / 100.0, f)); Some(feature_vertex) }else{ None } } //TODO debug_renderer is for debug only pub fn make_contour(vg : &VoxelGrid3<f32>, f : &DenFn3<f32>, accuracy : usize, debug_renderer : &mut RendererVertFragDef) -> ContourData{ //TODO inefficient Vec::new() creation vvv let mut contour_data = ContourData{lines : Vec::new(), triangles : Vec::new(), triangle_normals : Vec::new(), features : vec![None;vg.size_x * vg.size_y * vg.size_z], normals : vec![None;vg.size_x * vg.size_y * vg.size_z]}; let mut cache_already_calculated = vec![false;vg.size_x * vg.size_y * vg.size_z]; //this cache is used to mark cubes that have already been calculated for feature vertex { //&mut contour_data, cache_already_calculated let mut cached_make = |x: usize, y: usize, z : usize, contour_data : &mut ContourData| -> Option<Vector3<f32>>{ let t = z * vg.size_y * vg.size_x + y * vg.size_x + x; if cache_already_calculated[t] { contour_data.features[t] }else{ cache_already_calculated[t] = true; calc_feature(&vg, x, y, z, f, accuracy, contour_data, debug_renderer) } }; for z in 0..vg.size_z{ for y in 0..vg.size_y { for x in 0..vg.size_x { //let p00 = vg.get(x, y, z); //let p01 = vg.get(x + 1, y, z); //let p02 = vg.get(x, y + 1, z); let p03 = vg.get(x + 1, y + 1, z); //let p10 = vg.get(x, y, z + 1); let p11 = vg.get(x + 1, y, z + 1); let p12 = vg.get(x, y + 1, z + 1); let p13 = vg.get(x + 1, y + 1, z + 1); /*let v00 = vg.get_point(x, y, z); let v01 = vg.get_point(x + 1, y, z); let v02 = vg.get_point(x, y + 1, z); let v03 = vg.get_point(x + 1, y + 1, z); let v10 = vg.get_point(x,y, z + 1); let v11 = vg.get_point(x + 1, y, z + 1); let v12 = vg.get_point(x, y + 1, z + 1); let v13 = vg.get_point(x + 1, y + 1, z + 1);*/ let possible_feature_vertex = cached_make(x, y, z, &mut contour_data); match possible_feature_vertex{ None => (), Some(f0) => { let t = z * vg.size_y * vg.size_x + y * vg.size_x + x; let normal = contour_data.normals[t].unwrap(); //TODO incorrect normals in some places if !const_sign(p03, p13){ let f1 = cached_make(x + 1, y, z, &mut contour_data).unwrap(); let f2 = cached_make(x + 1, y + 1, z, &mut contour_data).unwrap(); let f3 = cached_make(x, y + 1, z, &mut contour_data).unwrap(); //f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge //this is needed to calculate the direction of the resulting quad correctly let dir = (f2 - f0).cross(&(f3 - f0)).normalize(); if dir.dot(&normal) > 0.0{ //should not be zero at any time contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); //TODO debug /* if (dir.dot(&debug_real_normal) <= 0.0) { println!("bad normal at {} {} {} {}", 1, x, y, z); } */ contour_data.triangle_normals.push(dir); //TODO inefficient }else{ contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); /* if (-dir.dot(&debug_real_normal) <= 0.0) { add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0)); add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); add_line3_color(debug_renderer, Line3{start : f0, end : f0 - normal.normalize()}, Vector3::new(0.0, 0.0, 0.0)); println!("bad normal at {} {}", 2, -dir.dot(&debug_real_normal)); } */ contour_data.triangle_normals.push(-dir); } } if !const_sign(p12, p13){ let f1 = cached_make(x, y, z + 1, &mut contour_data).unwrap(); let f2 = cached_make(x, y + 1, z + 1, &mut contour_data).unwrap(); let f3 = cached_make(x, y + 1, z, &mut contour_data).unwrap(); //f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge //this is needed to calculate the direction of the resulting quad correctly let dir = (f2 - f0).cross(&(f3 - f0)).normalize(); if dir.dot(&normal) > 0.0{ //should not be zero at any time contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); /* if (dir.dot(&debug_real_normal) <= 0.0) { println!("bad normal at {} {} {} {}", 3, x, y, z); } */ contour_data.triangle_normals.push(dir); }else{ contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); /* if (-dir.dot(&debug_real_normal) <= 0.0) { add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0)); add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); add_line3_color(debug_renderer, Line3{start : f0, end : f0 - normal.normalize()}, Vector3::new(0.0, 0.0, 0.0)); println!("bad normal at {} {}", 4, -dir.dot(&debug_real_normal)); } */ contour_data.triangle_normals.push(-dir); } } if !const_sign(p11, p13){ let f1 = cached_make(x + 1, y, z, &mut contour_data).unwrap(); let f2 = cached_make(x + 1, y, z + 1, &mut contour_data).unwrap(); let f3 = cached_make(x, y, z + 1, &mut contour_data).unwrap(); //f1 && f2 && f3 all should be non-empty, as they all exhibit a sign change at least on their common edge //this is needed to calculate the direction of the resulting quad correctly let dir = (f2 - f0).cross(&(f3 - f0)).normalize(); if dir.dot(&normal) > 0.0{ //should not be zero at any time contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f3}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f1, p3 : f2}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 + dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); /* if (dir.dot(&debug_real_normal) <= 0.0) { println!("bad normal at {} {} {} {}", 5, x, y, z); } */ contour_data.triangle_normals.push(dir); } else{ contour_data.triangles.push(Triangle3{p1 : f0, p2 : f3, p3 : f2}); contour_data.triangles.push(Triangle3{p1 : f0, p2 : f2, p3 : f1}); //add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); /* if (-dir.dot(&debug_real_normal) <= 0.0) { add_square3_bounds_color(debug_renderer, vg.square3(x, y, z), Vector3::new(1.0, 0.0, 0.0)); add_line3_color(debug_renderer, Line3{start : f0, end : f0 - dir * 0.1}, Vector3::new(1.0, 1.0, 1.0)); println!("bad normal at {} {} {} {}", 6, x, y, z); } */ contour_data.triangle_normals.push(-dir); } } }, } } } } } contour_data } pub fn fill_in_grid(vg : &mut VoxelGrid3<f32>, f : &DenFn3<f32>, offset : Vector3<f32>){ for z in 0..vg.size_z + 1 { for y in 0..vg.size_y + 1{ for x in 0..vg.size_x + 1 { let vx = vg.vertices_x(); let vy = vg.vertices_y(); vg.grid[z * vy * vx + y * vx + x] = f(offset + Vector3::new(vg.a * (x as f32), vg.a * (y as f32), vg.a * (z as f32))); } } } } pub struct ContourData{ // + hermite data ? (exact points of intersection of the surface with each edge that exhibits a sign change + normals for each of those points) pub lines : Vec<Line3<f32>>, pub triangles : Vec<Triangle3<f32>>, pub triangle_normals : Vec<Vector3<f32>>, pub features : Vec<Option<Vector3<f32>>>, pub normals : Vec<Option<Vector3<f32>>>, //normal to the surface calculated at feature vertex }
use std::collections::{HashMap, BTreeMap}; use std::error; use std::fmt; use std::io::Write; use std::io::Error as IOError; use serialize::json::Json; use template::{Template, TemplateElement, Parameter, HelperTemplate}; use template::TemplateElement::{RawString, Expression, Comment, HelperBlock, HTMLExpression, HelperExpression}; use registry::Registry; use context::{Context, JsonRender}; use support::str::StringWriter; #[derive(Debug, Clone, Copy)] pub struct RenderError { pub desc: &'static str } impl fmt::Display for RenderError { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{}", self.desc) } } impl error::Error for RenderError { fn description(&self) -> &str { self.desc } } impl From<IOError> for RenderError { fn from(_: IOError) -> RenderError { render_error("IO Error") } } /// The context of a render call /// /// this context stores information of a render and a writer where generated /// content is written to. /// pub struct RenderContext<'a> { partials: HashMap<String, Template>, path: String, local_variables: HashMap<String, Json>, default_var: Json, /// the `Write` where page is generated pub writer: &'a mut Write } impl<'a> RenderContext<'a> { /// Create a render context from a `Write` pub fn new(w: &'a mut Write) -> RenderContext<'a> { RenderContext { partials: HashMap::new(), path: ".".to_string(), local_variables: HashMap::new(), default_var: Json::Null, writer: w } } /// Create a new `RenderContext` with a different `Write` pub fn with_writer<'b>(&self, w: &'b mut Write) -> RenderContext<'b> { RenderContext { partials: self.partials.clone(), path: self.path.clone(), local_variables: self.local_variables.clone(), default_var: self.default_var.clone(), writer: w } } pub fn get_partial(&self, name: &String) -> Option<Template> { match self.partials.get(name) { Some(t) => Some(t.clone()), None => None } } pub fn set_partial(&mut self, name: String, result: Template) { self.partials.insert(name, result); } pub fn get_path(&self) -> &String { &self.path } pub fn set_path(&mut self, path: String) { self.path = path } pub fn set_local_var(&mut self, name: String, value: Json) { self.local_variables.insert(name, value); } pub fn clear_local_vars(&mut self){ self.local_variables.clear(); } pub fn promote_local_vars(&mut self) { let mut new_map: HashMap<String, Json> = HashMap::new(); for key in self.local_variables.keys() { let mut new_key = String::new(); new_key.push_str("@../"); new_key.push_str(&key[1..]); let v = self.local_variables.get(key).unwrap().clone(); new_map.insert(new_key, v); } self.local_variables = new_map; } pub fn demote_local_vars(&mut self) { let mut new_map: HashMap<String, Json> = HashMap::new(); for key in self.local_variables.keys() { if key.starts_with("@../") { let mut new_key = String::new(); new_key.push('@'); new_key.push_str(&key[4..]); let v = self.local_variables.get(key).unwrap().clone(); new_map.insert(new_key, v); } } self.local_variables = new_map; } pub fn get_local_var(&self, name: &String) -> &Json { match self.local_variables.get(name) { Some(j) => j, None => &self.default_var } } pub fn writer(&mut self) -> &mut Write { self.writer } } pub struct Helper<'a> { name: &'a String, params: Vec<String>, hash: BTreeMap<String, Json>, template: &'a Option<Template>, inverse: &'a Option<Template>, block: bool } impl<'a, 'b> Helper<'a> { fn from_template(ht: &'a HelperTemplate, ctx: &Context, registry: &Registry, rc: &'b mut RenderContext) -> Result<Helper<'a>, RenderError> { let mut evaluated_params = Vec::new(); for p in ht.params.iter() { let r = try!(p.renders(ctx, registry, rc)); evaluated_params.push(r); } let mut evaluated_hash = BTreeMap::new(); for (k, p) in ht.hash.iter() { let r = try!(p.renders(ctx, registry, rc)); // subexpression in hash values are all treated as json string for now // FIXME: allow different types evaluated as hash value evaluated_hash.insert(k.clone(), Json::String(r)); } Ok(Helper { name: &ht.name, params: evaluated_params, hash: evaluated_hash, template: &ht.template, inverse: &ht.inverse, block: ht.block }) } pub fn name(&self) -> &String { &self.name } pub fn params(&self) -> &Vec<String> { &self.params } pub fn param(&self, idx: usize) -> Option<&String> { self.params.get(idx) } pub fn hash(&self) -> &BTreeMap<String, Json> { &self.hash } pub fn hash_get(&self, key: &str) -> Option<&Json> { self.hash.get(key) } pub fn template(&self) -> Option<&Template> { match *self.template { Some(ref t) => { Some(t) }, None => None } } pub fn inverse(&self) -> Option<&Template> { match *self.inverse { Some(ref t) => { Some(t) }, None => None } } pub fn is_block(&self) -> bool { self.block } } pub trait Renderable { fn render(&self, ctx: &Context, registry: &Registry, rc: &mut RenderContext) -> Result<(), RenderError>; } impl Parameter { fn renders(&self, ctx: &Context, registry: &Registry, rc: &mut RenderContext) -> Result<String, RenderError> { match self { &Parameter::Name(ref n) => { Ok(n.clone()) }, &Parameter::Subexpression(ref t) => { let mut local_writer = StringWriter::new(); let result = { let mut local_rc = rc.with_writer(&mut local_writer); t.render(ctx, registry, &mut local_rc) }; match result { Ok(_) => { Ok(local_writer.to_string()) }, Err(e) => { Err(e) } } } } } } impl Renderable for Template { fn render(&self, ctx: &Context, registry: &Registry, rc: &mut RenderContext) -> Result<(), RenderError> { let iter = self.elements.iter(); for t in iter { let c = ctx; try!(t.render(c, registry, rc)) } Ok(()) } } pub fn render_error(desc: &'static str) -> RenderError { RenderError { desc: desc } } impl Renderable for TemplateElement { fn render(&self, ctx: &Context, registry: &Registry, rc: &mut RenderContext) -> Result<(), RenderError> { match *self { RawString(ref v) => { try!(rc.writer.write(v.clone().into_bytes().as_ref())); Ok(()) }, Expression(ref v) => { let name = try!(v.renders(ctx, registry, rc)); let rendered = { let value = if name.starts_with("@") { rc.get_local_var(&name) } else { ctx.navigate(rc.get_path(), &name) }; value.render() }; let output = rendered.replace("&", "&amp;") .replace("\"", "&quot;") .replace("<", "&lt;") .replace(">", "&gt;"); try!(rc.writer.write(output.into_bytes().as_ref())); Ok(()) }, HTMLExpression(ref v) => { let name = try!(v.renders(ctx, registry, rc)); let rendered = { let value = if name.starts_with("@") { rc.get_local_var(&name) } else { ctx.navigate(rc.get_path(), &name) }; value.render() }; try!(rc.writer.write(rendered.into_bytes().as_ref())); Ok(()) }, HelperExpression(ref ht) | HelperBlock(ref ht) => { let helper = try!(Helper::from_template(ht, ctx, registry, rc)); match registry.get_helper(&ht.name) { Some(d) => { (**d).call(ctx, &helper, registry, rc) }, None => { let meta_helper_name = if ht.block { "blockHelperMissing" } else { "helperMissing" }.to_string(); match registry.get_helper(&meta_helper_name) { Some (md) => { (**md).call(ctx, &helper, registry, rc) } None => { Err(RenderError{ desc: "Helper not defined." }) } } } } }, Comment(_) => { Ok(()) } } } } #[test] fn test_raw_string() { let r = Registry::new(); let mut sw = StringWriter::new(); { let mut rc = RenderContext::new(&mut sw); let raw_string = RawString("<h1>hello world</h1>".to_string()); raw_string.render(&Context::null(), &r, &mut rc).ok().unwrap(); } assert_eq!(sw.to_string(), "<h1>hello world</h1>".to_string()); } #[test] fn test_expression() { let r = Registry::new(); let mut sw = StringWriter::new(); { let mut rc = RenderContext::new(&mut sw); let element = Expression(Parameter::Name("hello".into())); let mut m: HashMap<String, String> = HashMap::new(); let value = "<p></p>".to_string(); m.insert("hello".to_string(), value); let ctx = Context::wraps(&m); element.render(&ctx, &r, &mut rc).ok().unwrap(); } assert_eq!(sw.to_string(), "&lt;p&gt;&lt;/p&gt;".to_string()); } #[test] fn test_html_expression() { let r = Registry::new(); let mut sw = StringWriter::new(); let value = "world"; { let mut rc = RenderContext::new(&mut sw); let element = HTMLExpression(Parameter::Name("hello".into())); let mut m: HashMap<String, String> = HashMap::new(); m.insert("hello".to_string(), value.to_string()); let ctx = Context::wraps(&m); element.render(&ctx, &r, &mut rc).ok().unwrap(); } assert_eq!(sw.to_string(), value.to_string()); } #[test] fn test_template() { let r = Registry::new(); let mut sw = StringWriter::new(); { let mut rc = RenderContext::new(&mut sw); let mut elements: Vec<TemplateElement> = Vec::new(); let e1 = RawString("<h1>".to_string()); elements.push(e1); let e2 = Expression(Parameter::Name("hello".into())); elements.push(e2); let e3 = RawString("</h1>".to_string()); elements.push(e3); let e4 = Comment("".to_string()); elements.push(e4); let template = Template { elements: elements }; let mut m: HashMap<String, String> = HashMap::new(); let value = "world".to_string(); m.insert("hello".to_string(), value); let ctx = Context::wraps(&m); template.render(&ctx, &r, &mut rc).ok().unwrap(); } assert_eq!(sw.to_string(), "<h1>world</h1>".to_string()); } #[test] fn test_render_context_promotion_and_demotion() { use serialize::json::ToJson; let mut sw = StringWriter::new(); let mut render_context = RenderContext::new(&mut sw); render_context.set_local_var("@index".to_string(), 0usize.to_json()); render_context.promote_local_vars(); assert_eq!(render_context.get_local_var(&"@../index".to_string()), &0usize.to_json()); render_context.demote_local_vars(); assert_eq!(render_context.get_local_var(&"@index".to_string()), &0usize.to_json()); } #[test] fn test_render_subexpression() { let r = Registry::new(); let mut sw =StringWriter::new(); { let mut rc = RenderContext::new(&mut sw); let mut elements: Vec<TemplateElement> = Vec::new(); let e1 = RawString("<h1>".to_string()); elements.push(e1); let e2 = Expression(Parameter::parse("(hello)".into()).ok().unwrap()); elements.push(e2); let e3 = RawString("</h1>".to_string()); elements.push(e3); let template = Template { elements: elements }; let mut m: HashMap<String, String> = HashMap::new(); m.insert("hello".to_string(), "world".to_string()); m.insert("world".to_string(), "nice".to_string()); let ctx = Context::wraps(&m); template.render(&ctx, &r, &mut rc).ok().unwrap(); } assert_eq!(sw.to_string(), "<h1>nice</h1>".to_string()); }
use bitcoin::util::address::Address; use bitcoin::util::bip32::ExtendedPubKey; use serde::Deserialize; #[derive(Deserialize)] pub struct HWIExtendedPubKey { pub xpub: ExtendedPubKey, } #[derive(Deserialize)] pub struct HWISignature { pub signature: String, } #[derive(Deserialize)] pub struct HWIAddress { pub address: Address, } #[derive(Deserialize)] pub struct HWIPartiallySignedTransaction { pub psbt: String, } // TODO: use Descriptors #[derive(Deserialize)] pub struct HWIDescriptor { pub internal: Vec<String>, pub receive: Vec<String>, } #[derive(Deserialize)] pub struct HWIKeyPoolElement { pub desc: String, pub range: Vec<u32>, pub timestamp: String, pub internal: bool, pub keypool: bool, pub watchonly: bool, } #[derive(Clone)] pub enum HWIAddressType { Pkh, ShWpkh, Wpkh, }
#[doc = "Reader of register IF1CRQ"] pub type R = crate::R<u32, super::IF1CRQ>; #[doc = "Writer for register IF1CRQ"] pub type W = crate::W<u32, super::IF1CRQ>; #[doc = "Register IF1CRQ `reset()`'s with value 0"] impl crate::ResetValue for super::IF1CRQ { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `MNUM`"] pub type MNUM_R = crate::R<u8, u8>; #[doc = "Write proxy for field `MNUM`"] pub struct MNUM_W<'a> { w: &'a mut W, } impl<'a> MNUM_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x3f) | ((value as u32) & 0x3f); self.w } } #[doc = "Reader of field `BUSY`"] pub type BUSY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BUSY`"] pub struct BUSY_W<'a> { w: &'a mut W, } impl<'a> BUSY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } impl R { #[doc = "Bits 0:5 - Message Number"] #[inline(always)] pub fn mnum(&self) -> MNUM_R { MNUM_R::new((self.bits & 0x3f) as u8) } #[doc = "Bit 15 - Busy Flag"] #[inline(always)] pub fn busy(&self) -> BUSY_R { BUSY_R::new(((self.bits >> 15) & 0x01) != 0) } } impl W { #[doc = "Bits 0:5 - Message Number"] #[inline(always)] pub fn mnum(&mut self) -> MNUM_W { MNUM_W { w: self } } #[doc = "Bit 15 - Busy Flag"] #[inline(always)] pub fn busy(&mut self) -> BUSY_W { BUSY_W { w: self } } }
tonic::include_proto!("matchengine");
use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Default)] pub struct MemoData { #[serde(rename="MemoData")] pub memo_data: String, } impl MemoData { pub fn new(memo_data: String) -> Self { MemoData { memo_data: memo_data, } } } #[derive(Serialize, Deserialize, Debug, Default)] pub struct Memo { #[serde(rename="Memo")] pub memo_data: MemoData, } impl Memo { pub fn new(memo_data: MemoData) -> Self { Memo { memo_data: memo_data, } } } #[derive(Serialize, Deserialize, Debug, Default)] pub struct Memos { #[serde(rename="Memos")] pub memo: Memo, } impl Memos { pub fn new(memo: Memo) -> Self { Memos { memo: memo, } } } pub struct MemosBuilder { pub value: String, } impl MemosBuilder { pub fn new(value: String) -> Self { MemosBuilder { value: value, } } pub fn build(&self) -> Memos { let data = MemoData::new( String::from( self.value.as_str() ) ); let memo = Memo::new(data); Memos { memo: memo, } } }
use std::str::FromStr; use anyhow::Result; use sqlx::{Connection, ConnectOptions}; use sqlx::sqlite::SqliteConnectOptions; use structopt::StructOpt; use tokio; #[derive(Debug, StructOpt)] #[structopt(name = "list_servants")] struct Options { #[structopt(short, long, default_value = "sqlite:database.sqlite3")] url: String, } #[derive(Debug, sqlx::FromRow)] struct Servant { id: i64, name: String, class_name: String, created_at: chrono::NaiveDateTime, } #[tokio::main] async fn main() -> Result<()> { let options = Options::from_args(); let mut connection = SqliteConnectOptions::from_str(&options.url)? .create_if_missing(true) .connect().await?; let query = sqlx::query_as::<_, Servant>("select id, name, class_name, created_at from servants"); let results = query.fetch_all(&mut connection).await?; for servant in results { println!("{:?}", servant); } connection.close().await?; Ok(()) }
use crate::load_function_ptrs; use crate::prelude::*; use std::os::raw::c_char; use std::os::raw::c_void; pub type PFN_vkDebugReportCallbackEXT = extern "system" fn( VkDebugReportFlagsEXT, VkDebugReportObjectTypeEXT, u64, usize, i32, *const c_char, *const c_char, *mut c_void, ) -> VkBool32; load_function_ptrs!(DebugReportCallbackFunctions, { vkCreateDebugReportCallbackEXT( instance: VkInstance, createInfo: *const VkDebugReportCallbackCreateInfoEXT, allocationCallbacks: *const VkAllocationCallbacks, debugReportCallback: *mut VkDebugReportCallbackEXT ) -> VkResult, vkDestroyDebugReportCallbackEXT( instance: VkInstance, debugReportCallback: VkDebugReportCallbackEXT, allocationCallbacks: *const VkAllocationCallbacks ) -> (), });
extern crate enum_ast; use self::ast::*; type FragmentId = u32; type BindId = u32; #[ast] mod ast { #[derive(Copy, Clone, Debug, Hash, Eq, PartialEq, Ord, PartialOrd)] pub enum Step { Alternative(usize), Idx(usize), Fragment(FragmentId), StmtFragment(FragmentId), StmtIdx(usize), // Class(Class, Symbol), // RightQuote, Bind { bind_id: BindId, idx: usize }, Sequence { min: u32, max: Option<u32>, }, SequenceEnd, SequenceToken, #[upper_bound] Max, } neighborhood! { Neighborhood, Path, Step => (common ::= Alternative | Idx | Bind | Sequence) (start ::= StmtFragment StmtIdx common* (Fragment | Alternative)) (@allow start) } } #[test] fn test_panini() { let tree = InputTree { paths: vec![ path![Step::StmtFragment(0), Step::StmtIdx(0)], path![], ] } }
pub struct AreaLight {}
use crate::graphql::Context; use juniper::{FieldError, FieldResult, ID}; pub struct QueryUsers; #[juniper::graphql_object( Context = Context )] impl QueryUsers { /// Get a HOOMAN async fn getById(user_id: ID, context: &Context) -> FieldResult<super::User> { super::service::get_user(&context.client, &user_id) .await .map_err(FieldError::from) .map(|entity| super::User::from(&entity)) } /// Get list of HOOMANs async fn getList(context: &Context) -> FieldResult<Vec<super::User>> { super::service::get_all_users(&context.client) .await .map_err(FieldError::from) } }
use std::fmt::Display; use std::io; use std::io::BufRead; use std::ops::Deref; fn main() { let stdin = io::stdin(); let handle = stdin.lock(); let lines = handle.lines(); match compute(lines) { Ok(result) => println!("{}", result), Err(err) => eprintln!("Error: {}", err), }; } fn compute<'a, I, T, E>(input: I) -> Result<i32, String> where I: IntoIterator<Item = Result<T, E>>, T: Deref<Target = str>, E: Display { let lines = input.into_iter(); let mut sum = 0; for line_result in lines { let line = match line_result { Ok(line) => line, Err(err) => return Err(format!("Error while reading line: {}", err)), }; let values: Vec<i32> = values_from_line(line.deref())?; if let Some(line_result) = first_divisible_result(&values) { sum += line_result; } } Ok(sum) } fn values_from_line(line: &str) -> Result<Vec<i32>, String> { let mut values: Vec<i32> = vec![]; for cell in line.split_whitespace() { match i32::from_str_radix(cell, 10) { Ok(value) => values.push(value), Err(_) => return Err(format!("Not a number: {}", cell)), }; } Ok(values) } fn first_divisible_result<T: Deref<Target = [i32]>>(values: &T) -> Option<i32> { let mut it_i = values.iter(); while let Some(i) = it_i.next() { let mut it_j = it_i.clone(); while let Some(j) = it_j.next() { let (i, j) = if i < j { (i, j) } else { (j, i) }; if j % i == 0 { return Some(j / i) } } } None } #[cfg(test)] mod tests { use super::*; #[test] fn it_works_1() { let input = "5 9 2 8\n\ 9 4 7 3\n\ 3 8 6 5"; assert_eq!(Ok(9), compute(input.lines().map(|line| wrap(line)))); } fn wrap(input: &str) -> Result<&str, String> { Ok(input) } }
use super::*; use crate::{calc::*, cvars::Config, physics::*}; pub fn follow_camera(world: &mut World, config: &Config) { for (_, (pos, rb_pos)) in world .query::<With<Camera, (Option<&mut Position>, Option<&RigidBodyPosition>)>>() .iter() { if let Some(rb_pos) = rb_pos { if let Some(mut pos) = pos { let mut vec_pos = rb_pos.position.translation.into(); vec_pos *= config.phys.scale; pos.0 = lerp(pos.0, vec_pos, 0.33); } } } } pub fn kinetic_movement(world: &mut World) { for (_entity, mut body) in world.query::<&mut Particle>().iter() { if body.active { body.euler(); } } } pub struct PrimitiveMovement; pub fn primitive_movement(world: &mut World) { for (_, (input, mut pos)) in world .query::<With<PrimitiveMovement, (&Input, &mut Position)>>() .iter() { let mut delta = Vec2::ZERO; if input.state.contains(InputState::MoveLeft) { delta.x -= 1.; } if input.state.contains(InputState::MoveRight) { delta.x += 1.; } if input.state.contains(InputState::Jump) { delta.y -= 1.; } if input.state.contains(InputState::Crouch) { delta.y += 1.; } if delta != Vec2::ZERO { **pos += delta; } } } pub struct ForceMovement; pub fn force_movement(world: &mut World, config: &Config) { const RUNSPEED: f32 = 0.118; const RUNSPEEDUP: f32 = RUNSPEED / 6.0; const MAX_VELOCITY: f32 = 11.0; for (_, (input, mut forces, mut velocity, mass_properties)) in world .query::<With< ForceMovement, ( &Input, &mut RigidBodyForces, &mut RigidBodyVelocity, &RigidBodyMassProps, ), >>() .iter() { if input.state.contains(InputState::MoveLeft) && !input.state.contains(InputState::MoveRight) { forces.force.x = -RUNSPEED * config.phys.scale; forces.force.y = -RUNSPEEDUP * config.phys.scale; } if input.state.contains(InputState::MoveRight) && !input.state.contains(InputState::MoveLeft) { forces.force.x = RUNSPEED * config.phys.scale; forces.force.y = -RUNSPEEDUP * config.phys.scale; } if input.state.contains(InputState::Jump) { velocity.apply_impulse(mass_properties, Vec2::new(0.0, -RUNSPEED).into()); velocity.linvel.y = f32::max(velocity.linvel.y, -MAX_VELOCITY); velocity.linvel.y = f32::min(velocity.linvel.y, 0.); } // if input.state.contains(InputState::Crouch) { // delta.y += 1.; // } // println!("{:?}", forces); } }
pub enum StatFromType { Query = 1, /// Detect by host Host = 2, /// Detect base location query /// Detect base referer url Referer = 3, /// Detect base user-agent UserAgent = 4, } /// Request from pub struct StatFrom { /// name pub key: String, /// detect type pub detect_type: i16, /// keyword pub keyword: String, } impl StatFrom { pub fn new(key: &str, detect_type: i16, keyword: &str) -> Self { Self { key: key.to_owned(), detect_type, keyword: keyword.to_owned(), } } } lazy_static! { pub static ref INTERNAL_STAT_FROM_VEC: Vec<StatFrom> = vec![ StatFrom::new("百度", StatFromType::Referer as i16, "www.baidu.com"), StatFrom::new( "百度推广", StatFromType::Referer as i16, "www.baidu.com/baidu.php" ), StatFrom::new( "百度-移动端", StatFromType::Referer as i16, "m.baidu.com/from=" ), StatFrom::new( "百度推广-移动端", StatFromType::Referer as i16, "m.baidu.com/baidu.php" ), StatFrom::new( "百度知道", StatFromType::Referer as i16, "zhidao.baidu.com" ), StatFrom::new( "百度贴吧", StatFromType::Referer as i16, "tieba.baidu.com" ), StatFrom::new( "百度百科", StatFromType::Referer as i16, "baike.baidu.com" ), StatFrom::new("搜狗", StatFromType::Referer as i16, "www.sogou.com/link"), StatFrom::new( "搜狗-移动端", StatFromType::Referer as i16, "m.sogou.com/web" ), StatFrom::new( "搜狗推广", StatFromType::Referer as i16, "www.sogou.com/bill_cpc" ), StatFrom::new( "搜狗推广-移动端", StatFromType::Referer as i16, "m.sogou.com/bill_cpc" ), StatFrom::new( "搜狗百科", StatFromType::Referer as i16, "baike.sogou.com" ), StatFrom::new("360", StatFromType::Referer as i16, "so.com/link"), StatFrom::new( "360推广", StatFromType::Referer as i16, "so.com/search/eclk" ), StatFrom::new("神马搜索",StatFromType::Referer as i16,"sm.cn/adclick?url="), StatFrom::new("Bing", StatFromType::Referer as i16, ".bing.com"), StatFrom::new("Google", StatFromType::Referer as i16, ".google."), StatFrom::new("今日头条", StatFromType::Referer as i16, ".toutiao.com"), StatFrom::new("今日惠州", StatFromType::Referer as i16, ".huizhou.cn"), StatFrom::new("360推广", StatFromType::Host as i16, "mf.baolibao.cn"), StatFrom::new("UC",StatFromType::Host as i16,"daili.meizhuli365.com"), ]; }
use crate::mechanics::damage::DamageMultiplier; use crate::mechanics::Multiplier; mod effectiveness; #[derive(Debug, Eq, PartialEq, Hash)] pub enum MonsterType { FIRE, PLANT, WATER, } impl AsRef<MonsterType> for MonsterType { fn as_ref(&self) -> &MonsterType { self } } impl MonsterType { pub fn calculate_damage_multiplier<T: AsRef<MonsterType>>( receiver_primary_type: MonsterType, receiver_secondary_type: Option<MonsterType>, damage_type: T, ) -> DamageMultiplier { let eff_primary = damage_type .as_ref() .effectiveness_on_type(receiver_primary_type.as_ref()); let eff_secondary = match receiver_secondary_type.as_ref() { Some(t) => damage_type.as_ref().effectiveness_on_type(t), None => DamageMultiplier::SINGLE, }; DamageMultiplier::combine(eff_primary, eff_secondary).unwrap_or_else(|_| { panic!( "failed to combine {:?} with {:?}", receiver_primary_type, receiver_secondary_type ) }) } } #[cfg(test)] mod tests { use crate::mechanics::damage::DamageMultiplier; use crate::types::MonsterType; #[test] fn test_calculate_damage_multiplier_secondary_none() { assert_eq!( DamageMultiplier::DOUBLE, MonsterType::calculate_damage_multiplier(MonsterType::WATER, None, MonsterType::PLANT) ) } #[test] fn test_calculate_damage_multiplier_secondary_present() { assert_eq!( DamageMultiplier::SINGLE, MonsterType::calculate_damage_multiplier( MonsterType::WATER, Some(MonsterType::FIRE), MonsterType::PLANT, ) ) } }
extern crate chrono; extern crate iso6937; extern crate nom; use std::fmt; use std::fs::File; use std::io; use std::io::prelude::*; use std::str; use codepage_strings::Coding; pub mod parser; use crate::parser::parse_stl_from_slice; pub use crate::parser::ParseError; // STL File #[derive(Debug)] pub struct Stl { pub gsi: GsiBlock, pub ttis: Vec<TtiBlock>, } impl fmt::Display for Stl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}\n{:?}\n", self.gsi, self.ttis) } } pub struct TtiFormat { #[doc = "Justification Code"] pub jc: u8, #[doc = "Vertical Position"] pub vp: u8, #[doc = "Double Height"] pub dh: bool, } impl Stl { pub fn new() -> Stl { Stl { gsi: GsiBlock::new(), ttis: vec![], } } pub fn write_to_file(&self, filename: &str) -> Result<(), io::Error> { let mut f = File::create(filename)?; f.write_all(&self.gsi.serialize())?; for tti in self.ttis.iter() { f.write_all(&tti.serialize())?; } Ok(()) } pub fn add_sub(&mut self, tci: Time, tco: Time, txt: &str, opt: TtiFormat) { if txt.len() > 112 { //TODO: if txt.len() > 112 split in multiple println!("Warning: sub text is too long!"); } self.gsi.tnb += 1; // First TTI has sn=1 let tti = TtiBlock::new(self.gsi.tnb, tci, tco, txt, opt); self.gsi.tns += 1; self.ttis.push(tti); } } impl Default for Stl { fn default() -> Self { Self::new() } } pub fn parse_stl_from_file(filename: &str) -> Result<Stl, ParseError> { let mut f = File::open(filename)?; let mut buffer = vec![]; f.read_to_end(&mut buffer)?; parse_stl_from_slice(&buffer) } struct CodePageDecoder { coding: Coding, } impl CodePageDecoder { pub fn new(codepage: u16) -> Result<Self, ParseError> { Ok(Self { coding: Coding::new(codepage).map_err(|_e| ParseError::CodePageNumber(codepage))?, }) } fn parse(&self, data: &[u8]) -> Result<String, ParseError> { Ok(self.coding.decode_lossy(data).to_string()) } } // GSI Block #[derive(Debug)] #[allow(non_camel_case_types)] pub enum CodePageNumber { CPN_437, CPN_850, CPN_860, CPN_863, CPN_865, } impl CodePageNumber { fn serialize(&self) -> Vec<u8> { match *self { CodePageNumber::CPN_437 => vec![0x34, 0x33, 0x37], CodePageNumber::CPN_850 => vec![0x38, 0x35, 0x30], CodePageNumber::CPN_860 => vec![0x38, 0x36, 0x30], CodePageNumber::CPN_863 => vec![0x38, 0x36, 0x33], CodePageNumber::CPN_865 => vec![0x38, 0x36, 0x35], } } pub(crate) fn from_u16(codepage: u16) -> Result<CodePageNumber, ParseError> { match codepage { 437 => Ok(CodePageNumber::CPN_437), 850 => Ok(CodePageNumber::CPN_850), 860 => Ok(CodePageNumber::CPN_860), 863 => Ok(CodePageNumber::CPN_863), 865 => Ok(CodePageNumber::CPN_865), _ => Err(ParseError::CodePageNumber(codepage)), } } } #[derive(Debug)] pub enum DisplayStandardCode { Blank, OpenSubtitling, Level1Teletext, Level2Teletext, } impl DisplayStandardCode { fn parse(data: u8) -> Result<DisplayStandardCode, ParseError> { match data { 0x20 => Ok(DisplayStandardCode::Blank), 0x30 => Ok(DisplayStandardCode::OpenSubtitling), 0x31 => Ok(DisplayStandardCode::Level1Teletext), 0x32 => Ok(DisplayStandardCode::Level2Teletext), _ => Err(ParseError::DisplayStandardCode), } } fn serialize(&self) -> u8 { match *self { DisplayStandardCode::Blank => 0x20, DisplayStandardCode::OpenSubtitling => 0x30, DisplayStandardCode::Level1Teletext => 0x31, DisplayStandardCode::Level2Teletext => 0x32, } } } #[derive(Debug)] pub enum TimeCodeStatus { NotIntendedForUse, IntendedForUse, } impl TimeCodeStatus { fn parse(data: u8) -> Result<TimeCodeStatus, ParseError> { match data { 0x30 => Ok(TimeCodeStatus::NotIntendedForUse), 0x31 => Ok(TimeCodeStatus::IntendedForUse), _ => Err(ParseError::TimeCodeStatus), } } fn serialize(&self) -> u8 { match *self { TimeCodeStatus::NotIntendedForUse => 0x30, TimeCodeStatus::IntendedForUse => 0x31, } } } #[derive(Debug)] pub enum CharacterCodeTable { Latin, LatinCyrillic, LatinArabic, LatinGreek, LatinHebrew, } impl CharacterCodeTable { fn parse(data: &[u8]) -> Result<CharacterCodeTable, ParseError> { if data.len() != 2 { return Err(ParseError::CharacterCodeTable); } if data[0] != 0x30 { return Err(ParseError::CharacterCodeTable); } match data[1] { 0x30 => Ok(CharacterCodeTable::Latin), 0x31 => Ok(CharacterCodeTable::LatinCyrillic), 0x32 => Ok(CharacterCodeTable::LatinArabic), 0x33 => Ok(CharacterCodeTable::LatinGreek), 0x34 => Ok(CharacterCodeTable::LatinHebrew), _ => Err(ParseError::CharacterCodeTable), } } fn serialize(&self) -> Vec<u8> { match *self { CharacterCodeTable::Latin => vec![0x30, 0x30], CharacterCodeTable::LatinCyrillic => vec![0x30, 0x31], CharacterCodeTable::LatinArabic => vec![0x30, 0x32], CharacterCodeTable::LatinGreek => vec![0x30, 0x33], CharacterCodeTable::LatinHebrew => vec![0x30, 0x34], } } } #[derive(Debug)] #[allow(non_camel_case_types)] pub enum DiskFormatCode { STL25_01, STL30_01, } impl DiskFormatCode { fn parse(data: &str) -> Result<DiskFormatCode, ParseError> { if data == "STL25.01" { Ok(DiskFormatCode::STL25_01) } else if data == "STL30.01" { Ok(DiskFormatCode::STL30_01) } else { Err(ParseError::DiskFormatCode(data.to_string())) } } fn serialize(&self) -> Vec<u8> { match *self { DiskFormatCode::STL25_01 => String::from("STL25.01").into_bytes(), DiskFormatCode::STL30_01 => String::from("STL30.01").into_bytes(), } } pub fn get_fps(&self) -> usize { match self { DiskFormatCode::STL25_01 => 25, DiskFormatCode::STL30_01 => 30, } } } #[derive(Debug)] pub struct GsiBlock { #[doc = "0..2 Code Page Number"] cpn: CodePageNumber, #[doc = "3..10 Disk Format Code"] dfc: DiskFormatCode, #[doc = "11 Display Standard Code"] dsc: DisplayStandardCode, #[doc = "12..13 Character Code Table Number"] cct: CharacterCodeTable, #[doc = "14..15 Language Code"] lc: String, #[doc = "16..47 Original Program Title"] opt: String, #[doc = "48..79 Original Episode Title"] oet: String, #[doc = "80..111 Translated Program Title"] tpt: String, #[doc = "112..143 Translated Episode Title"] tet: String, #[doc = "144..175 Translator's Name"] tn: String, #[doc = "176..207 Translator's Contact Details"] tcd: String, #[doc = "208..223 Subtitle List Reference Code"] slr: String, #[doc = "224..229 Creation Date"] cd: String, #[doc = "230..235 Revision Date"] rd: String, #[doc = "236..237 Revision Number"] rn: String, #[doc = "238..242 Total Number of Text and Timing Blocks"] tnb: u16, #[doc = "243..247 Total Number of Subtitles"] tns: u16, #[doc = "248..250 Total Number of Subtitle Groups"] tng: u16, #[doc = "251..252 Maximum Number of Displayable Characters in a Text Row"] mnc: u16, #[doc = "253..254 Maximum Number of Displayable Rows"] mnr: u16, #[doc = "255 Time Code Status"] tcs: TimeCodeStatus, #[doc = "256..263 Time Code: Start of Programme (format: HHMMSSFF)"] tcp: String, #[doc = "264..271 Time Code: First-in-Cue (format: HHMMSSFF)"] tcf: String, #[doc = "272 Total Number of Disks"] tnd: u8, #[doc = "273 Disk Sequence Number"] dsn: u8, #[doc = "274..276 Country of Origin"] co: String, // TODO Type with country definitions #[doc = "277..308 Publisher"] pub_: String, #[doc = "309..340 Editor's Name"] en: String, #[doc = "341..372 Editor's Contact Details"] ecd: String, #[doc = "373..447 Spare Bytes"] _spare: String, #[doc = "448..1023 User-Defined Area"] uda: String, } impl GsiBlock { pub fn get_code_page_number(&self) -> &CodePageNumber { &self.cpn } pub fn get_disk_format_code(&self) -> &DiskFormatCode { &self.dfc } pub fn get_display_standard_code(&self) -> &DisplayStandardCode { &self.dsc } pub fn get_character_code_table(&self) -> &CharacterCodeTable { &self.cct } pub fn get_language_code(&self) -> &str { &self.lc } pub fn get_original_program_title(&self) -> &str { &self.opt } pub fn get_original_episode_title(&self) -> &str { &self.oet } pub fn get_translated_program_title(&self) -> &str { &self.tpt } pub fn get_translated_episode_title(&self) -> &str { &self.tet } pub fn get_translators_name(&self) -> &str { &self.tn } pub fn get_translators_contact_details(&self) -> &str { &self.tcd } pub fn get_subtitle_list_reference_code(&self) -> &str { &self.slr } pub fn get_creation_date(&self) -> &str { &self.cd } pub fn get_revision_date(&self) -> &str { &self.rd } pub fn get_revision_number(&self) -> &str { &self.rn } pub fn get_total_number_of_text_and_timing_blocks(&self) -> u16 { self.tnb } pub fn get_total_number_of_subtitles(&self) -> u16 { self.tns } pub fn get_total_number_of_chars_in_row(&self) -> u16 { self.tng } pub fn get_max_number_of_chars_in_row(&self) -> u16 { self.mnc } pub fn get_max_number_of_rows(&self) -> u16 { self.mnr } pub fn get_timecode_status(&self) -> &TimeCodeStatus { &self.tcs } pub fn get_timecode_start_of_program(&self) -> &str { &self.tcp } pub fn get_timecode_first_in_cue(&self) -> &str { &self.tcf } pub fn get_total_number_of_disks(&self) -> u8 { self.tnd } pub fn get_disk_sequence_number(&self) -> u8 { self.dsn } pub fn get_country_of_origin(&self) -> &str { &self.co } pub fn get_publisher(&self) -> &str { &self.pub_ } pub fn get_editors_name(&self) -> &str { &self.en } pub fn get_editors_contact_details(&self) -> &str { &self.ecd } pub fn get_user_defined_area(&self) -> &str { &self.uda } } fn push_string(v: &mut Vec<u8>, s: &str, len: usize) { let addendum = s.to_owned().into_bytes(); let padding = len - addendum.len(); v.extend(addendum.iter().cloned()); v.extend(vec![0x20u8; padding]); } impl GsiBlock { pub fn new() -> GsiBlock { let date = chrono::Local::now(); let now = date.format("%y%m%d").to_string(); GsiBlock { cpn: CodePageNumber::CPN_850, dfc: DiskFormatCode::STL25_01, dsc: DisplayStandardCode::Level1Teletext, cct: CharacterCodeTable::Latin, lc: "0F".to_string(), // FIXME: ok for default? opt: "".to_string(), oet: "".to_string(), tpt: "".to_string(), tet: "".to_string(), tn: "".to_string(), tcd: "".to_string(), slr: "".to_string(), cd: now.clone(), rd: now, rn: "00".to_string(), tnb: 0, tns: 0, tng: 1, // At least one group? mnc: 40, // FIXME: ok for default? mnr: 23, // FIXME: ok for default? tcs: TimeCodeStatus::IntendedForUse, tcp: "00000000".to_string(), tcf: "00000000".to_string(), tnd: 1, dsn: 1, co: "".to_string(), pub_: "".to_string(), en: "".to_string(), ecd: "".to_string(), _spare: "".to_string(), uda: "".to_string(), } } fn serialize(&self) -> Vec<u8> { let mut res = Vec::with_capacity(1024); res.extend(self.cpn.serialize()); res.extend(self.dfc.serialize().iter().cloned()); res.push(self.dsc.serialize()); res.extend(self.cct.serialize()); // be careful for the length of following: must force padding push_string(&mut res, &self.lc, 15 - 14 + 1); push_string(&mut res, &self.opt, 47 - 16 + 1); push_string(&mut res, &self.oet, 79 - 48 + 1); push_string(&mut res, &self.tpt, 111 - 80 + 1); push_string(&mut res, &self.tet, 143 - 112 + 1); push_string(&mut res, &self.tn, 175 - 144 + 1); push_string(&mut res, &self.tcd, 207 - 176 + 1); push_string(&mut res, &self.slr, 223 - 208 + 1); push_string(&mut res, &self.cd, 229 - 224 + 1); push_string(&mut res, &self.rd, 235 - 230 + 1); push_string(&mut res, &self.rn, 237 - 236 + 1); push_string(&mut res, &format!("{:05}", self.tnb), 242 - 238 + 1); push_string(&mut res, &format!("{:05}", self.tns), 247 - 243 + 1); push_string(&mut res, &format!("{:03}", self.tng), 250 - 248 + 1); push_string(&mut res, &format!("{:02}", self.mnc), 252 - 251 + 1); push_string(&mut res, &format!("{:02}", self.mnr), 254 - 253 + 1); res.push(self.tcs.serialize()); push_string(&mut res, &self.tcp, 263 - 256 + 1); push_string(&mut res, &self.tcf, 271 - 264 + 1); push_string(&mut res, &format!("{:1}", self.tnd), 1); push_string(&mut res, &format!("{:1}", self.dsn), 1); push_string(&mut res, &self.co, 276 - 274 + 1); push_string(&mut res, &self.pub_, 308 - 277 + 1); push_string(&mut res, &self.en, 340 - 309 + 1); push_string(&mut res, &self.ecd, 372 - 341 + 1); push_string(&mut res, &self._spare, 447 - 373 + 1); push_string(&mut res, &self.uda, 1023 - 448 + 1); res } } impl Default for GsiBlock { fn default() -> Self { Self::new() } } impl fmt::Display for GsiBlock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "Program Title: {}\nEpisode Title: {}\ncct:{:?} lc:{}\n", self.opt, self.oet, self.cct, self.lc ) } } // TTI Block #[derive(Debug)] pub enum CumulativeStatus { NotPartOfASet, FirstInSet, IntermediateInSet, LastInSet, } impl CumulativeStatus { fn parse(d: u8) -> Result<CumulativeStatus, ParseError> { match d { 0 => Ok(CumulativeStatus::NotPartOfASet), 1 => Ok(CumulativeStatus::FirstInSet), 2 => Ok(CumulativeStatus::IntermediateInSet), 3 => Ok(CumulativeStatus::LastInSet), _ => Err(ParseError::CumulativeStatus), } } fn serialize(&self) -> u8 { match *self { CumulativeStatus::NotPartOfASet => 0, CumulativeStatus::FirstInSet => 1, CumulativeStatus::IntermediateInSet => 2, CumulativeStatus::LastInSet => 3, } } } pub enum Justification { Unchanged, Left, Centered, Right, } #[derive(Debug, PartialEq, Eq)] pub struct Time { pub hours: u8, pub minutes: u8, pub seconds: u8, pub frames: u8, } impl Time { fn new(h: u8, m: u8, s: u8, f: u8) -> Time { Time { hours: h, minutes: m, seconds: s, frames: f, } } pub fn format_fps(&self, fps: usize) -> String { format!( "{}:{}:{},{}", self.hours, self.minutes, self.seconds, self.frames as usize * 1000 / fps ) } fn serialize(&self) -> Vec<u8> { vec![self.hours, self.minutes, self.seconds, self.frames] } } impl fmt::Display for Time { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}:{}:{}/{})", self.hours, self.minutes, self.seconds, self.frames ) } } pub struct TtiBlock { #[doc = "0 Subtitle Group Number. 00h-FFh"] sgn: u8, #[doc = "1..2 Subtitle Number range. 0000h-FFFFh"] sn: u16, #[doc = "3 Extension Block Number. 00h-FFh"] ebn: u8, #[doc = "4 Cumulative Status. 00-03h"] cs: CumulativeStatus, #[doc = "5..8 Time Code In"] tci: Time, #[doc = "9..12 Time Code Out"] tco: Time, #[doc = "13 Vertical Position"] vp: u8, #[doc = "14 Justification Code"] jc: u8, #[doc = "15 Comment Flag"] cf: u8, #[doc = "16..127 Text Field"] tf: Vec<u8>, } impl TtiBlock { pub fn get_subtitle_group_number(&self) -> u8 { self.sgn } pub fn get_subtitle_number_range(&self) -> u16 { self.sn } pub fn get_extension_block_number(&self) -> u8 { self.ebn } pub fn get_cumulative_status(&self) -> &CumulativeStatus { &self.cs } pub fn get_time_code_in(&self) -> &Time { &self.tci } pub fn get_time_code_out(&self) -> &Time { &self.tco } pub fn get_vertical_position(&self) -> u8 { self.vp } pub fn get_justification_code(&self) -> u8 { self.jc } pub fn get_comment_flag(&self) -> u8 { self.cf } } impl TtiBlock { pub fn new(idx: u16, tci: Time, tco: Time, txt: &str, opt: TtiFormat) -> TtiBlock { TtiBlock { sgn: 0, sn: idx, ebn: 0xff, cs: CumulativeStatus::NotPartOfASet, tci, tco, vp: opt.vp, jc: opt.jc, cf: 0, tf: TtiBlock::encode_text(txt, opt.dh), } } fn encode_text(txt: &str, dh: bool) -> Vec<u8> { const TF_LENGTH: usize = 112; let text = iso6937::encode(txt); let mut res = Vec::with_capacity(TF_LENGTH); if dh { res.push(0x0d); } res.push(0x0b); res.push(0x0b); res.extend(text); // Make sure size does not exceeds 112 bytes, FIXME: and what if! let max_size = TF_LENGTH - 3; // 3 trailing teletext codes to add. if res.len() > max_size { println!("!!! subtitle length is too long, truncating!"); } res.truncate(max_size); res.push(0x0A); res.push(0x0A); res.push(0x8A); let padding = TF_LENGTH - res.len(); res.extend(vec![0x8Fu8; padding]); res } pub fn get_text(&self) -> String { let mut result = String::from(""); let mut first = 0; for i in 0..self.tf.len() { let c = self.tf[i]; if match c { 0x0..=0x1f => true, //TODO: decode teletext control codes 0x20..=0x7f => false, 0x80..=0x9f => true, // TODO: decode codes 0xa0..=0xff => false, } { if first != i { result.push_str(&iso6937::decode(&self.tf[first..i])); } if c == 0x8f { break; } else if c == 0x8a { result.push_str("\r\n"); } first = i + 1; } } result } #[allow(clippy::vec_init_then_push)] fn serialize(&self) -> Vec<u8> { let mut res = vec![]; res.push(self.sgn); res.push((self.sn & 0xff) as u8); res.push((self.sn >> 8) as u8); res.push(self.ebn); res.push(self.cs.serialize()); res.extend(self.tci.serialize().iter().cloned()); res.extend(self.tco.serialize().iter().cloned()); res.push(self.vp); res.push(self.jc); res.push(self.cf); res.extend(self.tf.iter().cloned()); res } } impl fmt::Debug for TtiBlock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "\n{}-->{} sgn:{} sn:{} ebn:{} cs:{:?} vp:{} jc:{} cf:{} [{}]", self.tci, self.tco, self.sgn, self.sn, self.ebn, self.cs, self.vp, self.jc, self.cf, self.get_text() ) } } impl fmt::Display for TtiBlock { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "\n{} {} {} {} {:?} [{}]", self.tci, self.sgn, self.sn, self.ebn, self.cs, self.get_text() ) } }
use std::collections::HashMap; struct Solution {} impl Solution { /// @param n : the number of nodes in the tree /// @param edges: [a_i, b_i] elements, describe an edge a -- b /// @return a list of all root nodes that form minimum height trees fn find_min_height_trees(n: i32, edges: Vec<Vec<i32>>) -> Vec<i32> { if n == 1 { return vec![0]; } let mut total = 0; let mut height = f64::log2(n as f64).ceil() as i32; let mut heights = vec![height; n as usize]; let mut neighbors: HashMap<i32, Vec<i32>> = HashMap::new(); for edge in edges { let x = edge[0]; let y = edge[1]; neighbors.entry(x).or_insert(vec![]).push(y); neighbors.entry(y).or_insert(vec![]).push(x); } for root in 0..n { let mut visited = vec![0; n as usize]; visited[root as usize] = 1; let h = Solution::depth_first_search(root, 1, height, &neighbors, &mut visited); heights[root as usize] = h; height = if height < h { height } else if height == h { total += 1; h } else { total = 1; h }; if total > 2 { height = height - 1; total = 0; } } let mut answer = vec![]; for root in 0..n { if heights[root as usize] == height { answer.push(root); } } answer } fn depth_first_search( node: i32, cur_height: i32, cur_min_height: i32, neighbors: &HashMap<i32, Vec<i32>>, visited: &mut Vec<i32>, ) -> i32 { if cur_height > cur_min_height { return cur_min_height + 1; } let mut height = cur_height; for neighbor in &neighbors[&node] { let i = *neighbor as usize; if visited[i] != 0 { continue; } visited[i] = 1; let h = Solution::depth_first_search( *neighbor, cur_height + 1, cur_min_height, neighbors, visited, ); height = if height > h { height } else { h }; } height } } fn main() { let n = 6; let edges: Vec<Vec<i32>> = vec![vec![3, 0], vec![3, 1], vec![3, 2], vec![3, 4], vec![5, 4]]; // let n = 2; // let edges: Vec<Vec<i32>> = vec![vec![0, 1]]; println!("{:#?}", Solution::find_min_height_trees(n, edges)); // println!("{}", f64::log2(3.0)); }
#![allow(dead_code)] use block_on_proc::block_on; struct Tokio {} struct AsyncStd {} #[block_on("tokio")] impl Tokio { async fn test_async(&self) {} async fn test_async_static() {} async fn test_async_mut(&mut self) {} async fn test_async_arg(&self, _i: u8) {} async fn test_async_static_arg(_i: u8) {} async fn test_async_pointer_arg(&self, _i: &u8) {} // Fails with mut in argument // async fn test_async_pointer_arg(&self, mut _i: u8) {} async fn test_async_static_pointer_arg(_i: &u8) {} async fn test_async_args(&self, _i: u8, _j: u8, _k: u8) {} async fn test_async_static_args(_i: u8, _j: u8, _k: u8) {} async fn test_async_pointer_args(&self, _i: u8, _j: &u8, _k: &mut u8) {} async fn test_async_static_pointer_args(_i: u8, _j: &u8, _k: &mut u8) {} } #[block_on("async-std")] impl AsyncStd { async fn test_async(&self) {} async fn test_async_static() {} async fn test_async_mut(&mut self) {} async fn test_async_arg(&self, _i: u8) {} async fn test_async_static_arg(_i: u8) {} async fn test_async_pointer_arg(&self, _i: &u8) {} // Fails with mut in argument // async fn test_async_pointer_arg(&self, mut _i: u8) {} async fn test_async_static_pointer_arg(_i: &u8) {} async fn test_async_args(&self, _i: u8, _j: u8, _k: u8) {} async fn test_async_static_args(_i: u8, _j: u8, _k: u8) {} async fn test_async_pointer_args(&self, _i: u8, _j: &u8, _k: &mut u8) {} async fn test_async_static_pointer_args(_i: u8, _j: &u8, _k: &mut u8) {} } fn main() {}
use std::io::Read; use reqwest::StatusCode; use reqwest::blocking::Response; use crate::error::Result; #[derive(Debug, Clone)] pub struct Client { host: String, } impl Client { pub fn new(host: String) -> Self { Client { host } } // pub fn post(&self, endpoint: &str) -> Result<String> { // let url: String = format!("{}{}", self.host, endpoint); // // let client = reqwest::blocking::Client::new(); // let response = client // .post(url.as_str()) // // .headers(self.build_headers(false)?) // .send()?; // // self.handler(response) // } // // // fn handler(&self, mut response: Response) -> Result<String> { // match response.status() { // StatusCode::OK => { // let mut body = String::new(); // response.read_to_string(&mut body)?; // Ok(body) // } // } // } }
//! Robust implementation of `GraphicsDisplay` using Google's Skia. //! From https://github.com/jazzfool/reclutch/ //! MIT licensed extern crate gl; use { skia_safe as sk, std::collections::HashMap, }; mod error; /// Contains information about an existing OpenGL framebuffer. #[derive(Debug, Clone, Copy)] pub struct SkiaOpenGlFramebuffer { pub size: (i32, i32), pub framebuffer_id: u32, } /// Contains information about an existing OpenGL texture. #[derive(Debug, Clone, Copy)] pub struct SkiaOpenGlTexture { pub size: (i32, i32), pub mip_mapped: bool, pub texture_id: u32, } pub enum SurfaceType { OpenGlFramebuffer(SkiaOpenGlFramebuffer), OpenGlTexture(SkiaOpenGlTexture), } enum Resource { Image(sk::Image), Font(sk::Typeface), } /// Converts [`DisplayCommand`](crate::display::DisplayCommand) to immediate-mode Skia commands. pub struct SkiaGraphicsDisplay { pub surface: sk::Surface, pub surface_type: SurfaceType, pub context: sk::gpu::Context, next_command_group_id: u64, resources: HashMap<u64, Resource>, next_resource_id: u64, } impl SkiaGraphicsDisplay { /// Creates a new [`SkiaGraphicsDisplay`](SkiaGraphicsDisplay) with the Skia OpenGL backend, drawing into an existing framebuffer. /// This assumes that an OpenGL context has already been set up. /// This also assumes that the color format is RGBA with 8-bit components. pub fn new_gl_framebuffer(target: &SkiaOpenGlFramebuffer) -> Result<Self, error::SkiaError> { let (surface, context) = Self::new_gl_framebuffer_surface(target)?; Ok(Self { surface, surface_type: SurfaceType::OpenGlFramebuffer(*target), context, next_command_group_id: 0, resources: HashMap::new(), next_resource_id: 0, }) } /// Creates a new [`SkiaGraphicsDisplay`](SkiaGraphicsDisplay) with the Skia OpenGL backend, drawing into an existing texture. /// This assumes that an OpenGL context has already been set up. /// This also assumes that the color format is RGBA with 8-bit components pub fn new_gl_texture(target: &SkiaOpenGlTexture) -> Result<Self, error::SkiaError> { let (surface, context) = Self::new_gl_texture_surface(target)?; Ok(Self { surface, surface_type: SurfaceType::OpenGlTexture(*target), context, next_command_group_id: 0, resources: HashMap::new(), next_resource_id: 0, }) } /// Returns the size of the underlying surface. pub fn size(&self) -> (i32, i32) { match self.surface_type { SurfaceType::OpenGlFramebuffer(SkiaOpenGlFramebuffer { size, .. }) | SurfaceType::OpenGlTexture(SkiaOpenGlTexture { size, .. }) => size, } } fn new_gl_framebuffer_surface( target: &SkiaOpenGlFramebuffer, ) -> Result<(sk::Surface, sk::gpu::Context), error::SkiaError> { let mut context = Self::new_gl_context()?; Ok((SkiaGraphicsDisplay::new_gl_framebuffer_from_context(target, &mut context)?, context)) } fn new_gl_framebuffer_from_context( target: &SkiaOpenGlFramebuffer, context: &mut sk::gpu::Context, ) -> Result<sk::Surface, error::SkiaError> { let info = sk::gpu::BackendRenderTarget::new_gl( target.size, None, 8, sk::gpu::gl::FramebufferInfo { fboid: target.framebuffer_id, format: gl::RGBA8 }, ); Ok(sk::Surface::from_backend_render_target( context, &info, sk::gpu::SurfaceOrigin::BottomLeft, sk::ColorType::RGBA8888, sk::ColorSpace::new_srgb(), None, ) .ok_or_else(|| error::SkiaError::InvalidTarget(String::from("framebuffer")))?) } fn new_gl_texture_surface( target: &SkiaOpenGlTexture, ) -> Result<(sk::Surface, sk::gpu::Context), error::SkiaError> { let mut context = Self::new_gl_context()?; Ok((SkiaGraphicsDisplay::new_gl_texture_from_context(target, &mut context)?, context)) } fn new_gl_texture_from_context( target: &SkiaOpenGlTexture, context: &mut sk::gpu::Context, ) -> Result<sk::Surface, error::SkiaError> { let info = unsafe { sk::gpu::BackendTexture::new_gl( target.size, if target.mip_mapped { sk::gpu::MipMapped::Yes } else { sk::gpu::MipMapped::No }, sk::gpu::gl::TextureInfo { format: gl::RGBA8, target: gl::TEXTURE_2D, id: target.texture_id, }, ) }; Ok(sk::Surface::from_backend_texture( context, &info, sk::gpu::SurfaceOrigin::BottomLeft, None, sk::ColorType::RGBA8888, sk::ColorSpace::new_srgb(), None, ) .ok_or_else(|| error::SkiaError::InvalidTarget(String::from("texture")))?) } fn new_gl_context() -> Result<sk::gpu::Context, error::SkiaError> { sk::gpu::Context::new_gl(sk::gpu::gl::Interface::new_native()) .ok_or(error::SkiaError::InvalidContext) } }
//! A sound API that allows playing clips at given volumes //! //! On the desktop, currently all sounds are loaded into memory, but streaming sounds may be //! introduced in the future. On the web, it can be different from browser to browser use crate::{ Result, error::QuicksilverError, }; use futures::{Future, future}; use std::{ error::Error, fmt, io::Error as IOError, path::Path }; #[cfg(not(target_arch="wasm32"))] use { rodio::{ self, decoder::{Decoder, DecoderError}, source::{SamplesConverter, Source,Amplify}, }, std::{ fs::File, io::{Cursor, Read}, sync::Arc } }; #[cfg(target_arch="wasm32")] use { futures::Async, std::io::ErrorKind, stdweb::{ unstable::TryInto, Value } }; /// A clip of sound, which may be streamed from disc or stored in memory /// /// It can be played an arbitrary amount of times and concurrently with itself, meaning you don't /// need more than one instance of a clip. However, if you want different clips with different /// volumes, you can clone the Sound. #[derive(Clone, Debug)] pub struct Sound { #[cfg(not(target_arch="wasm32"))] val: Arc<Vec<u8>>, #[cfg(target_arch="wasm32")] sound: Value, volume: f32 } #[cfg(target_arch="wasm32")] fn wasm_sound_error(error: &str) -> QuicksilverError { let error = IOError::new(ErrorKind::NotFound, error); let error: SoundError = error.into(); error.into() } impl Sound { /// Start loading a sound from a given path pub fn load(path: impl AsRef<Path>) -> impl Future<Item = Sound, Error = QuicksilverError> { Sound::load_impl(path.as_ref()) } #[cfg(not(target_arch="wasm32"))] fn load_impl(path: &Path) -> impl Future<Item = Sound, Error = QuicksilverError> { future::result(load(path)) } #[cfg(target_arch="wasm32")] fn load_impl(path: &Path) -> impl Future<Item = Sound, Error = QuicksilverError> { let sound = js! { const audio = new Audio(@{path.to_str().expect("Path must be stringifiable")}); audio.hasError = false; audio.onerror = (error) => audio.hasError = true; return audio; }; future::poll_fn(move || { let error = js! ( return @{&sound}.hasError ).try_into(); let ready = js! ( return @{&sound}.readyState ).try_into(); match (error, ready) { (Ok(false), Ok(4)) => Ok(Async::Ready(Sound { sound: sound.clone(), volume: 1f32 })), (Ok(true), _) => Err(wasm_sound_error("Sound file not found or could not load")), (Ok(false), Ok(_)) => Ok(Async::NotReady), (Err(_), _) => Err(wasm_sound_error("Checking sound network state failed")), (_, Err(_)) => Err(wasm_sound_error("Checking sound ready state failed")), } }) } /// Get the volume of the sound clip instance /// /// The volume is multiplicative, meaing 1 is the identity, 0 is silent, 2 is twice the /// amplitude, etc. Note that sound is not perceived linearly so results may not correspond as /// expected. pub fn volume(&self) -> f32 { self.volume } /// Set the volume of the sound clip instance /// /// The volume is multiplicative, meaing 1 is the identity, 0 is silent, 2 is twice the /// amplitude, etc. Note that sound is not perceived linearly so results may not correspond as /// expected. pub fn set_volume(&mut self, volume: f32) { self.volume = volume; } #[cfg(not(target_arch="wasm32"))] fn get_source(&self) -> Result<SamplesConverter<Amplify<Decoder<Cursor<Sound>>>, f32>> { Ok(Decoder::new(Cursor::new(self.clone()))?.amplify(self.volume).convert_samples()) } /// Play the sound clip at its current volume /// /// The sound clip can be played over itself. /// /// Future changes in volume will not change the sound emitted by this method. pub fn play(&self) -> Result<()> { #[cfg(not(target_arch="wasm32"))] { let device = match rodio::default_output_device() { Some(device) => device, None => return Err(SoundError::NoOutputAvailable.into()) }; rodio::play_raw(&device, self.get_source()?); } #[cfg(target_arch="wasm32")] js! { @{&self.sound}.cloneNode().play(); } Ok(()) } #[cfg(not(target_arch="wasm32"))] //Play a silent sound so rodio startup doesn't interfere with application //Unfortunately this means even apps that don't use sound eat the startup penalty but it's not a //huge one pub(crate) fn initialize() { if let Some(ref device) = rodio::default_output_device() { rodio::play_raw(device, rodio::source::Empty::new()) } } } #[cfg(not(target_arch="wasm32"))] fn load(path: &Path) -> Result<Sound> { let mut bytes = Vec::new(); File::open(path)?.read_to_end(&mut bytes)?; let val = Arc::new(bytes); let sound = Sound { val, volume: 1f32 }; Decoder::new(Cursor::new(sound.clone()))?; Ok(sound) } #[doc(hidden)] #[cfg(not(target_arch="wasm32"))] impl AsRef<[u8]> for Sound { fn as_ref(&self) -> &[u8] { self.val.as_ref().as_ref() } } #[derive(Debug)] /// An error generated when loading a sound pub enum SoundError { /// The sound file is not in an format that can be played UnrecognizedFormat, /// No output device was found to play the sound NoOutputAvailable, /// The Sound was not found or could not be loaded IOError(IOError) } impl fmt::Display for SoundError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.description()) } } impl Error for SoundError { fn description(&self) -> &str { match self { SoundError::UnrecognizedFormat => "The sound file format was not recognized", SoundError::NoOutputAvailable => "There was no output device available for playing", SoundError::IOError(err) => err.description() } } fn cause(&self) -> Option<&dyn Error> { match self { SoundError::UnrecognizedFormat | SoundError::NoOutputAvailable => None, SoundError::IOError(err) => Some(err) } } } #[doc(hidden)] #[cfg(not(target_arch="wasm32"))] impl From<DecoderError> for SoundError { fn from(err: DecoderError) -> SoundError { match err { DecoderError::UnrecognizedFormat => SoundError::UnrecognizedFormat } } } #[doc(hidden)] impl From<IOError> for SoundError { fn from(err: IOError) -> SoundError { SoundError::IOError(err) } }
use logos::Logos; #[derive(Logos, Debug, PartialEq)] pub(crate) enum Token { #[regex("[a-zA-Z]+", |lex| String::from(lex.slice()))] Identifier(String), #[regex("-?[0-9]+(.[0-9]+)?", |lex| lex.slice().parse())] Number(f64), #[regex(r#""[^"]*""#, |lex| String::from(lex.slice()))] VString(String), #[regex("[\r\n]+")] #[regex(r"#[^\n]*\n")] NewLine, #[token("=")] Equal, #[token(",")] Comma, #[token("(")] LParen, #[token(")")] RParen, #[token("{")] LBrace, #[token("}")] RBrace, #[error] #[regex(r"[ \t\f]", logos::skip)] Error, }
//! The DcMotor provides a uniform interface for using //! regular DC motors with no fancy controls or feedback. //! This includes LEGO MINDSTORMS RCX motors and LEGO Power Functions motors. /// The DcMotor provides a uniform interface for using /// regular DC motors with no fancy controls or feedback. /// This includes LEGO MINDSTORMS RCX motors and LEGO Power Functions motors. #[macro_export] macro_rules! dc_motor { () => { /// Causes the motor to run until another command is sent. pub const COMMAND_RUN_FOREVER: &'static str = "run-forever"; /// Run the motor for the amount of time specified in `time_sp` /// and then stops the motor using the command specified by `stop_action`. pub const COMMAND_RUN_TIMED: &'static str = "run-timed"; /// Runs the motor using the duty cycle specified by `duty_cycle_sp`. /// Unlike other run commands, changing `duty_cycle_sp` while running will take effect immediately. pub const COMMAND_RUN_DIRECT: &'static str = "run-direct"; /// Stop any of the run commands before they are complete using the command specified by `stop_action`. pub const COMMAND_STOP: &'static str = "stop"; /// A positive duty cycle will cause the motor to rotate clockwise. pub const POLARITY_NORMAL: &'static str = "normal"; /// A positive duty cycle will cause the motor to rotate counter-clockwise. pub const POLARITY_INVERSED: &'static str = "inversed"; /// Power is being sent to the motor. pub const STATE_RUNNING: &'static str = "running"; /// The motor is ramping up or down and has not yet reached a pub constant output level. pub const STATE_RAMPING: &'static str = "ramping"; /// Removes power from the motor. The motor will freely coast to a stop. pub const STOP_ACTION_COAST: &'static str = "coast"; /// Removes power from the motor and creates a passive electrical load. /// This is usually done by shorting the motor terminals together. /// This load will absorb the energy from the rotation of the motors /// and cause the motor to stop more quickly than coasting. pub const STOP_ACTION_BRAKE: &'static str = "brake"; /// Returns the current duty cycle of the motor. Units are percent. Values are -100 to 100. pub fn get_duty_cycle(&self) -> Ev3Result<i32> { self.get_attribute("duty_cycle").get() } /// Returns the current duty cycle setpoint of the motor. Units are in percent. /// Valid values are -100 to 100. A negative value causes the motor to rotate in reverse. pub fn get_duty_cycle_sp(&self) -> Ev3Result<i32> { self.get_attribute("duty_cycle_sp").get() } /// Sets the duty cycle setpoint of the motor. Units are in percent. /// Valid values are -100 to 100. A negative value causes the motor to rotate in reverse. pub fn set_duty_cycle_sp(&self, duty_cycle_sp: i32) -> Ev3Result<()> { self.get_attribute("duty_cycle_sp").set(duty_cycle_sp) } /// Returns the current polarity of the motor. pub fn get_polarity(&self) -> Ev3Result<String> { self.get_attribute("polarity").get() } /// Sets the polarity of the motor. pub fn set_polarity(&self, polarity: &str) -> Ev3Result<()> { self.get_attribute("polarity").set_str_slice(polarity) } /// Returns the current ramp up setpoint. /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will increase from 0 to 100% of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and max_speed multiplied by ramp_up_sp. Values must not be negative. pub fn get_ramp_up_sp(&self) -> Ev3Result<i32> { self.get_attribute("ramp_up_sp").get() } /// Sets the ramp up setpoint. /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will increase from 0 to 100% of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and max_speed multiplied by ramp_up_sp. Values must not be negative. pub fn set_ramp_up_sp(&self, ramp_up_sp: i32) -> Ev3Result<()> { self.get_attribute("ramp_up_sp").set(ramp_up_sp) } /// Returns the current ramp down setpoint. /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will decrease from 100% down to 0 of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and 0 multiplied by ramp_down_sp. Values must not be negative. pub fn get_ramp_down_sp(&self) -> Ev3Result<i32> { self.get_attribute("ramp_down_sp").get() } /// Sets the ramp down setpoint. /// Units are in milliseconds and must be positive. When set to a non-zero value, /// the motor speed will decrease from 100% down to 0 of `max_speed` over the span of this setpoint. /// The actual ramp time is the ratio of the difference between the speed_sp /// and the current speed and 0 multiplied by ramp_down_sp. Values must not be negative. pub fn set_ramp_down_sp(&self, ramp_down_sp: i32) -> Ev3Result<()> { self.get_attribute("ramp_down_sp").set(ramp_down_sp) } /// Returns a list of state flags. pub fn get_state(&self) -> Ev3Result<Vec<String>> { self.get_attribute("state").get_vec() } /// Returns the current stop action. /// The value determines the motors behavior when command is set to stop. pub fn get_stop_action(&self) -> Ev3Result<String> { self.get_attribute("stop_action").get() } /// Sets the stop action. /// The value determines the motors behavior when command is set to stop. pub fn set_stop_action(&self, stop_action: &str) -> Ev3Result<()> { self.get_attribute("stop_action").set_str_slice(stop_action) } /// Returns the current amount of time the motor will run when using the run-timed command. /// Units are in milliseconds. Values must not be negative. pub fn get_time_sp(&self) -> Ev3Result<i32> { self.get_attribute("time_sp").get() } /// Sets the amount of time the motor will run when using the run-timed command. /// Units are in milliseconds. Values must not be negative. pub fn set_time_sp(&self, time_sp: i32) -> Ev3Result<()> { self.get_attribute("time_sp").set(time_sp) } /// Runs the motor using the duty cycle specified by `duty_cycle_sp`. /// Unlike other run commands, changing `duty_cycle_sp` while running will take effect immediately. pub fn run_direct(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_RUN_DIRECT) } /// Causes the motor to run until another command is sent. pub fn run_forever(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_RUN_FOREVER) } /// Run the motor for the amount of time specified in `time_sp` /// and then stops the motor using the command specified by `stop_action`. pub fn run_timed(&self, time_sp: Option<Duration>) -> Ev3Result<()> { if let Some(duration) = time_sp { let p = duration.as_millis() as i32; self.set_time_sp(p)?; } self.set_command(Self::COMMAND_RUN_TIMED) } /// Stop any of the run commands before they are complete using the command specified by `stop_action`. pub fn stop(&self) -> Ev3Result<()> { self.set_command(Self::COMMAND_STOP) } /// Power is being sent to the motor. pub fn is_running(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_RUNNING)) } /// The motor is ramping up or down and has not yet reached a pub constant output level. pub fn is_ramping(&self) -> Ev3Result<bool> { Ok(self .get_state()? .iter() .any(|state| state == Self::STATE_RAMPING)) } }; }
use super::InternalEvent; use metrics::counter; use std::fmt::Debug; #[derive(Debug)] pub struct WatchRequestInvoked; impl InternalEvent for WatchRequestInvoked { fn emit_metrics(&self) { counter!("k8s_watch_requests_invoked", 1); } } #[derive(Debug)] pub struct WatchRequestInvocationFailed<E> { pub error: E, } impl<E: Debug> InternalEvent for WatchRequestInvocationFailed<E> { fn emit_logs(&self) { error!(message = "watch invocation failed", error = ?self.error, rate_limit_secs = 5); } fn emit_metrics(&self) { counter!("k8s_watch_requests_failed", 1); } } #[derive(Debug)] pub struct WatchStreamItemObtained; impl InternalEvent for WatchStreamItemObtained { fn emit_metrics(&self) { counter!("k8s_watch_stream_items_obtained", 1); } } #[derive(Debug)] pub struct WatchStreamErrored<E> { pub error: E, } impl<E: Debug> InternalEvent for WatchStreamErrored<E> { fn emit_logs(&self) { error!(message = "watch stream errored", error = ?self.error, rate_limit_secs = 5); } fn emit_metrics(&self) { counter!("k8s_watch_stream_errors", 1); } }
extern crate libc; use std::rc::Rc; use std::ptr; use std::string::raw::from_buf; use std::iter::Iterator; use self::libc::{c_int,c_char,c_uchar}; use git2::error::{GitError, get_last_error}; pub mod opaque { pub enum Config {} pub enum ConfigIterator {} } extern { fn git_config_free(obj: *mut self::opaque::Config); fn git_config_get_bool(out: *mut c_int, obj: *const self::opaque::Config, name: *const c_char) -> c_int; fn git_config_get_string(out: *mut *mut c_char, obj: *const self::opaque::Config, name: *const c_char) -> c_int; fn git_config_get_entry(out: *mut *mut GitConfigEntryRaw, obj: *const self::opaque::Config, name: *const c_char) -> c_int; fn git_config_iterator_new(out: *mut *mut self::opaque::ConfigIterator, obj: *const self::opaque::Config) -> c_int; fn git_config_next(out: *mut *mut GitConfigEntryRaw, obj: *mut self::opaque::ConfigIterator) -> c_int; fn git_config_iterator_free(obj: *mut self::opaque::ConfigIterator); } #[repr(C)] #[deriving(Show)] pub enum GitConfigLevel { GIT_CONFIG_LEVEL_SYSTEM = 1, GIT_CONFIG_LEVEL_XDG = 2, GIT_CONFIG_LEVEL_GLOBAL = 3, GIT_CONFIG_LEVEL_LOCAL = 4, GIT_CONFIG_LEVEL_APP = 5, GIT_CONFIG_HIGHEST_LEVEL = -1, } struct GitConfigEntryRaw { name: *const c_uchar, value: *const c_uchar, level: GitConfigLevel } #[deriving(Show)] pub struct GitConfigEntry { pub name: String, pub value: String, pub level: GitConfigLevel } struct GitConfigPtr { _val: *mut self::opaque::Config } pub struct GitConfigIterator { _iter: *mut self::opaque::ConfigIterator } #[deriving(Clone)] pub struct Config { _ptr: Rc<GitConfigPtr> } impl Config { pub fn _get_ptr(&self) -> *const self::opaque::Config { self._ptr.deref()._val as *const self::opaque::Config } pub fn _new(p: *mut self::opaque::Config) -> Config { Config {_ptr : Rc::new(GitConfigPtr{_val:p})} } /// Get the value of a boolean config variable. /// /// This function uses the usual C convention of 0 being false and anything else true. /// /// All config files will be looked into, in the order of their defined level. A higher level /// means a higher priority. The first occurrence of the variable will be returned here. pub fn get_bool(&self, name: &str) -> Result<bool,GitError> { let mut val: c_int = -1; match unsafe { git_config_get_bool(&mut val, self._get_ptr(), name.to_c_str().as_ptr()) } { 0 => Ok(val == 1), _ => Err(get_last_error()) } } /// Get the value of a string config variable. /// /// All config files will be looked into, in the order of their defined level. A higher level /// means a higher priority. The first occurrence of the variable will be returned here pub fn get_string(&self, name: &str) -> Result<String,GitError> { let mut p: *mut c_char = ptr::mut_null(); unsafe { match git_config_get_string(&mut p, self._get_ptr(), name.to_c_str().as_ptr()) { 0 => Ok(from_buf(p as *const u8)), _ => Err(get_last_error()) } } } /// Get the git_config_entry of a config variable. pub fn get_entry(&self, name: &str) -> Result<GitConfigEntry,GitError> { let mut entryptr: *mut GitConfigEntryRaw = ptr::mut_null(); unsafe { if git_config_get_entry(&mut entryptr, self._get_ptr(), name.to_c_str().as_ptr()) != 0 { return Err(get_last_error()); } let deref: GitConfigEntryRaw = *entryptr; return Ok(GitConfigEntry{ name: from_buf(deref.name), value: from_buf(deref.value), level: deref.level }); } } /// Iterate over all the config variables pub fn iterator(&self) -> Result<GitConfigIterator,GitError> { let mut iter: *mut self::opaque::ConfigIterator = ptr::mut_null(); if unsafe { git_config_iterator_new(&mut iter, self._get_ptr()) } != 0 { return Err(get_last_error()); } return Ok(GitConfigIterator{_iter: iter}); } } impl Iterator<GitConfigEntry> for GitConfigIterator { fn next(&mut self) -> Option<GitConfigEntry> { let mut entryptr: *mut GitConfigEntryRaw = ptr::mut_null(); let ret = unsafe { git_config_next(&mut entryptr, self._iter) }; if ret == 0 { return unsafe { let deref: GitConfigEntryRaw = *entryptr; Some(GitConfigEntry{ name: from_buf(deref.name), value: from_buf(deref.value), level: deref.level }) } } else if ret == -31 { // iter over return None; } else { fail!("git_config_next failure! {}", get_last_error()); } } } impl Drop for GitConfigPtr { fn drop(&mut self) { println!("Dropping this config pointer!"); unsafe {git_config_free(self._val)} } } impl Drop for GitConfigIterator { fn drop(&mut self) { println!("Dropping this config iterator!"); unsafe {git_config_iterator_free(self._iter)} } }
//or.rs - opcodes for xor and inclusive or dealt with! use super::addressing::{self, Operation}; use crate::memory::{RAM, *}; pub fn xor_immediate( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, cycles_until_next: &mut u8, ) { *accumulator = addressing::immediate(*accumulator, operand, &mut status_flags, Operation::Eor); *pc_reg += 2; *cycles_until_next = 2; } pub fn xor_zero_page( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page( *accumulator, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 2; *cycles_until_next = 3; } pub fn xor_zero_page_x( operand: u8, x_reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page_x( *accumulator, x_reg, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 2; *cycles_until_next = 4; } pub fn xor_absolute( operand: u16, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute( *accumulator, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn xor_absolute_reg( operand: u16, reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute_reg( *accumulator, reg, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn xor_indexed_indirect( operand: u8, x_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indexed_indirect( *accumulator, x_val, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 2; *cycles_until_next = 6; } pub fn xor_indirect_indexed( operand: u8, y_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indirect_indexed( *accumulator, y_val, operand, memory, &mut status_flags, Operation::Eor, ); *pc_reg += 2; *cycles_until_next = 5; } pub fn ior_immediate( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, cycles_until_next: &mut u8, ) { *accumulator = addressing::immediate(*accumulator, operand, &mut status_flags, Operation::Ior); *pc_reg += 2; *cycles_until_next = 2; } pub fn ior_zero_page( operand: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page( *accumulator, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 2; *cycles_until_next = 3; } pub fn ior_zero_page_x( operand: u8, x_reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::zero_page_x( *accumulator, x_reg, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 2; *cycles_until_next = 4; } pub fn ior_absolute( operand: u16, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute( *accumulator, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn ior_absolute_reg( operand: u16, reg: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::absolute_reg( *accumulator, reg, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 3; *cycles_until_next = 4; } pub fn ior_indexed_indirect( operand: u8, x_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indexed_indirect( *accumulator, x_val, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 2; *cycles_until_next = 6; } pub fn ior_indirect_indexed( operand: u8, y_val: u8, pc_reg: &mut u16, accumulator: &mut u8, mut status_flags: &mut u8, memory: &mut RAM, cycles_until_next: &mut u8, ) { *accumulator = addressing::indirect_indexed( *accumulator, y_val, operand, memory, &mut status_flags, Operation::Ior, ); *pc_reg += 2; *cycles_until_next = 5; } #[cfg(test)] mod tests { use super::*; use crate::memory; #[test] pub fn test_or() { let operand = 7; let mut pc_reg = 0; let mut accumulator = 2; let mut status: u8 = 0; let mut test_memory: memory::RAM = memory::RAM::new(); let mut cycles = 0; // init mem for i in 0..512 { test_memory.write_mem_value(i * 2, 0 as u8); test_memory.write_mem_value(i * 2 + 1, i as u8); } for i in 512..1024 { test_memory.write_mem_value(i, i as u8); } ior_immediate(5, &mut pc_reg, &mut accumulator, &mut status, &mut cycles); assert_eq!(pc_reg, 2); assert_eq!(accumulator, 7); xor_immediate(7, &mut pc_reg, &mut accumulator, &mut status, &mut cycles); assert_eq!(pc_reg, 4); assert_eq!(accumulator, 0); assert_eq!(status, 2); status = 0; ior_zero_page( 11, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 6); assert_eq!(accumulator, 5); assert_eq!(status, 0); xor_zero_page( 5, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 8); assert_eq!(accumulator, 7); assert_eq!(status, 0); status = 0; ior_zero_page_x( 11, 2, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 10); assert_eq!(accumulator, 7); assert_eq!(status, 0); status = 0; accumulator = 0; xor_zero_page_x( 11, 2, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 12); assert_eq!(accumulator, 6); assert_eq!(status, 0); xor_zero_page_x( 255, 14, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 14); assert_eq!(accumulator, 0); assert_eq!(status, 2); status = 0; accumulator = 0; ior_absolute( 259, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 17); assert_eq!(accumulator, 129); assert_eq!(status, 64); status = 0; xor_absolute( 259, &mut pc_reg, &mut accumulator, &mut status, &mut test_memory, &mut cycles, ); assert_eq!(pc_reg, 20); assert_eq!(accumulator, 0); assert_eq!(status, 2); } }
pub mod card; pub use self::card::Suit; pub use self::card::Card; pub fn parse(cards: &str) -> Vec<Card> { cards .split(' ') .map(card::parse) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn it_parsers_string_into_a_card_list() { assert_eq!(parse("2H 4S AD"), vec![ Card { number: 2, suit: Suit::Hearts }, Card { number: 4, suit: Suit::Spades }, Card { number: 14, suit: Suit::Dimonds } ]); } }
use super::{Interceptor, InterceptorFuture, InterceptorObj}; use crate::{body::AsyncBody, error::Error}; use http::{Request, Response}; use std::{fmt, sync::Arc}; /// Execution context for an interceptor. pub struct Context<'a> { pub(crate) invoker: Arc<dyn Invoke + Send + Sync + 'a>, pub(crate) interceptors: &'a [InterceptorObj], } impl<'a> Context<'a> { /// Send a request asynchronously, executing the next interceptor in the /// chain, if any. pub async fn send(&self, request: Request<AsyncBody>) -> Result<Response<AsyncBody>, Error> { if let Some(interceptor) = self.interceptors.first() { let inner_context = Self { invoker: self.invoker.clone(), interceptors: &self.interceptors[1..], }; interceptor.intercept(request, inner_context).await } else { self.invoker.invoke(request).await } } } impl fmt::Debug for Context<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Context").finish() } } pub(crate) trait Invoke { fn invoke(&self, request: Request<AsyncBody>) -> InterceptorFuture<'_, Error>; }
use std::fs::File; use std::io::{BufRead, BufReader}; use std::collections::HashMap; fn dfs(directs: &HashMap<String, Vec<String>>, ctr: &str, dist_com: i32) -> (i32, i32, i32) { let (mut tot_com, mut dist_you, mut dist_san) = (dist_com, -1, -1); if let Some(orbits) = directs.get(ctr) { for arnd in orbits { let (tot_arnd, d_you, d_san) = dfs(directs, arnd, dist_com + 1); tot_com += tot_arnd; if arnd == "YOU" { dist_you = 0; } if arnd == "SAN" { dist_san = 0; } if d_you >= 0 && d_san >= 0 { dist_you = d_you; dist_san = d_san; } else if d_you >= 0 { dist_you = d_you + 1; } else if d_san >= 0 { dist_san = d_san + 1; } } } (tot_com, dist_you, dist_san) } fn main() { let mut directs: HashMap<_, Vec<String>> = HashMap::new(); for line in BufReader::new(File::open("in6.txt").unwrap()).lines().map(|line| line.unwrap()) { let sep = line.find(')').unwrap(); let (ctr, arnd) = (line[0..sep].to_string(), line[sep + 1 ..].to_string()); match directs.get_mut(&ctr) { Some(orbits) => orbits.push(arnd), None => { directs.insert(ctr, vec![arnd]); }, } } let (tot_com, dist_you, dist_san) = dfs(&directs, "COM", 0); println!("Part A: {}", tot_com); // 160040 println!("Part B: {}", dist_you + dist_san); // 373 }
#![no_std] #![no_main] use core::sync::atomic::{AtomicUsize, Ordering}; use cortex_m_rt::entry; use defmt::*; use defmt_rtt as _; // global logger use panic_probe as _; use rp2040_pac as pac; #[defmt::timestamp] fn timestamp() -> u64 { static COUNT: AtomicUsize = AtomicUsize::new(0); // NOTE(no-CAS) `timestamps` runs with interrupts disabled let n = COUNT.load(Ordering::Relaxed); COUNT.store(n + 1, Ordering::Relaxed); n as u64 } #[entry] fn main() -> ! { info!("Hello World!"); let p = pac::Peripherals::take().unwrap(); loop { info!("on!"); p.IO_BANK0.gpio25_ctrl.write(|w| { w.oeover().enable(); w.outover().high(); w }); cortex_m::asm::delay(64_000_000); info!("off!"); p.IO_BANK0.gpio25_ctrl.write(|w| { w.oeover().enable(); w.outover().low(); w }); cortex_m::asm::delay(64_000_000); } }
use super::*; pub struct Camera { origin: Point3, lower_left_corner: Point3, horizontal: Point3, vertical: Point3, u: Point3, v: Point3, _w: Point3, lens_radius: f64, } impl Camera { pub fn new( lookfrom: Point3, lookat: Point3, vup: Point3, vfov: Degrees, aspect_ratio: f64, aperture: f64, focus_dist: f64, ) -> Self { let theta: f64 = vfov.to_radians().into(); let h = (theta / 2.0).tan(); let viewport_height = 2.0 * h; let viewport_width: f64 = aspect_ratio * viewport_height; let w = (lookfrom - lookat).unit(); let u = vup.cross(&w).unit(); let v = w.cross(&u); let origin = lookfrom; let horizontal = focus_dist * viewport_width * u; let vertical = focus_dist * viewport_height * v; let lower_left_corner = origin - horizontal / 2.0 - vertical / 2.0 - focus_dist * w; let lens_radius = aperture / 2.0; Camera { origin, lower_left_corner, horizontal, vertical, lens_radius, u, v, _w: w, } } pub fn ray(&self, s: f64, t: f64) -> Ray { let rd: Point3 = self.lens_radius * Point3::random_in_unit_disk(); let offset: Point3 = (rd.x * self.u) + rd.y * self.v; Ray::new( self.origin + offset, self.lower_left_corner + s * self.horizontal + t * self.vertical - self.origin - offset, ) } } pub struct Degrees(f64); impl Degrees { pub fn new(val: f64) -> Self { Degrees(val) } fn to_radians(&self) -> Radians { Radians(self.0 * std::f64::consts::PI / 180.0) } } impl Into<f64> for Degrees { fn into(self) -> f64 { self.0 } } pub struct Radians(f64); impl Radians { fn to_degrees(&self) -> Radians { todo!() } } impl Into<f64> for Radians { fn into(self) -> f64 { self.0 } }
extern crate calm_io; extern crate eyre; extern crate hidapi; extern crate indicatif; use std::fs::File; use std::io::Read; use argparse::{ArgumentParser, Print, Store}; use calm_io::stdoutln; use eyre::{Report, WrapErr}; use indicatif::{ProgressBar, ProgressStyle}; pub mod vb_prog { use super::{Report, WrapErr}; use hidapi; pub const HEADER_LEN: usize = 512 + 32; // ROM metadata + Interrupt vectors pub struct FlashBoy { dev: hidapi::HidDevice, } pub struct WriteToken { _int: (), } impl FlashBoy { pub fn open() -> Result<FlashBoy, Report> { let api = hidapi::HidApi::new()?; let device = api .open(0x1781, 0x09a2) .or_else(|e| Err(Error::FlashboyNotFound(Some(e)))) .wrap_err("No USB device with VID:PID 0x1781:0x09a2 was found.")?; // Plenty of non-FlashBoy devices use Atmel micros, so check for string. if !device .get_product_string() .or_else(|e| Err(Error::FlashboyNotFound(Some(e))))? .ok_or(Error::FlashboyNotFound(None)) .wrap_err( "USB device with VID:PID 0x1781:0x9a2 found, but the product string\n\ was empty. Stopping to be safe.", )? .contains("FlashBoy") { return Err(Error::FlashboyNotFound(None)).wrap_err( "A USB device with VID:PID 0x1781:0x9a2 was found, but it wasn't a\n\ FlashBoy. Do you have multiple Atmel devices attached?", ); } Ok(FlashBoy { dev: device }) } pub fn erase(&mut self) -> Result<(), Report> { let mut buf = [0; 65]; buf[1] = Cmds::Erase as u8; self.dev.write(&buf)?; self.dev.read(&mut buf)?; self.check_response(&buf, Cmds::Erase)?; Ok(()) } pub fn init_prog(&mut self) -> Result<WriteToken, Report> { let mut buf = [0; 65]; buf[1] = Cmds::StartProg as u8; self.dev.write(&buf)?; Ok(WriteToken { _int: () }) } pub fn write_chunk(&mut self, _tok: &WriteToken, buf: &[u8; 1024]) -> Result<(), Report> { let mut packet = [0; 65]; packet[1] = Cmds::Write1024 as u8; self.dev.write(&packet)?; for p in buf.chunks_exact(64) { let (_, payload) = packet.split_at_mut(1); payload.clone_from_slice(p); self.dev.write(&packet)?; } self.dev.read(&mut packet)?; self.check_response(&packet, Cmds::Write1024)?; Ok(()) } fn check_response(&self, buf: &[u8], cmd: Cmds) -> Result<(), Error> { if buf[0] == (cmd as u8) { Ok(()) } else { match cmd { Cmds::Erase => Err(Error::UnexpectedEraseResponse { code: buf[1] }), _ => Err(Error::UnexpectedWriteResponse { code: buf[1] }), } } } } #[derive(Clone, Copy)] enum Cmds { Erase = 0xA1, StartProg = 0xB0, Write1024 = 0xB4, } #[derive(Debug)] pub enum Error { FlashboyNotFound(Option<hidapi::HidError>), UnexpectedEraseResponse { code: u8 }, UnexpectedWriteResponse { code: u8 }, } impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Error::FlashboyNotFound(_) => write!(f, "FlashBoy was not found"), Error::UnexpectedEraseResponse { code } => write!( f, "Unexpected response {} when erasing, expected {}", code, Cmds::Erase as u8 ), Error::UnexpectedWriteResponse { code } => write!( f, "Unexpected response {} when writing, expected {}", code, Cmds::Write1024 as u8 ), } } } impl std::error::Error for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { // Error::FlashboyNotFound(Some(e)) => Some(&e), Why does this error? Error::FlashboyNotFound(Some(e)) => Some(e), _ => None, } } } } use self::vb_prog::*; fn main() -> Result<(), Report> { let mut rom = String::new(); { let mut ap = ArgumentParser::new(); ap.set_description("Command-line Virtual Boy Flash Programmer"); ap.add_option( &["-v"], Print( option_env!("CARGO_PKG_VERSION") .unwrap_or("No version- compiled without Cargo.") .to_string(), ), "Show version.", ); ap.refer(&mut rom) .add_argument("rom", Store, "Virtual Boy ROM image to flash.") .required(); ap.parse_args_or_exit(); } let mut f = File::open(&rom)?; let f_len = f.metadata()?.len(); if !(f_len > 16 * 1024 && f_len <= 2 * 1024 * 1024 && f_len.is_power_of_two()) { let f_err = std::io::Error::new( std::io::ErrorKind::InvalidData, "Input ROM was less than 16kB in length, greater than 2MB in length,\n\ or a non power of two length.", ); return Err(From::from(f_err)); } let mut flash = FlashBoy::open()?; stdoutln!("Erasing device (5-10 seconds)...")?; flash.erase()?; stdoutln!("Flashing...")?; let tok = flash.init_prog()?; let mut buf = [0; 1024]; let mut header = [0; HEADER_LEN]; let mut packet_cnt = 0; let header_packet = (f_len / 1024) - 1; let pb = ProgressBar::new(2048); pb.set_style( ProgressStyle::default_bar() .template("[{elapsed_precise}] [{bar:40}] {pos}/{len} packets ({eta})") .progress_chars("#>-"), ); while packet_cnt < 2048 { if packet_cnt <= header_packet { f.read_exact(&mut buf).wrap_err(format!( "File {} must be read in 1024-byte chunks.\n\ Chunk {} was not read properly.", rom, packet_cnt ))?; } else { // Flashboy optimizes for 0xFF chunks when programming. for i in buf.iter_mut() { *i = 0xFF; } } // We only need to pad if the ROM is < 2MB. if header_packet != 2047 { if packet_cnt == header_packet { header.copy_from_slice(buf.split_at_mut(1024 - HEADER_LEN).1); } else if packet_cnt == 2047 { buf.split_at_mut(1024 - HEADER_LEN) .1 .copy_from_slice(&header); } } flash.write_chunk(&tok, &buf)?; packet_cnt += 1; pb.set_position(packet_cnt); } pb.finish(); stdoutln!("Image flashed successfully.")?; Ok(()) }
pub(crate) mod lexer; pub(crate) mod parser;
#[doc = "Writer for register CSRL0"] pub type W = crate::W<u8, super::CSRL0>; #[doc = "Register CSRL0 `reset()`'s with value 0"] impl crate::ResetValue for super::CSRL0 { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Write proxy for field `RXRDY`"] pub struct RXRDY_W<'a> { w: &'a mut W, } impl<'a> RXRDY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u8) & 0x01); self.w } } #[doc = "Write proxy for field `TXRDY`"] pub struct TXRDY_W<'a> { w: &'a mut W, } impl<'a> TXRDY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u8) & 0x01) << 1); self.w } } #[doc = "Write proxy for field `STALLED`"] pub struct STALLED_W<'a> { w: &'a mut W, } impl<'a> STALLED_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u8) & 0x01) << 2); self.w } } #[doc = "Write proxy for field `DATAEND`"] pub struct DATAEND_W<'a> { w: &'a mut W, } impl<'a> DATAEND_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u8) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `SETUP`"] pub struct SETUP_W<'a> { w: &'a mut W, } impl<'a> SETUP_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u8) & 0x01) << 3); self.w } } #[doc = "Write proxy for field `SETEND`"] pub struct SETEND_W<'a> { w: &'a mut W, } impl<'a> SETEND_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u8) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `ERROR`"] pub struct ERROR_W<'a> { w: &'a mut W, } impl<'a> ERROR_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u8) & 0x01) << 4); self.w } } #[doc = "Write proxy for field `REQPKT`"] pub struct REQPKT_W<'a> { w: &'a mut W, } impl<'a> REQPKT_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u8) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `STALL`"] pub struct STALL_W<'a> { w: &'a mut W, } impl<'a> STALL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u8) & 0x01) << 5); self.w } } #[doc = "Write proxy for field `STATUS`"] pub struct STATUS_W<'a> { w: &'a mut W, } impl<'a> STATUS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u8) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `RXRDYC`"] pub struct RXRDYC_W<'a> { w: &'a mut W, } impl<'a> RXRDYC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u8) & 0x01) << 6); self.w } } #[doc = "Write proxy for field `NAKTO`"] pub struct NAKTO_W<'a> { w: &'a mut W, } impl<'a> NAKTO_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u8) & 0x01) << 7); self.w } } #[doc = "Write proxy for field `SETENDC`"] pub struct SETENDC_W<'a> { w: &'a mut W, } impl<'a> SETENDC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u8) & 0x01) << 7); self.w } } impl W { #[doc = "Bit 0 - Receive Packet Ready"] #[inline(always)] pub fn rxrdy(&mut self) -> RXRDY_W { RXRDY_W { w: self } } #[doc = "Bit 1 - Transmit Packet Ready"] #[inline(always)] pub fn txrdy(&mut self) -> TXRDY_W { TXRDY_W { w: self } } #[doc = "Bit 2 - Endpoint Stalled"] #[inline(always)] pub fn stalled(&mut self) -> STALLED_W { STALLED_W { w: self } } #[doc = "Bit 3 - Data End"] #[inline(always)] pub fn dataend(&mut self) -> DATAEND_W { DATAEND_W { w: self } } #[doc = "Bit 3 - Setup Packet"] #[inline(always)] pub fn setup(&mut self) -> SETUP_W { SETUP_W { w: self } } #[doc = "Bit 4 - Setup End"] #[inline(always)] pub fn setend(&mut self) -> SETEND_W { SETEND_W { w: self } } #[doc = "Bit 4 - Error"] #[inline(always)] pub fn error(&mut self) -> ERROR_W { ERROR_W { w: self } } #[doc = "Bit 5 - Request Packet"] #[inline(always)] pub fn reqpkt(&mut self) -> REQPKT_W { REQPKT_W { w: self } } #[doc = "Bit 5 - Send Stall"] #[inline(always)] pub fn stall(&mut self) -> STALL_W { STALL_W { w: self } } #[doc = "Bit 6 - STATUS Packet"] #[inline(always)] pub fn status(&mut self) -> STATUS_W { STATUS_W { w: self } } #[doc = "Bit 6 - RXRDY Clear"] #[inline(always)] pub fn rxrdyc(&mut self) -> RXRDYC_W { RXRDYC_W { w: self } } #[doc = "Bit 7 - NAK Timeout"] #[inline(always)] pub fn nakto(&mut self) -> NAKTO_W { NAKTO_W { w: self } } #[doc = "Bit 7 - Setup End Clear"] #[inline(always)] pub fn setendc(&mut self) -> SETENDC_W { SETENDC_W { w: self } } }
extern crate iptables; use iptables::error::{IPTError, IPTResult}; use iptables::IPTables; /// Behaves like new_chain except it does not produce an error when the chain already exists. pub fn new_chain(ipt: &IPTables, table: &str, chain: &str) -> IPTResult<()> { match ipt.new_chain(table, chain) { // Chain was created. Ok(()) => Ok(()), // Chain already exists. Err(IPTError::BadExitStatus(1)) => Ok(()), err => err, } } /// Behaves just like append_uniquee except it does not produce an error when the rule already /// exists. pub fn append_unique(ipt: &IPTables, table: &str, chain: &str, rule: &str) -> IPTResult<()> { match ipt.append_unique(table, chain, rule) { // Rule was appended. Ok(()) => Ok(()), // Rule already exists. Err(IPTError::Other("the rule exists in the table/chain")) => Ok(()), err => err, } } /// Behaves just like delete except it does not produce an error when the rule does not exist or /// when the jump target does not exist. pub fn delete(ipt: &IPTables, table: &str, chain: &str, rule: &str) -> IPTResult<()> { match ipt.delete(table, chain, rule) { // Rule was deleted. Ok(()) => Ok(()), // Rule was not found. Err(IPTError::BadExitStatus(1)) => Ok(()), // Jump target chain was not found. Err(IPTError::BadExitStatus(2)) => Ok(()), err => err, } } /// Behaves just like delete_chain except it does produce an error when the chain does not exist. pub fn delete_chain(ipt: &IPTables, table: &str, chain: &str) -> IPTResult<()> { match ipt.delete_chain(table, chain) { // Chain was deleted. Ok(()) => Ok(()), // Chain was not found. Err(IPTError::BadExitStatus(1)) => Ok(()), err => err, } } #[cfg(test)] mod test { use super::*; const IPV4: bool = false; #[test] fn test_create_and_delete() { let ipt = iptables::new(IPV4).unwrap(); // Ensure test environment didn't leak from last test run. assert_exists(&ipt, false); // Create a custom chain and rule. new_chain(&ipt, "filter", "CUSTOM_INPUT").unwrap(); append_unique(&ipt, "filter", "INPUT", "-j CUSTOM_INPUT").unwrap(); assert_exists(&ipt, true); // Create them a second time and ensure they don't produce errors. new_chain(&ipt, "filter", "CUSTOM_INPUT").unwrap(); append_unique(&ipt, "filter", "INPUT", "-j CUSTOM_INPUT").unwrap(); assert_exists(&ipt, true); // Delete the custom chain and rule. delete(&ipt, "filter", "INPUT", "-j CUSTOM_INPUT").unwrap(); delete_chain(&ipt, "filter", "CUSTOM_INPUT").unwrap(); assert_exists(&ipt, false); // Delete them a second time to ensure they don't produce errors. delete(&ipt, "filter", "INPUT", "-j CUSTOM_INPUT").unwrap(); delete_chain(&ipt, "filter", "CUSTOM_INPUT").unwrap(); assert_exists(&ipt, false); } fn assert_exists(ipt: &IPTables, exists: bool) { assert_eq!( ipt.exists("filter", "INPUT", "-j CUSTOM_INPUT").unwrap(), exists ); assert_eq!(ipt.chain_exists("filter", "CUSTOM_INPUT").unwrap(), exists); } }
use std::io::IoResult; use std::io::fs::{mod, PathExtensions}; use std::sync::atomics; use std::{io, os}; use cargo::util::realpath; static CARGO_INTEGRATION_TEST_DIR : &'static str = "cargo-integration-tests"; local_data_key!(task_id: uint) static mut NEXT_ID: atomics::AtomicUint = atomics::INIT_ATOMIC_UINT; pub fn root() -> Path { let my_id = *task_id.get().unwrap(); let path = os::self_exe_path().unwrap() .join(CARGO_INTEGRATION_TEST_DIR) .join(format!("test-{}", my_id)); realpath(&path).unwrap() } pub fn home() -> Path { root().join("home") } pub trait PathExt { fn rm_rf(&self) -> IoResult<()>; fn mkdir_p(&self) -> IoResult<()>; fn move_into_the_past(&self) -> IoResult<()>; } impl PathExt for Path { /* Technically there is a potential race condition, but we don't * care all that much for our tests */ fn rm_rf(&self) -> IoResult<()> { if self.exists() { // On windows, apparently git checks out the database with objects // set to the permission 444, and apparently you can't unlink a file // with permissions 444 because you don't have write permissions. // Whow knew! // // If the rmdir fails due to a permission denied error, then go back // and change everything to have write permissions, then remove // everything. match fs::rmdir_recursive(self) { Err(io::IoError { kind: io::PermissionDenied, .. }) => {} e => return e, } for path in try!(fs::walk_dir(self)) { try!(fs::chmod(&path, io::UserRWX)); } fs::rmdir_recursive(self) } else { Ok(()) } } fn mkdir_p(&self) -> IoResult<()> { fs::mkdir_recursive(self, io::UserDir) } fn move_into_the_past(&self) -> IoResult<()> { if self.is_file() { try!(time_travel(self)); } else { for f in try!(fs::walk_dir(self)) { if !f.is_file() { continue } try!(time_travel(&f)); } } return Ok(()); fn time_travel(path: &Path) -> IoResult<()> { let stat = try!(path.stat()); let hour = 1000 * 3600; let newtime = stat.modified - hour; // Sadly change_file_times has the same failure mode as the above // rmdir_recursive :( match fs::change_file_times(path, newtime, newtime) { Err(io::IoError { kind: io::PermissionDenied, .. }) => {} e => return e, } try!(fs::chmod(path, stat.perm | io::UserWrite)); fs::change_file_times(path, newtime, newtime) } } } /// Ensure required test directories exist and are empty pub fn setup() { let my_id = unsafe { NEXT_ID.fetch_add(1, atomics::SeqCst) }; task_id.replace(Some(my_id)); debug!("path setup; root={}; home={}", root().display(), home().display()); root().rm_rf().unwrap(); home().mkdir_p().unwrap(); }
use lazy_static::lazy_static; use rand::random; use rayon::prelude::*; use std::io::Write; use std::ops::{Add, Mul, Not, Rem}; #[derive(Debug, Clone, Copy)] struct Vec3 { x: f32, y: f32, z: f32, } impl Vec3 { fn new_abc(a: f32, b: f32, c: f32) -> Self { Vec3 { x: a, y: b, z: c } } fn new_ab(a: f32, b: f32) -> Self { Vec3 { x: a, y: b, z: 0.0 } } } impl Add for Vec3 { type Output = Vec3; fn add(self, other: Vec3) -> Self { Vec3 { x: self.x + other.x, y: self.y + other.y, z: self.z + other.z, } } } impl Mul for Vec3 { type Output = Vec3; fn mul(self, other: Vec3) -> Self { Vec3 { x: self.x * other.x, y: self.y * other.y, z: self.z * other.z, } } } impl Rem for Vec3 { type Output = f32; fn rem(self, other: Vec3) -> f32 { self.x * other.x + self.y * other.y + self.z * other.z } } impl Not for Vec3 { type Output = Vec3; fn not(self) -> Vec3 { self * (1.0 / (self % self).sqrt()).into() } } impl From<f32> for Vec3 { fn from(n: f32) -> Vec3 { Vec3::new_abc(n, n, n) } } fn min(l: f32, r: f32) -> f32 { if l < r { l } else { r } } fn random_val() -> f32 { random() } fn fmodf(x: f32, y: f32) -> f32 { x % y } fn fabsf(x: f32) -> f32 { x.abs() } fn sqrtf(x: f32) -> f32 { x.sqrt() } fn powf(x: f32, y: f32) -> f32 { x.powf(y) } fn cosf(x: f32) -> f32 { x.cos() } fn sinf(x: f32) -> f32 { x.sin() } fn box_test(position: Vec3, lower_left: Vec3, upper_right: Vec3) -> f32 { let lower_left = position + lower_left * Vec3::from(-1.0); let upper_right = upper_right + position * Vec3::from(-1.0); -min( min( min(lower_left.x, upper_right.x), min(lower_left.y, upper_right.y), ), min(lower_left.z, upper_right.z), ) } const HIT_NONE: u8 = 0; const HIT_LETTER: u8 = 1; const HIT_WALL: u8 = 2; const HIT_SUN: u8 = 3; lazy_static! { static ref LETTER_BLOCKS: Vec<(i32,i32,i32,i32)> = { let x: String = [ "5O5_", "5W9W", "5_9_", // P (without curve) "AOEO", "COC_", "A_E_", // I "IOQ_", "I_QO", // X "UOY_", "Y_]O", "WW[W", // A "aOa_", "aWeW", "a_e_", "cWiO" // R (without curve) ].concat(); let mut blocks: Vec<(i32, i32,i32,i32)> = vec![]; let chs: Vec<i32> = x.chars().map(|c| c as i32).collect(); for i in (0..x.len()).step_by(4) { blocks.push((chs[i], chs[i+1], chs[i+2], chs[i+3])) } blocks }; static ref CURVES: [Vec3; 2] = { [Vec3::new_abc(-11.0, 6.0, 0.0), Vec3::new_abc(11.0, 6.0, 0.0)] }; } fn query_database(position: Vec3, hit_type: &mut u8) -> f32 { let mut distance = std::f32::MAX; let mut f = position; f.z = 0.0; for (a, b, c, d) in LETTER_BLOCKS.iter() { let begin = Vec3::new_ab((a - 79) as f32, (b - 79) as f32) * Vec3::from(0.5); let e = Vec3::new_ab((c - 79) as f32, (d - 79) as f32) * Vec3::from(0.5) + begin * Vec3::from(-1.0); let o_part1 = -min((begin + f * Vec3::from(-1.0)) % e / (e % e), 0.0); let o = f + (begin + e * min(o_part1, 1.0).into()) * Vec3::from(-1.0); distance = min(distance, o % o); } distance = sqrtf(distance); for curve in CURVES.iter().rev() { let mut o = f + *curve * Vec3::from(-1.0); let temp = if o.x > 0.0 { fabsf(sqrtf(o % o) - 2.0) } else { o.y += if o.y > 0.0 { -2.0 } else { 2.0 }; sqrtf(o % o) }; distance = min(distance, temp); } distance = powf(distance.powi(8) + position.z.powi(8), 0.125) - 0.5; *hit_type = HIT_LETTER; let room_dist = min( -min( box_test( position, Vec3::new_abc(-30.0, -0.5, -30.0), Vec3::new_abc(30.0, 18.0, 30.0), ), box_test( position, Vec3::new_abc(-25.0, 17.0, -25.0), Vec3::new_abc(25.0, 20.0, 25.0), ), ), box_test( Vec3::new_abc(fmodf(fabsf(position.x), 8.0), position.y, position.z), Vec3::new_abc(1.5, 18.5, -25.0), Vec3::new_abc(6.5, 20.0, 25.0), ), ); if room_dist < distance { distance = room_dist; *hit_type = HIT_WALL; } let sun = 19.9 - position.y; if sun < distance { distance = sun; *hit_type = HIT_SUN; } distance } fn ray_marching(origin: Vec3, direction: Vec3, hit_pos: &mut Vec3, hit_norm: &mut Vec3) -> u8 { let mut hit_type = HIT_NONE; let mut no_hit_count = 0; let mut total_d = 0.0; while total_d < 100.0 { *hit_pos = origin + direction * total_d.into(); let d = query_database(*hit_pos, &mut hit_type); no_hit_count += 1; if d < 0.01 || no_hit_count > 99 { *hit_norm = !Vec3::new_abc( query_database(*hit_pos + Vec3::new_ab(0.01, 0.0), &mut no_hit_count) - d, query_database(*hit_pos + Vec3::new_ab(0.0, 0.01), &mut no_hit_count) - d, query_database(*hit_pos + Vec3::new_abc(0.0, 0.0, 0.01), &mut no_hit_count) - d, ); return hit_type; } total_d += d; } 0 } fn trace(mut origin: Vec3, mut direction: Vec3) -> Vec3 { let mut sampled_position = Vec3::from(0.0); let mut normal = Vec3::from(0.0); let mut color = Vec3::from(0.0); let mut attenuation = Vec3::from(1.0); let light_direction = !Vec3::new_abc(0.6, 0.6, 1.0); for _ in 0..3 { let hit_type = ray_marching(origin, direction, &mut sampled_position, &mut normal); if hit_type == HIT_NONE { break; } if hit_type == HIT_LETTER { direction = direction + normal * ((normal % direction) * -2.0).into(); origin = sampled_position + direction * Vec3::from(0.1); attenuation = attenuation * Vec3::from(0.2); } if hit_type == HIT_WALL { let incidence = normal % light_direction; let p = 6.283185 * random_val(); let c = random_val(); let s = sqrtf(1.0 - c); let g = if normal.z < 0.0 { -1.0 } else { 1.0 }; let u = -1.0 / (g + normal.z); let v = normal.x * normal.y * u; direction = Vec3::new_abc(v, g + normal.y * normal.y * u, -normal.y) * cosf(p).into() * s.into() + Vec3::new_abc(1.0 + g * normal.x * normal.x * u, g * v, -g * normal.x) * (Vec3::from(sinf(p)) * Vec3::from(s)) + normal * sqrtf(c).into(); origin = sampled_position + direction * Vec3::from(0.1); attenuation = attenuation * Vec3::from(0.2); if incidence > 0.0 && ray_marching( sampled_position + normal * Vec3::from(0.1), light_direction, &mut sampled_position, &mut normal, ) == HIT_SUN { color = color + attenuation * Vec3::new_abc(500.0, 400.0, 100.0) * incidence.into(); } } if hit_type == HIT_SUN { color = color + attenuation * Vec3::new_abc(50.0, 80.0, 100.0); break; } } color } const BYTES_PER_PIXEL: usize = 3; fn main() { let w = 960.0; let h = 540.0; let samples_count = 2; let position = Vec3::new_abc(-22.0, 5.0, 25.0); let goal = !(Vec3::new_abc(-3.0, 4.0, 0.0) + position * Vec3::from(-1.0)); let left = !Vec3::new_abc(goal.z, 0.0, -goal.x) * (1.0 / w).into(); let up = Vec3::new_abc( goal.y * left.z - goal.z * left.y, goal.z * left.x - goal.x * left.z, goal.x * left.y - goal.y * left.x, ); let filename = String::from("output-rust.ppm"); println!( "Width: = {}, Height: = {}, Samples = {}", w, h, samples_count ); println!("Writing data to {}", filename); let mut file = std::fs::File::create(filename).unwrap(); write!(file, "P6 {} {} 255 ", w, h).unwrap(); let mut bytes = vec![0u8; h as usize * w as usize * BYTES_PER_PIXEL]; bytes // take mutable chunks of three items .par_chunks_mut(BYTES_PER_PIXEL) // Turn this into a parallel iterator using Rayon .into_par_iter() // reverse the order in which we iterate so our picture doesn't end upside down .rev() // enumerate() changes the closure argument from |item| => |(index, item)| tuple .enumerate() .for_each(|(idx, chunk)| { // determine the x- and y-coordinates based on the index in row-major order // https://en.wikipedia.org/wiki/Row-major_order let y = (idx / w as usize) as f32; let x = (idx % w as usize) as f32; let mut color = Vec3::from(0.0); for _ in 0..samples_count { color = color + trace( position, !(goal + left * (x - w / 2.0 + random_val()).into() + up * (y - h / 2.0 + random_val()).into()), ); } color = color * (1.0 / samples_count as f32).into() + (14.0 / 241.0).into(); let o: Vec3 = color + Vec3::from(1.0); color = Vec3::new_abc(color.x / o.x, color.y / o.y, color.z / o.z) * Vec3::from(255.0); // We write the new values to our buffer chunk[0] = color.x as u8; chunk[1] = color.y as u8; chunk[2] = color.z as u8; }); file.write_all(&bytes).unwrap(); }
use std::fmt::Display; struct Pair<T> { x: T, y: T, } impl<T> Pair<T> { fn new(x: T, y: T) -> Self { // Self is syntactic sugar for the current type, particularly useful with generic implementations Self { x, y, } } } impl<T: Display + PartialOrd> Pair<T> { fn cmp_display(&self) { // self is syntactic sugar for "self: &Self", and also "&mut self" is short for "self: &mut Self" if self.x >= self.y { println!("The largest member is x = {}", self.x); } else { println!("The largest member is y = {}", self.y); } } } trait TestTo_String { fn me_stringy(&self) -> String; } impl<T: Display> TestTo_String for T { fn me_stringy(&self) -> String { // Similar to how ToString trait is implemented in std String::from("I am available on all types that implement Display trait") } } fn main() { let x = String::from("Look at me"); println!("{}", x); println!("{}", x.me_stringy()); println!("Same with me - {}", 3); println!("{}", 3.me_stringy()); }
use super::{dump::dump_data_frames, InfluxRpcTest}; use async_trait::async_trait; use futures::{prelude::*, FutureExt}; use generated_types::aggregate::AggregateType; use std::sync::Arc; use test_helpers_end_to_end::{ maybe_skip_integration, GrpcRequestBuilder, MiniCluster, Step, StepTest, StepTestState, }; // Standalone test that all the pipes are hooked up for read window aggregate #[tokio::test] pub async fn read_window_aggregate_test() { do_read_window_aggregate_test( vec![ "h2o,state=MA,city=Boston temp=70.0 100", "h2o,state=MA,city=Boston temp=71.0 200", "h2o,state=MA,city=Boston temp=72.0 300", "h2o,state=MA,city=Boston temp=73.0 400", "h2o,state=MA,city=Boston temp=74.0 500", "h2o,state=MA,city=Cambridge temp=80.0 100", "h2o,state=MA,city=Cambridge temp=81.0 200", "h2o,state=MA,city=Cambridge temp=82.0 300", "h2o,state=MA,city=Cambridge temp=83.0 400", "h2o,state=MA,city=Cambridge temp=84.0 500", "h2o,state=CA,city=LA temp=90.0 100", "h2o,state=CA,city=LA temp=91.0 200", "h2o,state=CA,city=LA temp=92.0 300", "h2o,state=CA,city=LA temp=93.0 400", "h2o,state=CA,city=LA temp=94.0 500", ], GrpcRequestBuilder::new() .timestamp_range(200, 1000) .tag_predicate("state", "MA") .window_every(200) .offset(0) .aggregate_type(AggregateType::Sum), vec![ "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Boston,state=MA, type: 0", "FloatPointsFrame, timestamps: [400, 600], values: \"143,147\"", "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Cambridge,state=MA, type: 0", "FloatPointsFrame, timestamps: [400, 600], values: \"163,167\"", ], ) .await } // Standalone test that all the pipes are hooked up for read window aggregate #[tokio::test] pub async fn read_window_aggregate_test_with_periods() { do_read_window_aggregate_test( vec![ "measurement.one,tag.one=foo field.one=1,field.two=100 1000", "measurement.one,tag.one=bar field.one=2,field.two=200 2000", ], GrpcRequestBuilder::new() .timestamp_range(0, 2001) .field_predicate("field.two") .window_every(200) .offset(0) .aggregate_type(AggregateType::Sum), vec![ "SeriesFrame, tags: _field=field.two,_measurement=measurement.one,tag.one=bar, type: 0", "FloatPointsFrame, timestamps: [2200], values: \"200\"", "SeriesFrame, tags: _field=field.two,_measurement=measurement.one,tag.one=foo, type: 0", "FloatPointsFrame, timestamps: [1200], values: \"100\"", ], ) .await } /// Sends the specified line protocol to a server, runs a read_window_aggregate /// gRPC request, and compares it against expected frames async fn do_read_window_aggregate_test( input_lines: Vec<&str>, request_builder: GrpcRequestBuilder, expected_frames: impl IntoIterator<Item = &str>, ) { test_helpers::maybe_start_logging(); let database_url = maybe_skip_integration!(); let expected_frames: Vec<String> = expected_frames.into_iter().map(|s| s.to_string()).collect(); // Set up the cluster ==================================== let mut cluster = MiniCluster::create_shared(database_url).await; let line_protocol = input_lines.join("\n"); StepTest::new( &mut cluster, vec![ Step::WriteLineProtocol(line_protocol), Step::Custom(Box::new(move |state: &mut StepTestState| { let request_builder = request_builder.clone(); let expected_frames = expected_frames.clone(); async move { let mut storage_client = state.cluster().querier_storage_client(); let request = request_builder .source(state.cluster()) .build_read_window_aggregate(); println!("Sending read_window_aggregate request {request:#?}"); let response = storage_client.read_window_aggregate(request).await.unwrap(); let responses: Vec<_> = response.into_inner().try_collect().await.unwrap(); let frames: Vec<_> = responses .into_iter() .flat_map(|r| r.frames) .flat_map(|f| f.data) .collect(); let actual_frames = dump_data_frames(&frames); assert_eq!( expected_frames, actual_frames, "\n\nExpected:\n{expected_frames:#?}\nActual:\n{actual_frames:#?}", ); } .boxed() })), ], ) .run() .await } #[tokio::test] async fn nanoseconds() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForWindowAggregate", aggregate_type: AggregateType::Mean, every: 200, offset: 0, request: GrpcRequestBuilder::new() .or_tag_predicates([("city", "Boston"), ("city", "LA")].into_iter()) .timestamp_range(100, 450), expected_results: vec![ // note the name of the field is "temp" even though it is the average "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Boston,state=MA, type: 0", "FloatPointsFrame, timestamps: [200, 400, 600], values: \"70,71.5,73\"", "SeriesFrame, tags: _field=temp,_measurement=h2o,city=LA,state=CA, type: 0", "FloatPointsFrame, timestamps: [200, 400, 600], values: \"90,91.5,93\"", ], }) .run() .await; } #[tokio::test] async fn nanoseconds_measurement_predicate() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForWindowAggregate", aggregate_type: AggregateType::Mean, every: 200, offset: 0, request: GrpcRequestBuilder::new() .not_measurement_predicate("other") .tag_predicate("city", "LA") .or_tag_predicates([("city", "Boston")].into_iter()) .timestamp_range(100, 450), expected_results: vec![ "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Boston,state=MA, type: 0", "FloatPointsFrame, timestamps: [200, 400, 600], values: \"70,71.5,73\"", "SeriesFrame, tags: _field=temp,_measurement=h2o,city=LA,state=CA, type: 0", "FloatPointsFrame, timestamps: [200, 400, 600], values: \"90,91.5,93\"", ], }) .run() .await; } #[tokio::test] async fn nanoseconds_measurement_count() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForWindowAggregate", aggregate_type: AggregateType::Count, every: 200, offset: 0, request: GrpcRequestBuilder::new().timestamp_range(100, 450), expected_results: vec![ // Expect that the type of `Count` is Integer "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Boston,state=MA, type: 1", "IntegerPointsFrame, timestamps: [200, 400, 600], values: \"1,2,1\"", "SeriesFrame, tags: _field=temp,_measurement=h2o,city=Cambridge,state=MA, type: 1", "IntegerPointsFrame, timestamps: [200, 400, 600], values: \"1,2,1\"", "SeriesFrame, tags: _field=temp,_measurement=h2o,city=LA,state=CA, type: 1", "IntegerPointsFrame, timestamps: [200, 400, 600], values: \"1,2,1\"", ], }) .run() .await; } // See <https://github.com/influxdata/influxdb_iox/issues/2697> #[tokio::test] async fn min_defect_2697() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForDefect2697", aggregate_type: AggregateType::Min, every: 10, offset: 0, request: GrpcRequestBuilder::new() // time >= '2021-01-01T00:00:01.000000001Z' AND time <= '2021-01-01T00:00:01.000000031Z' .timestamp_range(1_609_459_201_000_000_001, 1_609_459_201_000_000_031), expected_results: vec![ // Because the windowed aggregate is using a selector aggregate (one of MIN, // MAX, FIRST, LAST) we need to run a plan that brings along the timestamps // for the chosen aggregate in the window. "SeriesFrame, tags: _field=bar,_measurement=mm,section=1a, type: 0", "FloatPointsFrame, timestamps: [1609459201000000011], values: \"5\"", "SeriesFrame, tags: _field=foo,_measurement=mm,section=1a, type: 0", "FloatPointsFrame, timestamps: [1609459201000000001, 1609459201000000024], \ values: \"1,11.24\"", "SeriesFrame, tags: _field=bar,_measurement=mm,section=2b, type: 0", "FloatPointsFrame, \ timestamps: [1609459201000000009, 1609459201000000015, 1609459201000000022], \ values: \"4,6,1.2\"", "SeriesFrame, tags: _field=foo,_measurement=mm,section=2b, type: 0", "FloatPointsFrame, timestamps: [1609459201000000002], values: \"2\"", ], }) .run() .await; } // See <https://github.com/influxdata/influxdb_iox/issues/2697> #[tokio::test] async fn sum_defect_2697() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForDefect2697", aggregate_type: AggregateType::Sum, every: 10, offset: 0, request: GrpcRequestBuilder::new() // time >= '2021-01-01T00:00:01.000000001Z' AND time <= '2021-01-01T00:00:01.000000031Z' .timestamp_range(1_609_459_201_000_000_001, 1_609_459_201_000_000_031), expected_results: vec![ // The windowed aggregate is using a non-selector aggregate (SUM, COUNT, MEAN). // For each distinct series the window defines the `time` column "SeriesFrame, tags: _field=bar,_measurement=mm,section=1a, type: 0", "FloatPointsFrame, timestamps: [1609459201000000020], values: \"5\"", "SeriesFrame, tags: _field=foo,_measurement=mm,section=1a, type: 0", "FloatPointsFrame, timestamps: [1609459201000000010, 1609459201000000030], \ values: \"4,11.24\"", "SeriesFrame, tags: _field=bar,_measurement=mm,section=2b, type: 0", "FloatPointsFrame, \ timestamps: [1609459201000000010, 1609459201000000020, 1609459201000000030], \ values: \"4,6,1.2\"", "SeriesFrame, tags: _field=foo,_measurement=mm,section=2b, type: 0", "FloatPointsFrame, timestamps: [1609459201000000010], values: \"2\"", ], }) .run() .await; } // See <https://github.com/influxdata/influxdb_iox/issues/2845> // // Adds coverage to window_aggregate plan for filtering on _field. #[tokio::test] async fn field_predicates() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForDefect2697", aggregate_type: AggregateType::Sum, every: 10, offset: 0, request: GrpcRequestBuilder::new() .field_predicate("foo") // time >= '2021-01-01T00:00:01.000000001Z' AND time <= '2021-01-01T00:00:01.000000031Z' .timestamp_range(1_609_459_201_000_000_001, 1_609_459_201_000_000_031), expected_results: vec![ // The windowed aggregate is using a non-selector aggregate (SUM, COUNT, MEAN). // For each distinct series the window defines the `time` column "SeriesFrame, tags: _field=foo,_measurement=mm,section=1a, type: 0", "FloatPointsFrame, timestamps: [1609459201000000010, 1609459201000000030], \ values: \"4,11.24\"", "SeriesFrame, tags: _field=foo,_measurement=mm,section=2b, type: 0", "FloatPointsFrame, timestamps: [1609459201000000010], values: \"2\"", ], }) .run() .await; } #[tokio::test] async fn overflow() { Arc::new(ReadWindowAggregateTest { setup_name: "MeasurementForDefect2890", aggregate_type: AggregateType::Max, // Note the giant window every: i64::MAX, offset: 0, request: GrpcRequestBuilder::new() .timestamp_range(1_609_459_201_000_000_001, 1_609_459_201_000_000_024), expected_results: vec![ // The windowed aggregate is using a non-selector aggregate (SUM, COUNT, MEAN). // For each distinct series the window defines the `time` column "SeriesFrame, tags: _field=bar,_measurement=mm, type: 0", "FloatPointsFrame, timestamps: [1609459201000000015], values: \"6\"", "SeriesFrame, tags: _field=foo,_measurement=mm, type: 0", "FloatPointsFrame, timestamps: [1609459201000000005], values: \"3\"", ], }) .run() .await; } #[tokio::test] async fn periods() { Arc::new(ReadWindowAggregateTest { setup_name: "PeriodsInNames", aggregate_type: AggregateType::Max, every: 500_000_000_000, offset: 0, request: GrpcRequestBuilder::new().timestamp_range(0, 1_700_000_001_000_000_000), expected_results: vec![ "SeriesFrame, tags: \ _field=field.one,_measurement=measurement.one,tag.one=value,tag.two=other, type: 0", "FloatPointsFrame, timestamps: [1609459201000000001], values: \"1\"", "SeriesFrame, tags: \ _field=field.two,_measurement=measurement.one,tag.one=value,tag.two=other, type: 3", "BooleanPointsFrame, timestamps: [1609459201000000001], values: true", "SeriesFrame, tags: \ _field=field.one,_measurement=measurement.one,tag.one=value2,tag.two=other2, type: 0", "FloatPointsFrame, timestamps: [1609459201000000002], values: \"1\"", "SeriesFrame, tags: \ _field=field.two,_measurement=measurement.one,tag.one=value2,tag.two=other2, type: 3", "BooleanPointsFrame, timestamps: [1609459201000000002], values: false", ], }) .run() .await; } #[derive(Debug)] struct ReadWindowAggregateTest { setup_name: &'static str, aggregate_type: AggregateType, every: i64, offset: i64, request: GrpcRequestBuilder, expected_results: Vec<&'static str>, } #[async_trait] impl InfluxRpcTest for ReadWindowAggregateTest { fn setup_name(&self) -> &'static str { self.setup_name } async fn request_and_assert(&self, cluster: &MiniCluster) { let mut storage_client = cluster.querier_storage_client(); let read_window_aggregate_request = self .request .clone() .source(cluster) .aggregate_type(self.aggregate_type) .window_every(self.every) .offset(self.offset) .build_read_window_aggregate(); let read_window_aggregate_response = storage_client .read_window_aggregate(read_window_aggregate_request) .await .expect("successful read_window_aggregate call"); let responses: Vec<_> = read_window_aggregate_response .into_inner() .try_collect() .await .unwrap(); let frames: Vec<_> = responses .into_iter() .flat_map(|r| r.frames) .flat_map(|f| f.data) .collect(); let results = dump_data_frames(&frames); assert_eq!(results, self.expected_results); } }
//! Module for API context management. //! //! This module defines traits and structs that can be used to manage //! contextual data related to a request, as it is passed through a series of //! hyper services. //! //! See the `context_tests` module below for examples of how to use. use crate::auth::{AuthData, Authorization}; use crate::XSpanIdString; use hyper::{service::Service, Request, Response}; use std::future::Future; use std::pin::Pin; /// Defines methods for accessing, modifying, adding and removing the data stored /// in a context. Used to specify the requirements that a hyper service makes on /// a generic context type that it receives with a request, e.g. /// /// ```rust /// # use futures::future::ok; /// # use std::future::Future; /// # use std::marker::PhantomData; /// # use std::pin::Pin; /// # use std::task::{Context, Poll}; /// # use swagger::context::*; /// # /// # struct MyItem; /// # fn do_something_with_my_item(item: &MyItem) {} /// # /// struct MyService<C> { /// marker: PhantomData<C>, /// } /// /// impl<C> hyper::service::Service<(hyper::Request<hyper::Body>, C)> for MyService<C> /// where C: Has<MyItem> + Send + 'static /// { /// type Response = hyper::Response<hyper::Body>; /// type Error = std::io::Error; /// type Future = Pin<Box<dyn Future<Output=Result<Self::Response, Self::Error>>>>; /// /// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { /// Poll::Ready(Ok(())) /// } /// /// fn call(&mut self, req : (hyper::Request<hyper::Body>, C)) -> Self::Future { /// let (_, context) = req; /// do_something_with_my_item(Has::<MyItem>::get(&context)); /// Box::pin(ok(hyper::Response::new(hyper::Body::empty()))) /// } /// } /// ``` pub trait Has<T> { /// Get an immutable reference to the value. fn get(&self) -> &T; /// Get a mutable reference to the value. fn get_mut(&mut self) -> &mut T; /// Set the value. fn set(&mut self, value: T); } /// Defines a method for permanently extracting a value, changing the resulting /// type. Used to specify that a hyper service consumes some data from the context, /// making it unavailable to later layers, e.g. /// /// ```rust /// # use futures::future::{Future, ok}; /// # use std::task::{Context, Poll}; /// # use std::marker::PhantomData; /// # use swagger::context::*; /// # /// struct MyItem1; /// struct MyItem2; /// struct MyItem3; /// /// struct MiddlewareService<T, C> { /// inner: T, /// marker: PhantomData<C>, /// } /// /// impl<T, C, D, E> hyper::service::Service<(hyper::Request<hyper::Body>, C)> for MiddlewareService<T, C> /// where /// C: Pop<MyItem1, Result=D> + Send + 'static, /// D: Pop<MyItem2, Result=E>, /// E: Pop<MyItem3>, /// E::Result: Send + 'static, /// T: hyper::service::Service<(hyper::Request<hyper::Body>, E::Result)> /// { /// type Response = T::Response; /// type Error = T::Error; /// type Future = T::Future; /// /// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { /// self.inner.poll_ready(cx) /// } /// /// fn call(&mut self, req : (hyper::Request<hyper::Body>, C)) -> Self::Future { /// let (request, context) = req; /// /// // type annotations optional, included for illustrative purposes /// let (_, context): (MyItem1, D) = context.pop(); /// let (_, context): (MyItem2, E) = context.pop(); /// let (_, context): (MyItem3, E::Result) = context.pop(); /// /// self.inner.call((request, context)) /// } /// } pub trait Pop<T> { /// The type that remains after the value has been popped. type Result; /// Extracts a value. fn pop(self) -> (T, Self::Result); } /// Defines a method for inserting a value, changing the resulting /// type. Used to specify that a hyper service adds some data from the context, /// making it available to later layers, e.g. /// /// ```rust /// # use swagger::context::*; /// # use std::marker::PhantomData; /// # use std::task::{Context, Poll}; /// # /// struct MyItem1; /// struct MyItem2; /// struct MyItem3; /// /// struct MiddlewareService<T, C> { /// inner: T, /// marker: PhantomData<C>, /// } /// /// impl<T, C, D, E> hyper::service::Service<(hyper::Request<hyper::Body>, C)> for MiddlewareService<T, C> /// where /// C: Push<MyItem1, Result=D> + Send + 'static, /// D: Push<MyItem2, Result=E>, /// E: Push<MyItem3>, /// E::Result: Send + 'static, /// T: hyper::service::Service<(hyper::Request<hyper::Body>, E::Result)> /// { /// type Response = T::Response; /// type Error = T::Error; /// type Future = T::Future; /// /// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { /// self.inner.poll_ready(cx) /// } /// /// fn call(&mut self, req : (hyper::Request<hyper::Body>, C)) -> Self::Future { /// let (request, context) = req; /// let context = context /// .push(MyItem1{}) /// .push(MyItem2{}) /// .push(MyItem3{}); /// self.inner.call((request, context)) /// } /// } pub trait Push<T> { /// The type that results from adding an item. type Result; /// Inserts a value. fn push(self, value: T) -> Self::Result; } /// Defines a struct that can be used to build up contexts recursively by /// adding one item to the context at a time, and a unit struct representing an /// empty context. The first argument is the name of the newly defined context struct /// that is used to add an item to the context, the second argument is the name of /// the empty context struct, and subsequent arguments are the types /// that can be stored in contexts built using these struct. /// /// A cons list built using the generated context type will implement Has<T> and Pop<T> /// for each type T that appears in the list, provided that the list only /// contains the types that were passed to the macro invocation after the context /// type name. /// /// All list types constructed using the generated types will implement `Push<T>` /// for all types `T` that appear in the list passed to the macro invocation. /// /// E.g. /// /// ```edition2018 /// #[derive(Default)] /// struct MyType1; /// #[derive(Default)] /// struct MyType2; /// #[derive(Default)] /// struct MyType3; /// #[derive(Default)] /// struct MyType4; /// /// swagger::new_context_type!(MyContext, MyEmpContext, MyType1, MyType2, MyType3); /// /// fn use_has_my_type_1<T: swagger::Has<MyType1>> (_: &T) {} /// fn use_has_my_type_2<T: swagger::Has<MyType2>> (_: &T) {} /// fn use_has_my_type_3<T: swagger::Has<MyType3>> (_: &T) {} /// fn use_has_my_type_4<T: swagger::Has<MyType4>> (_: &T) {} /// /// // Will implement `Has<MyType1>` and `Has<MyType2>` because these appear /// // in the type, and were passed to `new_context_type!`. Will not implement /// // `Has<MyType3>` even though it was passed to `new_context_type!`, because /// // it is not included in the type. /// type ExampleContext = MyContext<MyType1, MyContext<MyType2, MyEmpContext>>; /// /// // Will not implement `Has<MyType4>` even though it appears in the type, /// // because `MyType4` was not passed to `new_context_type!`. /// type BadContext = MyContext<MyType1, MyContext<MyType4, MyEmpContext>>; /// /// fn main() { /// # use swagger::Push as _; /// let context : ExampleContext = /// MyEmpContext::default() /// .push(MyType2{}) /// .push(MyType1{}); /// /// use_has_my_type_1(&context); /// use_has_my_type_2(&context); /// // use_has_my_type_3(&context); // will fail /// /// // Will fail because `MyType4`// was not passed to `new_context_type!` /// // let context = MyEmpContext::default().push(MyType4{}); /// /// let bad_context: BadContext = BadContext::default(); /// // use_has_my_type_4(&bad_context); // will fail /// } /// ``` /// /// See the `context_tests` module for more usage examples. #[macro_export] macro_rules! new_context_type { ($context_name:ident, $empty_context_name:ident, $($types:ty),+ ) => { /// Wrapper type for building up contexts recursively, adding one item /// to the context at a time. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct $context_name<T, C> { head: T, tail: C, } /// Unit struct representing an empty context with no data in it. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct $empty_context_name; // implement `Push<T>` on the empty context type for each type `T` that // was passed to the macro $( impl $crate::Push<$types> for $empty_context_name { type Result = $context_name<$types, Self>; fn push(self, item: $types) -> Self::Result { $context_name{head: item, tail: Self::default()} } } // implement `Has<T>` for a list where `T` is the type of the head impl<C> $crate::Has<$types> for $context_name<$types, C> { fn set(&mut self, item: $types) { self.head = item; } fn get(&self) -> &$types { &self.head } fn get_mut(&mut self) -> &mut $types { &mut self.head } } // implement `Pop<T>` for a list where `T` is the type of the head impl<C> $crate::Pop<$types> for $context_name<$types, C> { type Result = C; fn pop(self) -> ($types, Self::Result) { (self.head, self.tail) } } // implement `Push<U>` for non-empty lists, for each type `U` that was passed // to the macro impl<C, T> $crate::Push<$types> for $context_name<T, C> { type Result = $context_name<$types, Self>; fn push(self, item: $types) -> Self::Result { $context_name{head: item, tail: self} } } )+ // Add implementations of `Has<T>` and `Pop<T>` when `T` is any type stored in // the list, not just the head. $crate::new_context_type!(impl extend_has $context_name, $empty_context_name, $($types),+); }; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // takes a type `Type1` ($head) and a non-empty list of types `Types` ($tail). First calls // another helper macro to define the following impls, for each `Type2` in `Types`: // ``` // impl<C: Has<Type1> Has<Type1> for $context_name<Type2, C> {...} // impl<C: Has<Type2> Has<Type2> for $context_name<Type1, C> {...} // impl<C: Pop<Type1> Pop<Type1> for $context_name<Type2, C> {...} // impl<C: Pop<Type2> Pop<Type2> for $context_name<Type1, C> {...} // ``` // then calls itself again with the rest of the list. The end result is to define the above // impls for all distinct pairs of types in the original list. (impl extend_has $context_name:ident, $empty_context_name:ident, $head:ty, $($tail:ty),+ ) => { $crate::new_context_type!( impl extend_has_helper $context_name, $empty_context_name, $head, $($tail),+ ); $crate::new_context_type!(impl extend_has $context_name, $empty_context_name, $($tail),+); }; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // base case of the preceding helper macro - was passed an empty list of types, so // we don't need to do anything. (impl extend_has $context_name:ident, $empty_context_name:ident, $head:ty) => {}; // "HELPER" MACRO CASE - NOT FOR EXTERNAL USE // takes a type `Type1` ($type) and a non-empty list of types `Types` ($types). For // each `Type2` in `Types`, defines the following impls: // ``` // impl<C: Has<Type1> Has<Type1> for $context_name<Type2, C> {...} // impl<C: Has<Type2> Has<Type2> for $context_name<Type1, C> {...} // impl<C: Pop<Type1> Pop<Type1> for $context_name<Type2, C> {...} // impl<C: Pop<Type2> Pop<Type2> for $context_name<Type1, C> {...} // ``` // (impl extend_has_helper $context_name:ident, $empty_context_name:ident, $type:ty, $($types:ty),+ ) => { $( impl<C: $crate::Has<$type>> $crate::Has<$type> for $context_name<$types, C> { fn set(&mut self, item: $type) { self.tail.set(item); } fn get(&self) -> &$type { self.tail.get() } fn get_mut(&mut self) -> &mut $type { self.tail.get_mut() } } impl<C: $crate::Has<$types>> $crate::Has<$types> for $context_name<$type, C> { fn set(&mut self, item: $types) { self.tail.set(item); } fn get(&self) -> &$types { self.tail.get() } fn get_mut(&mut self) -> &mut $types { self.tail.get_mut() } } impl<C> $crate::Pop<$type> for $context_name<$types, C> where C: $crate::Pop<$type> { type Result = $context_name<$types, C::Result>; fn pop(self) -> ($type, Self::Result) { let (value, tail) = self.tail.pop(); (value, $context_name{ head: self.head, tail}) } } impl<C> $crate::Pop<$types> for $context_name<$type, C> where C: $crate::Pop<$types> { type Result = $context_name<$type, C::Result>; fn pop(self) -> ($types, Self::Result) { let (value, tail) = self.tail.pop(); (value, $context_name{ head: self.head, tail}) } } )+ }; } // Create a default context type to export. new_context_type!( ContextBuilder, EmptyContext, XSpanIdString, Option<AuthData>, Option<Authorization> ); /// Macro for easily defining context types. The first argument should be a /// context type created with `new_context_type!` and subsequent arguments are the /// types to be stored in the context, with the outermost first. /// /// ```rust /// # #[macro_use] extern crate swagger; /// # use swagger::{Has, Pop, Push}; /// /// # struct Type1; /// # struct Type2; /// # struct Type3; /// /// # new_context_type!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// /// // the following two types are identical /// type ExampleContext1 = make_context_ty!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// type ExampleContext2 = MyContext<Type1, MyContext<Type2, MyContext<Type3, MyEmptyContext>>>; /// /// // e.g. this wouldn't compile if they were different types /// fn do_nothing(input: ExampleContext1) -> ExampleContext2 { /// input /// } /// ``` #[macro_export] macro_rules! make_context_ty { ($context_name:ident, $empty_context_name:ident, $type:ty $(, $types:ty)* $(,)* ) => { $context_name<$type, $crate::make_context_ty!($context_name, $empty_context_name, $($types),*)> }; ($context_name:ident, $empty_context_name:ident $(,)* ) => { $empty_context_name }; } /// Macro for easily defining context values. The first argument should be a /// context type created with `new_context_type!` and subsequent arguments are the /// values to be stored in the context, with the outermost first. /// /// ```rust /// # #[macro_use] extern crate swagger; /// # use swagger::{Has, Pop, Push}; /// /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type1; /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type2; /// # #[derive(PartialEq, Eq, Debug)] /// # struct Type3; /// /// # new_context_type!(MyContext, MyEmptyContext, Type1, Type2, Type3); /// /// fn main() { /// // the following are equivalent /// let context1 = make_context!(MyContext, MyEmptyContext, Type1 {}, Type2 {}, Type3 {}); /// let context2 = MyEmptyContext::default() /// .push(Type3{}) /// .push(Type2{}) /// .push(Type1{}); /// /// assert_eq!(context1, context2); /// } /// ``` #[macro_export] macro_rules! make_context { ($context_name:ident, $empty_context_name:ident, $value:expr $(, $values:expr)* $(,)*) => { $crate::make_context!($context_name, $empty_context_name, $($values),*).push($value) }; ($context_name:ident, $empty_context_name:ident $(,)* ) => { $empty_context_name::default() }; } /// Context wrapper, to bind an API with a context. #[derive(Debug)] pub struct ContextWrapper<T, C> { api: T, context: C, } impl<T, C> ContextWrapper<T, C> { /// Create a new ContextWrapper, binding the API and context. pub fn new(api: T, context: C) -> Self { Self { api, context } } /// Borrows the API. pub fn api(&self) -> &T { &self.api } /// Borrows the context. pub fn context(&self) -> &C { &self.context } } impl<T: Clone, C: Clone> Clone for ContextWrapper<T, C> { fn clone(&self) -> Self { ContextWrapper { api: self.api.clone(), context: self.context.clone(), } } } /// Trait designed to ensure consistency in context used by swagger middlewares /// /// ```rust /// # use swagger::context::*; /// # use std::marker::PhantomData; /// # use std::task::{Context, Poll}; /// # use swagger::auth::{AuthData, Authorization}; /// # use swagger::XSpanIdString; /// /// struct ExampleMiddleware<T, C> { /// inner: T, /// marker: PhantomData<C>, /// } /// /// impl<T, C> hyper::service::Service<(hyper::Request<hyper::Body>, C)> for ExampleMiddleware<T, C> /// where /// T: SwaggerService<hyper::Body, hyper::Body, C>, /// C: Has<Option<AuthData>> + /// Has<Option<Authorization>> + /// Has<XSpanIdString> + /// Clone + /// Send + /// 'static, /// { /// type Response = T::Response; /// type Error = T::Error; /// type Future = T::Future; /// /// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { /// self.inner.poll_ready(cx) /// } /// /// fn call(&mut self, req: (hyper::Request<hyper::Body>, C)) -> Self::Future { /// self.inner.call(req) /// } /// } /// ``` pub trait SwaggerService<RequestBody, ResponseBody, Context>: Clone + Service< (Request<RequestBody>, Context), Response = Response<ResponseBody>, Error = hyper::Error, Future = Pin<Box<dyn Future<Output = Result<Response<ResponseBody>, hyper::Error>>>>, > where Context: Has<Option<AuthData>> + Has<Option<Authorization>> + Has<XSpanIdString> + Clone + 'static + Send, { } impl<ReqB, ResB, Context, T> SwaggerService<ReqB, ResB, Context> for T where T: Clone + Service< (Request<ReqB>, Context), Response = Response<ResB>, Error = hyper::Error, Future = Pin<Box<dyn Future<Output = Result<Response<ResB>, hyper::Error>>>>, >, Context: Has<Option<AuthData>> + Has<Option<Authorization>> + Has<XSpanIdString> + Clone + 'static + Send, { } #[cfg(test)] mod context_tests { use super::Has; use super::*; struct ContextItem1 { val: u32, } struct ContextItem2; struct ContextItem3; // all the hyper service layers you will be using, and what requirements // their contexts types have. Use the `new_context_type!` macro to create // a context type and empty context type that are capable of containing all the // types that your hyper services require. new_context_type!( MyContext, MyEmptyContext, ContextItem1, ContextItem2, ContextItem3 ); #[test] fn send_request() { let t = MyEmptyContext::default(); let t = t.push(ContextItem1 { val: 1 }); let t = t.push(ContextItem2); { let v: &ContextItem1 = t.get(); assert_eq!(v.val, 1); } let (_, mut t): (ContextItem2, _) = t.pop(); { let v: &mut ContextItem1 = t.get_mut(); v.val = 4; } { let v: &ContextItem1 = t.get(); assert_eq!(v.val, 4); } } }
static RAINBOW: [[u8; 3]; 12] = [[255, 0, 0], [255, 128, 0], [255, 255, 0], [128, 255, 0], [0, 255, 0], [0, 255, 128], [0, 255, 255], [0, 127, 255], [0, 0, 255], [128, 0, 255], [255, 0, 255], [255, 0, 128]]; use color::Color; pub fn get_rainbow_color(note: u8) -> Color { let rgb = RAINBOW[note as usize % 12 as usize]; Color::new(rgb[0], rgb[1], rgb[2]) }
//! Defines `Range` and `HalfRange` types. use proc_macro2::TokenStream; use quote::quote; /// Returns the tokens defining `Range` and `HalfRange`. pub fn get() -> TokenStream { quote! { use std::fmt; /// Abstracts integer choices by a range. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, Ord, PartialOrd)] #[repr(C)] pub struct Range { pub min: u32, pub max: u32, } #[allow(dead_code)] impl Range { pub const ALL: Range = Range { min: 0, max: std::u32::MAX }; pub const FAILED: Range = Range { min: 1, max: 0 }; /// Returns the full range. pub fn all() -> Self { Self::ALL } /// Inserts alternatives into the domain. pub fn insert(&mut self, other: Range) { self.min = std::cmp::min(self.min, other.min); self.max = std::cmp::max(self.max, other.max); } /// Returns the difference between the min and max of two ranges. fn get_diff_add(&self, other: Range) -> Range { Range { min: other.min - self.min, max: self.max - other.max } } /// Restricts the `Range` by applying the result of `get_diff`. fn apply_diff_add(&mut self, diff: Range) { self.min += diff.min; self.max -= diff.max; } /// Returns the difference between the min and max of two ranges. fn get_diff_mul(&self, other: Range) -> Range { Range { min: other.min / self.min, max: self.max / other.max } } /// Restricts the `Range` by applying the result of `get_diff`. fn apply_diff_mul(&mut self, diff: Range) { self.min *= diff.min; self.max /= diff.max; } fn add_add(&mut self, diff: Range) { self.min += diff.min; self.max += diff.max; } fn add_mul(&mut self, diff: Range) { self.min *= diff.min; self.max *= diff.max; } fn sub_add(&mut self, diff: Range) { self.min -= diff.min; self.max -= diff.max; } fn sub_mul(&mut self, diff: Range) { self.min /= diff.min; self.max /= diff.max; } pub fn as_fixed(&self) -> Option<u32> { if self.min == self.max { Some(self.min) } else { None } } } impl Domain for Range { fn is_failed(&self) -> bool { self.min > self.max } fn is_constrained(&self) -> bool { self.min == self.max } fn contains(&self, other: Range) -> bool { self.min <= other.min && self.max >= other.max } fn restrict(&mut self, other: Range) { self.min = std::cmp::max(self.min, other.min); self.max = std::cmp::min(self.max, other.max); } } impl NumSet for Range { type Universe = (); fn min_value(&self, _: &()) -> u32 { self.min } fn max_value(&self, _: &()) -> u32 { self.max } } impl NumDomain for Range { fn new_gt<D: NumSet>(_: &(), min: D, min_universe: &D::Universe) -> Self { let min = min.min_value(min_universe).saturating_add(1); Range { min, .. Range::ALL } } fn new_lt<D: NumSet>(_: &(), max: D, max_universe: &D::Universe) -> Self { let max = max.max_value(max_universe).saturating_sub(1); Range { max, .. Range::ALL } } fn new_geq<D: NumSet>(_: &(), min: D, min_universe: &D::Universe) -> Self { Range { min: min.min_value(min_universe), .. Range::ALL } } fn new_leq<D: NumSet>(_: &(), max: D, max_universe: &D::Universe) -> Self { Range { max: max.max_value(max_universe), .. Range::ALL } } fn new_eq<D: NumSet>(_: &(), eq: D, eq_universe: &D::Universe) -> Self { Range { max: eq.max_value(eq_universe), min: eq.min_value(eq_universe), } } } impl fmt::Display for Range { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { if self.max == std::u32::MAX { write!(fmt, "{}..", self.min) } else if self.min > self.max { write!(fmt, "{{}}") } else { write!(fmt, "{}..={}", self.min, self.max) } } } /// Abstracts integer choices by a range, but only store `min`. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize, Ord, PartialOrd)] #[repr(C)] pub struct HalfRange { pub min: u32 } #[allow(dead_code)] impl HalfRange { pub const ALL: HalfRange = HalfRange { min: 0 }; /// Returns the full `HalfRange`. pub fn all() -> Self { Self::ALL } /// Inserts alternatives into the domain. pub fn insert(&mut self, other: HalfRange) { self.min = std::cmp::min(self.min, other.min); } /// Returns the difference between the min and max of two ranges. fn get_diff_add(&self, other: HalfRange) -> HalfRange { HalfRange { min: other.min - self.min } } /// Restricts the `Range` by applying the result of `get_diff`. fn apply_diff_add(&mut self, diff: HalfRange) { self.min += diff.min; } /// Returns the difference between the min and max of two ranges. fn get_diff_mul(&self, other: HalfRange) -> HalfRange { HalfRange { min: other.min / self.min } } /// Restricts the `Range` by applying the result of `get_diff`. fn apply_diff_mul(&mut self, diff: HalfRange) { self.min *= diff.min; } fn add_add(&mut self, diff: HalfRange) { self.min += diff.min; } fn add_mul(&mut self, diff: HalfRange) { self.min *= diff.min; } fn sub_add(&mut self, diff: HalfRange) { self.min -= diff.min; } fn sub_mul(&mut self, diff: HalfRange) { self.min /= diff.min; } } impl Domain for HalfRange { fn is_failed(&self) -> bool { false } fn is_constrained(&self) -> bool { false } fn contains(&self, other: HalfRange) -> bool { self.min <= other.min } fn restrict(&mut self, other: HalfRange) { self.min = std::cmp::max(self.min, other.min); } } impl NumSet for HalfRange { type Universe = (); fn min_value(&self, _: &()) -> u32 { self.min } fn max_value(&self, _: &()) -> u32 { std::u32::MAX } } impl NumDomain for HalfRange { fn new_gt<D: NumSet>(_: &(), min: D, min_universe: &D::Universe) -> Self { let min = min.min_value(min_universe).saturating_add(1); HalfRange { min } } fn new_lt<D: NumSet>(_: &(), _: D, _: &D::Universe) -> Self { HalfRange::ALL } fn new_geq<D: NumSet>(_: &(), min: D, min_universe: &D::Universe) -> Self { HalfRange { min: min.min_value(min_universe) } } fn new_leq<D: NumSet>(_: &(), _: D, _: &D::Universe) -> Self { HalfRange::ALL } fn new_eq<D: NumSet>(_: &(), eq: D, eq_universe: &D::Universe) -> Self { HalfRange { min: eq.min_value(eq_universe) } } } impl fmt::Display for HalfRange { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{}..", self.min) } } } }
pub mod portfire; pub mod script; #[cfg(feature="tts")] pub mod tts;
pub mod consts;