text
stringlengths
8
4.13M
use juniper::{ graphql_object, EmptySubscription, FieldError, GraphQLInputObject, GraphQLObject, RootNode, }; use serde::{Deserialize, Serialize}; use crate::db::Db; type FieldResult<T> = std::result::Result<T, FieldError>; fn timestamp() -> String { chrono::Local::now().naive_utc().format("%+").to_string() } #[derive(Clone, GraphQLObject, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct Image { pub id: String, pub filename: Option<String>, pub tags: Option<Vec<String>>, pub access_count: Option<i32>, pub access_date: Option<String>, pub release_date: Option<String>, } #[derive(Clone, GraphQLInputObject, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct NewImage { pub id: String, pub filename: Option<String>, pub tags: Option<Vec<String>>, pub access_count: Option<i32>, pub access_date: Option<String>, pub release_date: Option<String>, } impl From<NewImage> for Image { fn from(new: NewImage) -> Self { Self { id: new.id, filename: new.filename, tags: new.tags, access_count: new.access_count, access_date: new.access_date, release_date: new.release_date, } } } pub struct Context { db: Db, } impl Context { pub fn new(db: Db) -> Self { Self { db } } } impl juniper::Context for Context {} pub struct Query; #[graphql_object(context = Context)] impl Query { fn version() -> String { "1.0".into() } #[graphql(arguments(ids(description = "list of the ids of the images")))] fn images(ctx: &Context, ids: Option<Vec<String>>) -> FieldResult<Vec<Image>> { let imgs = match ids { Some(ids) => { let imgs: Result<Vec<_>, _> = ids .into_iter() .map(|id| ctx.db.get(&id)) .filter_map(|i| i.transpose()) .collect(); imgs? } None => ctx.db.list()?, }; Ok(imgs) } #[graphql(arguments(id(description = "id of the image")))] fn image(ctx: &Context, id: String) -> FieldResult<Option<Image>> { let img = ctx.db.get(&id)?; Ok(img) } } pub struct Mutation; #[graphql_object(context = Context)] impl Mutation { fn apiVersion() -> String { "1.0".into() } #[graphql(arguments(image(description = "set new image object")))] fn image(ctx: &Context, image: NewImage) -> FieldResult<Image> { ctx.db.set(&image.id, &image)?; Ok(image.into()) } #[graphql(arguments(id(description = "id of the image")))] fn access(ctx: &Context, id: String) -> FieldResult<Option<Image>> { let img: Option<Image> = ctx.db.get(&id)?; match img { Some(mut img) => { img.access_count = Some(img.access_count.unwrap_or(0) + 1); img.access_date = Some(timestamp()); ctx.db.set(&img.id, &img)?; Ok(Some(img)) } None => Ok(None), } } } pub type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Context>>; pub fn schema() -> Schema { Schema::new(Query, Mutation, EmptySubscription::<Context>::new()) }
use actix::Addr; use actix_identity::Identity; use actix_web::{ web::{block, Data}, HttpResponse, Result, }; use auth::{get_claim_from_identity, PrivateClaim, Role}; use db::{get_conn, models::Round, Connection, PgPool}; use errors::Error; use crate::websocket::{client_messages, Server}; pub async fn lock_round( id: Identity, websocket_srv: Data<Addr<Server>>, pool: Data<PgPool>, ) -> Result<HttpResponse, Error> { let (claim, _) = get_claim_from_identity(id)?; if claim.role != Role::Owner { return Err(Error::Forbidden); } let conn = get_conn(&pool)?; let res: Result<(Connection, PrivateClaim), Error> = block(move || { let round = Round::get_active_round_by_game_id(&conn, claim.game_id)?; Round::lock(&conn, round.id)?; Ok((conn, claim)) }) .await?; let (conn, claim) = res?; client_messages::send_game_status(&websocket_srv, conn, claim.game_id).await; let conn = get_conn(&pool)?; client_messages::send_round_status(&websocket_srv, conn, claim.role, claim.id, claim.game_id) .await; Ok(HttpResponse::Ok().json(())) } #[cfg(test)] mod tests { use actix_web_actors::ws; use awc::Client; use diesel::{self, ExpressionMethods, QueryDsl, RunQueryDsl}; use futures::{SinkExt, StreamExt}; use serde_json; use auth::{create_jwt, PrivateClaim, Role}; use db::{ get_conn, models::{Game, Round}, new_pool, schema::{games, rounds}, }; use errors::ErrorResponse; use crate::handlers::{RoundStatusRepsonse, StatusResponse}; use crate::tests::helpers::tests::{get_test_server, get_websocket_frame_data, test_post}; #[derive(Insertable)] #[table_name = "games"] struct NewGame { slug: Option<String>, } #[derive(Insertable)] #[table_name = "rounds"] pub struct NewRound { player_one: String, player_two: String, game_id: i32, locked: bool, } #[actix_rt::test] async fn test_lock_current_round() { let pool = new_pool(); let conn = get_conn(&pool).unwrap(); let game: Game = diesel::insert_into(games::table) .values(NewGame { slug: Some("abc123".to_string()), }) .get_result(&conn) .unwrap(); diesel::insert_into(rounds::table) .values(vec![ NewRound { player_one: "maru".to_string(), player_two: "zest".to_string(), game_id: game.id, locked: false, }, NewRound { player_one: "serral".to_string(), player_two: "ty".to_string(), game_id: game.id, locked: true, }, ]) .execute(&conn) .unwrap(); let slug = game.slug.as_ref().unwrap().clone(); let claim = PrivateClaim::new(game.id, slug, game.id, Role::Owner); let token = create_jwt(claim).unwrap(); let srv = get_test_server(); let client = Client::default(); let mut ws_conn = client.ws(srv.url("/ws/")).connect().await.unwrap(); // auth this user with the websocket server ws_conn .1 .send(ws::Message::Text( format!("/auth {{\"token\":\"{}\"}}", token).into(), )) .await .unwrap(); let res = srv .post("/api/rounds/lock") .append_header(("Authorization", token)) .send() .await .unwrap(); assert_eq!(res.status().as_u16(), 200); let mut stream = ws_conn.1.take(3); // skip the first one, as it's a heartbeat stream.next().await; let msg = stream.next().await; let data = get_websocket_frame_data(msg.unwrap().unwrap()); if data.is_some() { let msg = data.unwrap(); assert_eq!(msg.path, "/game-status"); assert_eq!(msg.game_id, game.id); let game_status: StatusResponse = serde_json::from_value(msg.data).unwrap(); // both rounds are locked assert_eq!(game_status.open_round, false); assert_eq!(game_status.unfinished_round, true); assert_eq!(game_status.slug, game.slug.unwrap()); } else { assert!(false, "Message was not a string"); } let msg = stream.next().await; let data = get_websocket_frame_data(msg.unwrap().unwrap()); if data.is_some() { let msg = data.unwrap(); assert_eq!(msg.path, "/round-status"); assert_eq!(msg.game_id, game.id); let round_status: RoundStatusRepsonse = serde_json::from_value(msg.data).unwrap(); assert_eq!(round_status.locked, true); } else { assert!(false, "Message was not a string"); } drop(stream); srv.stop().await; let results: Vec<Round> = rounds::dsl::rounds .filter(rounds::dsl::game_id.eq(game.id)) .get_results(&conn) .unwrap(); assert_eq!(results.len(), 2); assert_eq!(results[0].locked, true); assert_eq!(results[1].locked, true); diesel::delete(rounds::table).execute(&conn).unwrap(); diesel::delete(games::table).execute(&conn).unwrap(); } #[actix_rt::test] async fn test_lock_current_round_forbidden_for_player() { let pool = new_pool(); let conn = get_conn(&pool).unwrap(); let game: Game = diesel::insert_into(games::table) .values(NewGame { slug: Some("abc123".to_string()), }) .get_result(&conn) .unwrap(); diesel::insert_into(rounds::table) .values(vec![ NewRound { player_one: "maru".to_string(), player_two: "zest".to_string(), game_id: game.id, locked: false, }, NewRound { player_one: "serral".to_string(), player_two: "ty".to_string(), game_id: game.id, locked: true, }, ]) .execute(&conn) .unwrap(); let claim = PrivateClaim::new(game.id, game.slug.unwrap(), game.id, Role::Player); let token = create_jwt(claim).unwrap(); let res: (u16, ErrorResponse) = test_post("/api/rounds/lock", (), Some(token)).await; assert_eq!(res.0, 403); diesel::delete(rounds::table).execute(&conn).unwrap(); diesel::delete(games::table).execute(&conn).unwrap(); } #[actix_rt::test] async fn test_lock_current_round_no_active_round() { let pool = new_pool(); let conn = get_conn(&pool).unwrap(); let game: Game = diesel::insert_into(games::table) .values(NewGame { slug: Some("abc123".to_string()), }) .get_result(&conn) .unwrap(); diesel::insert_into(rounds::table) .values(vec![ NewRound { player_one: "maru".to_string(), player_two: "zest".to_string(), game_id: game.id, locked: true, }, NewRound { player_one: "serral".to_string(), player_two: "ty".to_string(), game_id: game.id, locked: true, }, ]) .execute(&conn) .unwrap(); let claim = PrivateClaim::new(game.id, game.slug.unwrap(), game.id, Role::Owner); let token = create_jwt(claim).unwrap(); let res: (u16, ErrorResponse) = test_post("/api/rounds/lock", (), Some(token)).await; assert_eq!(res.0, 404); diesel::delete(rounds::table).execute(&conn).unwrap(); diesel::delete(games::table).execute(&conn).unwrap(); } }
// 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. // run-pass #![allow(non_upper_case_globals)] trait HasNumber<T> { const Number: usize; } enum One {} enum Two {} enum Foo {} impl<T> HasNumber<T> for One { const Number: usize = 1; } impl<T> HasNumber<T> for Two { const Number: usize = 2; } fn main() {}
// Copyright 2018 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. //! This is the client library for interacting with the Cobalt FIDL service. #![deny(missing_docs)] pub mod cobalt_event_builder; pub mod connector; pub mod sender; pub mod traits; use futures::prelude::*; pub use { cobalt_event_builder::CobaltEventExt, connector::{CobaltConnector, ConnectionType}, sender::CobaltSender, }; /// Helper function to connect to the cobalt FIDL service. /// /// # Arguments /// /// * `buffer_size` - The number of cobalt events that can be buffered before being sent to the /// Cobalt FIDL service. /// * `connection_type` - A `ConnectionType` object that defines how to connect to the Cobalt FIDL /// service. /// /// # Example /// /// ```no_run /// cobalt_fidl::serve(100, ConnectionType::project_name("test_project")); /// ``` pub fn serve( buffer_size: usize, connection_type: ConnectionType, ) -> (CobaltSender, impl Future<Output = ()>) { CobaltConnector { buffer_size, ..Default::default() }.serve(connection_type) }
#[derive(Debug, Copy, Clone, PartialEq)] pub enum Operation { Acc, Jmp, Nop, } #[derive(Debug)] pub struct Instruction { pub op: Operation, arg: i32, } #[derive(Debug)] pub struct Emulator<'a> { code: &'a Vec<Instruction>, pc: usize, acc: i32 } impl<'a> Emulator<'a> { pub fn new(code: &Vec<Instruction>) -> Emulator { Emulator { code: code, pc: 0, acc: 0, } } pub fn str_to_instructions(input: String) -> Instruction { let space_idx = input.find(" ").unwrap(); let op = match &input[0..space_idx] { "acc" => Operation::Acc, "jmp" => Operation::Jmp, "nop" => Operation::Nop, _ => panic!("Invalid operation!"), }; let val: i32 = match input[space_idx + 2..].parse() { Ok(v) => v, Err(_) => panic!("Invalid argument value!"), }; let arg = match input.chars().nth(space_idx + 1).unwrap() { '+' => val, '-' => -1 * val, _ => panic!("Invalid argument sign!"), }; Instruction { op: op, arg: arg, } } // Runs one instruction, returns (pc, acc) pub fn run_instruction(&mut self) -> (usize, i32) { let inst = match self.code.get(self.pc) { Some(i) => i, None => panic!("Instruction out of bounds!"), }; match inst.op { Operation::Acc => { self.acc += inst.arg; self.pc += 1; }, Operation::Jmp => self.pc = add(self.pc, inst.arg), Operation::Nop => self.pc += 1, }; (self.pc, self.acc) } } fn add(u: usize, i: i32) -> usize { if i.is_negative() { u - i.wrapping_abs() as usize } else { u + i as usize } }
#[macro_use] extern crate tera; use actix_files as fs; use actix_session::{CookieSession, Session}; use actix_utils::mpsc; use actix_http::{body::Body, Response}; use actix_web::{ dev::ServiceResponse, http::StatusCode, middleware::{ self, errhandlers::{ ErrorHandlerResponse, ErrorHandlers } }, get, post, web, App, HttpServer, Responder, error, HttpRequest, HttpResponse, Error, Result }; use std::{ env, io, collections::HashMap }; use tera::Tera; mod models; mod todo; #[get("/favicon")] async fn favicon() -> Result<fs::NamedFile> { Ok(fs::NamedFile::open("static/favicon.ico")?) } #[post("/event")] async fn capture_event(evt: web::Json<models::Event>) -> impl Responder { format!("dapat event {:?}", evt) } #[get("/temperature")] async fn current_temperature() -> impl Responder { web::Json(models::Measurement { temperature: 42.3 }) } #[post("/register")] async fn register(form: web::Form<models::Register>) -> impl Responder { format!("Hello {} from {}!", form.username, form.country) } // http://localhost:8088/1/agus/index.html #[get("/greeting/{id}/{name}/index.html")] async fn greeting(info: web::Path<(u32, String)>) -> impl Responder { format!("Hello {:?}! id: {:?}", info.1, info.0) } #[get("/")] async fn index() -> impl Responder { format!("Hello world!") } async fn hello(path: web::Path<String>) -> impl Responder { format!("Hello {}!", &path) } async fn hello_tera( tmpl: web::Data<tera::Tera>, query: web::Query<HashMap<String, String>>, ) -> Result<HttpResponse, Error> { let s = if let Some(name) = query.get("name") { let mut ctx = tera::Context::new(); ctx.insert("name", &name.to_owned()); ctx.insert("text", &"Welcome!".to_owned()); tmpl.render("user.html", &ctx) .map_err(|_| error::ErrorInternalServerError("Template Error"))? } else { tmpl.render("index.html", &tera::Context::new()) .map_err(|_| error::ErrorInternalServerError("Template Error"))? }; Ok(HttpResponse::Ok().content_type("text/html").body(s)) } #[get("/welcome")] async fn welcome(session: Session, req: HttpRequest) -> Result<HttpResponse> { println!("{:?}", req); let mut counter = 1; if let Some(count) = session.get::<i32>("counter")? { println!("Session value: {}", count); counter = count + 1; } session.set("counter", counter)?; Ok(HttpResponse::build(StatusCode::OK) .content_type("text/html; charset=utf-8") .body(include_str!("../static/welcome.html")) ) } async fn response_body(path: web::Path<String>) -> HttpResponse { let text = format!("Hello {}!", *path); let (tx, rx_body) = mpsc::channel(); let _ = tx.send(Ok::<_, Error>(web::Bytes::from(text))); HttpResponse::Ok().streaming(rx_body) } #[actix_web::main] async fn main() -> io::Result<()> { std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); HttpServer::new(move || { let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap(); App::new() .wrap(CookieSession::signed(&[0; 32]).secure(false)) .wrap(middleware::Logger::default()) .data(tera) .service(favicon) .service(welcome) .service(web::resource("/hello-tera").route(web::get().to(hello_tera))) .service(index) .service(greeting) .service(current_temperature) .service(capture_event) .service(register) .service(fs::Files::new("/static", "static").show_files_listing()) .service( web::resource("/async-body/{name}").route(web::get().to(response_body)) ) .route("/hello/{name}", web::get().to(hello)) .service(web::scope("").wrap(error_handlers())) }) .bind("127.0.0.1:8088")? .run() .await } fn error_handlers() -> ErrorHandlers<Body> { ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found) } fn not_found<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { let response = get_error_response(&res, "Page not found"); Ok(ErrorHandlerResponse::Response( res.into_response(response.into_body()), )) } fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> Response<Body> { let request = res.request(); let fallback = |e: &str| { Response::build(res.status()) .content_type("text/plain") .body(e.to_string()) }; let tera = request.app_data::<web::Data<Tera>>().map(|t| t.get_ref()); match tera { Some(tera) => { let mut context = tera::Context::new(); context.insert("error", error); context.insert("status_code", res.status().as_str()); let body = tera.render("error.html", &context); match body { Ok(body) => Response::build(res.status()) .content_type("text/html") .body(body), Err(_) => fallback(error), } } None => fallback(error) } }
use crate::lz4; use crate::entity::EntityEntry; use crate::vec2::{vec2,Vec2}; pub struct DataDef { pub offset: usize, pub pal: usize, } impl DataDef { pub fn data(&self) -> &'static [u8] { unsafe { &DATA[self.offset..] } } pub fn pal(&self) -> &'static [u32] { &PAL_DATA[self.pal..] } } pub struct LevelDef { pub offset: usize, pub width: u8, pub height: u8, pub start_pos: Vec2<i32> } impl LevelDef { pub fn data(&self) -> &'static [u8] { unsafe { &DATA[self.offset..] } } } pub fn init() { unsafe { lz4::decompress(&DATA_LZ4, &mut DATA) }; } include!(concat!(env!("OUT_DIR"), "/data.rs"));
#![allow(dead_code)] use crate::{aocbail, utils}; use std::iter::Peekable; use utils::{AOCError, AOCResult}; pub fn re_weird_parse( tokens: &mut Peekable<impl Iterator<Item = char>>, precedence: bool, greedy: bool, ) -> AOCResult<u64> { let mut left_expr = match tokens.next()? { '(' => { let expr = re_weird_parse(tokens, precedence, false)?; if tokens.next()? != ')' { aocbail!("Expected closing parens"); } expr } x => x.to_digit(10)? as u64, }; while let Some(token) = tokens.peek() { if greedy || *token == ')' { break; } let next_add = tokens.next()? == '+'; let right_expr = re_weird_parse(tokens, precedence, !precedence || next_add)?; if next_add { left_expr += right_expr; } else { left_expr *= right_expr; } } Ok(left_expr) } fn weird_parse(input: &str, precedence: bool) -> AOCResult<u64> { re_weird_parse( &mut input.chars().filter(|c| *c != ' ').peekable(), precedence, false, ) } pub fn day18() { let (s1, s2) = utils::get_input("day18").fold((0, 0), |(a1, a2), line| { ( a1 + weird_parse(&line, false).unwrap(), a2 + weird_parse(&line, true).unwrap(), ) }); println!("operation_order part 1: {:?}", s1); println!("operation_order part 2: {:?}", s2); } #[cfg(test)] mod tests { use crate::day18::*; #[test] pub fn test_day18() { assert_eq!(weird_parse("2 * 3 + (4 * 5)", false).unwrap(), 26); assert_eq!( weird_parse("1 + (2 * 3) + (4 * (5 + 6))", true).unwrap(), 51 ); assert_eq!(weird_parse("2 * 3 + (4 * 5)", true).unwrap(), 46); assert_eq!( weird_parse("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2", true).unwrap(), 23340 ); } }
pub mod root { // use std::fmt::Pointer; use std::alloc::Layout; use std::collections::HashMap; use std::ptr::hash; struct Test { name: String } impl std::fmt::Display for Test { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Name of Test struct: {}", self.name) } } impl Test { pub fn string_pointer(s: &str) -> usize { // s.make_ascii_lowercase(); s.len() } } // impl Test { // fn clone(&self) -> Test { // self. // // return Test { // ..self // } // } // } pub fn print_from_module(){ let t = Test { name: String::from("pronk") }; // t.clone(); // let t2 = Test { // ..t // }; // let t_ref = &mut t; // let t2_ref = &t2; { let mut v: Vec<&Test> = Vec::new(); v.push(&t); println!("veccie: {}", &v[0]) } { //alloc* let mut str = "broepie"; Test::string_pointer(str); println!("{}", t); //Transfer ownership (= transfer all values from stack from t.name to x) //heap value remains unchanged //rust has no invalidated and no longer allows usage of t.name //this to prevent the variable from potentially going out of scope twice; causing bugs //this because t.name no longer owns the associated piece of memory //the associated piece of memory is now owned by x let x = t.name; //Should not cause println to crahs //let x = &t.name; const INT_LITERAL: u32 = 500_000; //_ ayyy let veccy = vec![1, 2]; let veccy_keys = vec![String::from("s1"), String::from("s2")]; //veccy and veccy_keys are both consumed by into_iter/zip //values are moved out of the original vectors //collect() can become many a type; thus we need to help Rust by typehinting to HashMap<> //both key and value type can be inferred and thus we can discard those via an underscore let mut hashy: HashMap<_, _> = veccy_keys.into_iter().zip(veccy).collect(); println!("Length (should be 2): {}", hashy.len()); //Insert overwrites existing values hashy.insert(String::from("s1"), 4); println!("Length (should be 2): {}", hashy.len()); //Only insert when not present hashy.entry(String::from("s1")).or_insert(5); //Rust automagically marks our variable as mutable let entry_s3 = hashy.entry(String::from("s3")).or_insert(9); *entry_s3 += 1; println!("Length (should be 3): {}", hashy.len()); // veccy_keys.push(1); //Should crash; t.name is no longer owner by t // println!("{}", t); //Create pointer let x2 = &x; //Kabüm //let y = t.name; } //free (= drop) } }
extern crate reqwest; use dotenv::dotenv; use std::collections::HashMap; use std::env; use std::io::Read; fn main() { // load env vars dotenv().ok(); use env::var; let client_id = var("PLAID_CLIENT_ID").unwrap(); let secret = var("PLAID_SECRET").unwrap(); let access_token = var("PLAID_TOKEN").unwrap(); let start_date = String::from("2019-05-01"); let end_date = String::from("2019-05-02"); let mut body = HashMap::new(); body.insert("client_id", client_id); body.insert("secret", secret); body.insert("access_token", access_token); body.insert("start_date", start_date); body.insert("end_date", end_date); let client = reqwest::Client::new(); let mut response = client .post("https://development.plaid.com/transactions/get") .header("Content-Type", "application/json") .header("Plaid-Version", "2019-05-29") .json(&body) .send() .expect("Failed to send request"); let mut buf = String::new(); response .read_to_string(&mut buf) .expect("Failed to read response"); println!("{}", buf); }
use crate::config::PlatformConfiguration; use crate::errors::*; use crate::overlay::Overlayer; use crate::project::Project; use crate::toolchain::Toolchain; use crate::Build; use crate::Device; use crate::Platform; use crate::SetupArgs; use dinghy_build::build_env::set_env; use std::fmt::{Debug, Display, Formatter}; use std::process; pub struct IosPlatform { id: String, pub sim: bool, pub toolchain: Toolchain, pub configuration: PlatformConfiguration, } impl Debug for IosPlatform { fn fmt(&self, fmt: &mut Formatter) -> ::std::fmt::Result { write!(fmt, "{}", self.id) } } impl IosPlatform { pub fn new( id: String, rustc_triple: &str, configuration: PlatformConfiguration, ) -> Result<Box<dyn Platform>> { Ok(Box::new(IosPlatform { id, sim: rustc_triple.contains("86") || rustc_triple.contains("sim"), toolchain: Toolchain { rustc_triple: rustc_triple.to_string(), }, configuration, })) } fn sysroot_path(&self) -> Result<String> { let sdk_name = if self.sim { "iphonesimulator" } else { "iphoneos" }; let xcrun = process::Command::new("xcrun") .args(&["--sdk", sdk_name, "--show-sdk-path"]) .output()?; Ok(String::from_utf8(xcrun.stdout)?.trim_end().to_string()) } } impl Platform for IosPlatform { fn setup_env(&self, project: &Project, setup_args: &SetupArgs) -> Result<()> { let sysroot = self.sysroot_path()?; Overlayer::overlay(&self.configuration, self, project, &self.sysroot_path()?)?; self.toolchain.setup_cc(self.id().as_str(), "gcc")?; set_env("TARGET_SYSROOT", &sysroot); self.toolchain.setup_linker( &self.id(), &format!("cc -isysroot {}", sysroot), &project.metadata.workspace_root, )?; self.toolchain.setup_runner(&self.id(), setup_args)?; self.toolchain.setup_target()?; self.toolchain.setup_pkg_config()?; Ok(()) } fn id(&self) -> String { self.id.to_string() } fn is_compatible_with(&self, device: &dyn Device) -> bool { device.is_compatible_with_ios_platform(self) } fn is_host(&self) -> bool { false } fn rustc_triple(&self) -> &str { &self.toolchain.rustc_triple } fn strip(&self, build: &mut Build) -> Result<()> { let mut command = ::std::process::Command::new("xcrun"); command.arg("strip"); build.runnable = crate::platform::strip_runnable(&build.runnable, command)?; Ok(()) } fn sysroot(&self) -> Result<Option<std::path::PathBuf>> { self.sysroot_path().map(|s| Some(s.into())) } } impl Display for IosPlatform { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::result::Result<(), ::std::fmt::Error> { if self.sim { write!(f, "XCode targetting Ios Simulator") } else { write!(f, "XCode targetting Ios Device") } } }
pub struct MonsterSpawner{ pub zombie_spawn_chance: f64, pub wolf_pack_spawn_chance: f64 }
use int::Int; macro_rules! div { ($intrinsic:ident: $ty:ty, $uty:ty) => { div!($intrinsic: $ty, $uty, $ty, |i| {i}); }; ($intrinsic:ident: $ty:ty, $uty:ty, $tyret:ty, $conv:expr) => { /// Returns `a / b` #[cfg_attr(not(test), no_mangle)] pub extern "C" fn $intrinsic(a: $ty, b: $ty) -> $tyret { let s_a = a >> (<$ty>::bits() - 1); let s_b = b >> (<$ty>::bits() - 1); // NOTE it's OK to overflow here because of the `as $uty` cast below // This whole operation is computing the absolute value of the inputs // So some overflow will happen when dealing with e.g. `i64::MIN` // where the absolute value is `(-i64::MIN) as u64` let a = (a ^ s_a).wrapping_sub(s_a); let b = (b ^ s_b).wrapping_sub(s_b); let s = s_a ^ s_b; let r = udiv!(a as $uty, b as $uty); ($conv)((r as $ty ^ s) - s) } } } macro_rules! mod_ { ($intrinsic:ident: $ty:ty, $uty:ty) => { mod_!($intrinsic: $ty, $uty, $ty, |i| {i}); }; ($intrinsic:ident: $ty:ty, $uty:ty, $tyret:ty, $conv:expr) => { /// Returns `a % b` #[cfg_attr(not(test), no_mangle)] pub extern "C" fn $intrinsic(a: $ty, b: $ty) -> $tyret { let s = b >> (<$ty>::bits() - 1); // NOTE(wrapping_sub) see comment in the `div` macro let b = (b ^ s).wrapping_sub(s); let s = a >> (<$ty>::bits() - 1); let a = (a ^ s).wrapping_sub(s); let r = urem!(a as $uty, b as $uty); ($conv)((r as $ty ^ s) - s) } } } macro_rules! divmod { ($abi:tt, $intrinsic:ident, $div:ident: $ty:ty) => { /// Returns `a / b` and sets `*rem = n % d` #[cfg_attr(not(test), no_mangle)] pub extern $abi fn $intrinsic(a: $ty, b: $ty, rem: &mut $ty) -> $ty { #[cfg(all(feature = "c", any(target_arch = "x86")))] extern { fn $div(a: $ty, b: $ty) -> $ty; } let r = match () { #[cfg(not(all(feature = "c", any(target_arch = "x86"))))] () => $div(a, b), #[cfg(all(feature = "c", any(target_arch = "x86")))] () => unsafe { $div(a, b) }, }; // NOTE won't overflow because it's using the result from the // previous division *rem = a - r.wrapping_mul(b); r } } } #[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"), not(thumbv6m))))] div!(__divsi3: i32, u32); #[cfg(not(all(feature = "c", target_arch = "x86")))] div!(__divdi3: i64, u64); #[cfg(not(all(windows, target_pointer_width="64")))] div!(__divti3: i128, u128); #[cfg(all(windows, target_pointer_width="64"))] div!(__divti3: i128, u128, ::U64x2, ::sconv); #[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"))))] mod_!(__modsi3: i32, u32); #[cfg(not(all(feature = "c", target_arch = "x86")))] mod_!(__moddi3: i64, u64); #[cfg(not(all(windows, target_pointer_width="64")))] mod_!(__modti3: i128, u128); #[cfg(all(windows, target_pointer_width="64"))] mod_!(__modti3: i128, u128, ::U64x2, ::sconv); #[cfg(not(all(feature = "c", target_arch = "arm", not(target_os = "ios"))))] divmod!("C", __divmodsi4, __divsi3: i32); #[cfg(target_arch = "arm")] divmod!("aapcs", __divmoddi4, __divdi3: i64); #[cfg(not(target_arch = "arm"))] divmod!("C", __divmoddi4, __divdi3: i64);
use nom::*; use nom::types::*; use std::str; use std::str::FromStr; use std::str::Utf8Error; pub mod token; use lexer::token::*; // operators named!(equal_operator<CompleteByteSlice, Token>, do_parse!(tag!("==") >> (Token::Equal)) ); named!(not_equal_operator<CompleteByteSlice, Token>, do_parse!(tag!("!=") >> (Token::NotEqual)) ); named!(assign_operator<CompleteByteSlice, Token>, do_parse!(tag!("=") >> (Token::Assign)) ); named!(plus_operator<CompleteByteSlice, Token>, do_parse!(tag!("+") >> (Token::Plus)) ); named!(minus_operator<CompleteByteSlice, Token>, do_parse!(tag!("-") >> (Token::Minus)) ); named!(multiply_operator<CompleteByteSlice, Token>, do_parse!(tag!("*") >> (Token::Multiply)) ); named!(divide_operator<CompleteByteSlice, Token>, do_parse!(tag!("/") >> (Token::Divide)) ); named!(not_operator<CompleteByteSlice, Token>, do_parse!(tag!("!") >> (Token::Not)) ); named!(greater_operator_equal<CompleteByteSlice, Token>, do_parse!(tag!(">=") >> (Token::GreaterThanEqual)) ); named!(lesser_operator_equal<CompleteByteSlice, Token>, do_parse!(tag!("<=") >> (Token::LessThanEqual)) ); named!(greater_operator<CompleteByteSlice, Token>, do_parse!(tag!(">") >> (Token::GreaterThan)) ); named!(lesser_operator<CompleteByteSlice, Token>, do_parse!(tag!("<") >> (Token::LessThan)) ); named!(lex_operator<CompleteByteSlice, Token>, alt!( equal_operator | not_equal_operator | assign_operator | plus_operator | minus_operator | multiply_operator | divide_operator | not_operator | greater_operator_equal | lesser_operator_equal | greater_operator | lesser_operator )); // punctuations named!(comma_punctuation<CompleteByteSlice, Token>, do_parse!(tag!(",") >> (Token::Comma)) ); named!(semicolon_punctuation<CompleteByteSlice, Token>, do_parse!(tag!(";") >> (Token::SemiColon)) ); named!(colon_punctuation<CompleteByteSlice, Token>, do_parse!(tag!(":") >> (Token::Colon)) ); named!(lparen_punctuation<CompleteByteSlice, Token>, do_parse!(tag!("(") >> (Token::LParen)) ); named!(rparen_punctuation<CompleteByteSlice, Token>, do_parse!(tag!(")") >> (Token::RParen)) ); named!(lbrace_punctuation<CompleteByteSlice, Token>, do_parse!(tag!("{") >> (Token::LBrace)) ); named!(rbrace_punctuation<CompleteByteSlice, Token>, do_parse!(tag!("}") >> (Token::RBrace)) ); named!(lbracket_punctuation<CompleteByteSlice, Token>, do_parse!(tag!("[") >> (Token::LBracket)) ); named!(rbracket_punctuation<CompleteByteSlice, Token>, do_parse!(tag!("]") >> (Token::RBracket)) ); named!(lex_punctuations<CompleteByteSlice, Token>, alt!( comma_punctuation | semicolon_punctuation | colon_punctuation | lparen_punctuation | rparen_punctuation | lbrace_punctuation | rbrace_punctuation | lbracket_punctuation | rbracket_punctuation )); // Strings fn pis(input: CompleteByteSlice) -> IResult<CompleteByteSlice, Vec<u8>> { use std::result::Result::*; let (i1, c1) = try_parse!(input, take!(1)); match c1.as_bytes() { b"\"" => Ok((input, vec![])), b"\\" => { let (i2, c2) = try_parse!(i1, take!(1)); pis(i2).map(|(slice, done)| (slice, concat_slice_vec(c2.0, done))) } c => { pis(i1).map(|(slice, done)| (slice, concat_slice_vec(c, done))) }, } } fn concat_slice_vec(c: &[u8], done: Vec<u8>) -> Vec<u8> { let mut new_vec = c.to_vec(); new_vec.extend(&done); new_vec } fn convert_vec_utf8(v: Vec<u8>) -> Result<String, Utf8Error> { let slice = v.as_slice(); str::from_utf8(slice).map(|s| s.to_owned()) } named!(string<CompleteByteSlice, String>, delimited!( tag!("\""), map_res!(pis, convert_vec_utf8), tag!("\"") ) ); named!(lex_string<CompleteByteSlice, Token>, do_parse!( s: string >> (Token::StringLiteral(s)) ) ); macro_rules! check( ($input:expr, $submac:ident!( $($args:tt)* )) => ( { use std::result::Result::*; use nom::{Err,ErrorKind}; let mut failed = false; for &idx in $input.0 { if !$submac!(idx, $($args)*) { failed = true; break; } } if failed { let e: ErrorKind<u32> = ErrorKind::Tag; Err(Err::Error(error_position!($input, e))) } else { Ok((&b""[..], $input)) } } ); ($input:expr, $f:expr) => ( check!($input, call!($f)); ); ); // Reserved or ident fn parse_reserved(c: CompleteStr, rest: Option<CompleteStr>) -> Token { let mut string = c.0.to_owned(); string.push_str(rest.unwrap_or(CompleteStr("")).0); match string.as_ref() { "let" => Token::Let, "fn" => Token::Function, "if" => Token::If, "else" => Token::Else, "return" => Token::Return, "true" => Token::BoolLiteral(true), "false" => Token::BoolLiteral(false), _ => Token::Ident(string), } } fn complete_byte_slice_str_from_utf8(c: CompleteByteSlice) -> Result<CompleteStr, Utf8Error> { str::from_utf8(c.0).map(|s| CompleteStr(s)) } named!(take_1_char<CompleteByteSlice, CompleteByteSlice>, flat_map!(take!(1), check!(is_alphabetic)) ); named!(lex_reserved_ident<CompleteByteSlice, Token>, do_parse!( c: map_res!(call!(take_1_char), complete_byte_slice_str_from_utf8) >> rest: opt!(complete!(map_res!(alphanumeric, complete_byte_slice_str_from_utf8))) >> (parse_reserved(c, rest)) ) ); fn complete_str_from_str<F: FromStr>(c: CompleteStr) -> Result<F, F::Err> { FromStr::from_str(c.0) } // Integers parsing named!(lex_integer<CompleteByteSlice, Token>, do_parse!( i: map_res!(map_res!(digit, complete_byte_slice_str_from_utf8), complete_str_from_str) >> (Token::IntLiteral(i)) ) ); // Illegal tokens named!(lex_illegal<CompleteByteSlice, Token>, do_parse!(take!(1) >> (Token::Illegal)) ); named!(lex_token<CompleteByteSlice, Token>, alt_complete!( lex_operator | lex_punctuations | lex_string | lex_reserved_ident | lex_integer | lex_illegal )); named!(lex_tokens<CompleteByteSlice, Vec<Token>>, ws!(many0!(lex_token))); pub struct Lexer; impl Lexer { pub fn lex_tokens(bytes: &[u8]) -> IResult<CompleteByteSlice, Vec<Token>> { lex_tokens(CompleteByteSlice(bytes)).map(|(slice, result)| (slice, [&result[..], &vec![Token::EOF][..]].concat()) ) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_lexer1() { let input = &b"=+(){},;"[..]; let (_, result) = Lexer::lex_tokens(input).unwrap(); let expected_results = vec![ Token::Assign, Token::Plus, Token::LParen, Token::RParen, Token::LBrace, Token::RBrace, Token::Comma, Token::SemiColon, Token::EOF, ]; assert_eq!(result, expected_results); } #[test] fn test_lexer2() { let input = "let five = 5;\ let ten = 10;\ let add = fn(x, y) {\ x + y;\ };\ let result = add(five, ten);" .as_bytes(); let (_, result) = Lexer::lex_tokens(input).unwrap(); let expected_results = vec![ Token::Let, Token::Ident("five".to_owned()), Token::Assign, Token::IntLiteral(5), Token::SemiColon, Token::Let, Token::Ident("ten".to_owned()), Token::Assign, Token::IntLiteral(10), Token::SemiColon, Token::Let, Token::Ident("add".to_owned()), Token::Assign, Token::Function, Token::LParen, Token::Ident("x".to_owned()), Token::Comma, Token::Ident("y".to_owned()), Token::RParen, Token::LBrace, Token::Ident("x".to_owned()), Token::Plus, Token::Ident("y".to_owned()), Token::SemiColon, Token::RBrace, Token::SemiColon, Token::Let, Token::Ident("result".to_owned()), Token::Assign, Token::Ident("add".to_owned()), Token::LParen, Token::Ident("five".to_owned()), Token::Comma, Token::Ident("ten".to_owned()), Token::RParen, Token::SemiColon, Token::EOF, ]; assert_eq!(result, expected_results); } #[test] fn test_lexer3() { let input = "if (a == 10) {\ return a;\ } else if (a != 20) {\ return !a;\ } else if (a > 20) {\ return -30 / 40 * 50;\ } else if (a < 30) {\ return true;\ }\ return false;\ " .as_bytes(); let (_, result) = Lexer::lex_tokens(input).unwrap(); let expected_results = vec![ Token::If, Token::LParen, Token::Ident("a".to_owned()), Token::Equal, Token::IntLiteral(10), Token::RParen, Token::LBrace, Token::Return, Token::Ident("a".to_owned()), Token::SemiColon, Token::RBrace, Token::Else, Token::If, Token::LParen, Token::Ident("a".to_owned()), Token::NotEqual, Token::IntLiteral(20), Token::RParen, Token::LBrace, Token::Return, Token::Not, Token::Ident("a".to_owned()), Token::SemiColon, Token::RBrace, Token::Else, Token::If, Token::LParen, Token::Ident("a".to_owned()), Token::GreaterThan, Token::IntLiteral(20), Token::RParen, Token::LBrace, Token::Return, Token::Minus, Token::IntLiteral(30), Token::Divide, Token::IntLiteral(40), Token::Multiply, Token::IntLiteral(50), Token::SemiColon, Token::RBrace, Token::Else, Token::If, Token::LParen, Token::Ident("a".to_owned()), Token::LessThan, Token::IntLiteral(30), Token::RParen, Token::LBrace, Token::Return, Token::BoolLiteral(true), Token::SemiColon, Token::RBrace, Token::Return, Token::BoolLiteral(false), Token::SemiColon, Token::EOF, ]; assert_eq!(result, expected_results); } #[test] fn string_literals() { let (_, result) = Lexer::lex_tokens(&b"\"foobar\""[..]).unwrap(); assert_eq!(result, vec![Token::StringLiteral("foobar".to_owned()), Token::EOF]); let (_, result) = Lexer::lex_tokens(&b"\"foo bar\""[..]).unwrap(); assert_eq!(result, vec![Token::StringLiteral("foo bar".to_owned()), Token::EOF]); let (_, result) = Lexer::lex_tokens(&b"\"foo\nbar\""[..]).unwrap(); assert_eq!(result, vec![Token::StringLiteral("foo\nbar".to_owned()), Token::EOF]); let (_, result) = Lexer::lex_tokens(&b"\"foo\tbar\""[..]).unwrap(); assert_eq!(result, vec![Token::StringLiteral("foo\tbar".to_owned()), Token::EOF]); let (_, result) = Lexer::lex_tokens(&b"\"foo\\\"bar\""[..]) .unwrap(); assert_eq!(result, vec![Token::StringLiteral("foo\"bar".to_owned()), Token::EOF]); let (_, result) = Lexer::lex_tokens(&b"\"foo\\\"bar with \xf0\x9f\x92\x96 emojis\""[..]) .unwrap(); assert_eq!(result, vec![Token::StringLiteral("foo\"bar with 💖 emojis".to_owned()), Token::EOF]); } #[test] fn id_with_numbers() { let (_, result) = Lexer::lex_tokens(&b"hello2 hel301oo120"[..]) .unwrap(); let expected = vec![ Token::Ident("hello2".to_owned()), Token::Ident("hel301oo120".to_owned()), Token::EOF, ]; assert_eq!(result, expected); } #[test] fn array_tokens() { let (_, result) = Lexer::lex_tokens(&b"[1, 2];"[..]).unwrap(); let expected = vec![ Token::LBracket, Token::IntLiteral(1), Token::Comma, Token::IntLiteral(2), Token::RBracket, Token::SemiColon, Token::EOF ]; assert_eq!(result, expected); } #[test] fn hash_tokens() { let (_, result) = Lexer::lex_tokens(&b"{\"hello\": \"world\"}"[..]) .unwrap(); let expected = vec![ Token::LBrace, Token::StringLiteral("hello".to_owned()), Token::Colon, Token::StringLiteral("world".to_owned()), Token::RBrace, Token::EOF, ]; assert_eq!(result, expected); } }
use crate::parsing::parse_bag_def; #[test] fn test1() { let bag = parse_bag_def("dotted black bags contain no other bags."); assert_eq!(bag.color, "dotted black"); assert!(bag.inner_bags.is_empty()); } #[test] fn test2() { let bag = parse_bag_def("bright white bags contain 1 shiny gold bag."); assert_eq!(bag.color, "bright white"); assert!(!bag.inner_bags.is_empty()); assert_eq!(bag.inner_bags.len(), 1); assert_eq!(bag.inner_bags.first().unwrap(), "shiny gold"); } #[test] fn test3() { let bag = parse_bag_def("muted yellow bags contain 2 shiny gold bags, 9 faded blue bags."); assert_eq!(bag.color, "muted yellow"); assert!(!bag.inner_bags.is_empty()); assert_eq!(bag.inner_bags.len(), 11); assert!(bag.inner_bags.contains(&"shiny gold".to_string())); assert!(bag.inner_bags.contains(&"faded blue".to_string())); }
#[doc = "Reader of register TXCNTMCOL"] pub type R = crate::R<u32, super::TXCNTMCOL>; #[doc = "Reader of field `TXMULTCOLG`"] pub type TXMULTCOLG_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - This field indicates the number of successfully transmitted frames after multiple collisions in the half-duplex mode"] #[inline(always)] pub fn txmultcolg(&self) -> TXMULTCOLG_R { TXMULTCOLG_R::new((self.bits & 0xffff_ffff) as u32) } }
//Subscribe use ws::{connect, Handler, Sender, Handshake, Message, CloseCode}; use serde_json::{Value}; use std::sync::Arc; use crate::api::config::Config; use crate::api::subscription::data::{ SubscribeResponse, SubscribeCommand }; pub struct Client { out: Sender, op: Arc<dyn Fn(Result<SubscribeResponse, serde_json::error::Error>)>, } impl Handler for Client { fn on_open(&mut self, _: Handshake) -> Result<(), ws::Error> { // Now we don't need to call unwrap since `on_open` returns a `Result<()>`. // If this call fails, it will only result in this connection disconnecting. if let Ok(command) = SubscribeCommand::default().to_string() { self.out.send(command).unwrap(); } Ok(()) } // `on_message` is roughly equivalent to the Handler closure. It takes a `Message` // and returns a `Result<()>`. fn on_message(&mut self, msg: Message) -> Result<(), ws::Error> { // Close the connection when we get a response from the server let resp = msg.into_text().unwrap(); if let Ok(x) = serde_json::from_str(&resp) as Result<Value, serde_json::error::Error> { let result: String = x["result"].to_string(); if let Ok(x) = serde_json::from_str(&result) as Result<SubscribeResponse, serde_json::error::Error> { //to call the function stored in `op`, surround the field access with parentheses (self.op)(Ok(x)) } else if let Ok(x) = serde_json::from_str(&resp) as Result<SubscribeResponse, serde_json::error::Error> { (self.op)(Ok(x)) } } Ok(()) } fn on_close(&mut self, code: CloseCode, reason: &str) { match code { CloseCode::Normal => println!("The client is done with the connection."), CloseCode::Away => println!("The client is leaving the site."), _ => println!("The client encountered an error: {}", reason), } } } pub fn on<F>(config: Config, op: F) where F: 'static + Fn(Result<SubscribeResponse, serde_json::error::Error>) + std::marker::Send { let op_rc = Arc::new(op); connect(config.addr, |out| { let op = op_rc.clone(); Client { out: out, op: op, } }).unwrap(); }
//! C API wrappers to work with a Telamon search space. use std; use super::error::TelamonStatus; use super::ir::Function; use telamon::search_space; /// Opaque type that abstracts away the lifetime parameter of /// `search_space::SearchSpace`. #[derive(Clone)] pub struct SearchSpace(pub(crate) search_space::SearchSpace); /// Creates a new search space from an IR function. The caller stays /// is responsible for freeing the instance and action pointers; the /// created search space does not keep references to them. /// /// Must be freed using `telamon_search_space_free`. /// /// # Safety /// /// * `ir_instance` must point to a valid `Function` value. /// * `actions` must point to a sequence of at least `num_actions` /// valid `Action` values, unless `num_actions` is 0 in which case /// `actions` is not used. #[no_mangle] pub unsafe extern "C" fn telamon_search_space_new( ir_instance: *const Function, num_actions: usize, actions: *const search_space::Action, ) -> *mut SearchSpace { // std::slice::from_raw_parts require that the `actions` // pointer be non-null, so we have a special case in order to // allow C API users to pass in a null pointer in that case. let actions = if num_actions == 0 { Vec::new() } else { std::slice::from_raw_parts(actions, num_actions).to_vec() }; let search_space = unwrap_or_exit!( search_space::SearchSpace::new((*ir_instance).clone().into(), actions), null ); Box::into_raw(Box::new(SearchSpace(search_space))) } /// Apply a sequence of actions to a search space. /// /// # Safety /// /// * `search_space` must be a valid pointer containing a valid /// `SearchSpace` value. /// * `num_actions` must be non-zero. /// * `actions` must point to a sequence of at least `num_actions` /// valid `Action` values. #[no_mangle] pub unsafe extern "C" fn telamon_search_space_apply( search_space: *mut SearchSpace, num_actions: usize, actions: *const search_space::Action, ) -> TelamonStatus { unwrap_or_exit!((*search_space) .0 .apply_decisions(std::slice::from_raw_parts(actions, num_actions).to_vec())); TelamonStatus::Ok } /// Frees a search space instance allocated through /// `telamon_search_space_new`. /// /// # Safety /// /// `search_space` must point to a `SearchSpace` object created by /// `telamon_search_space_new` which has not yet been freed. #[no_mangle] pub unsafe extern "C" fn telamon_search_space_free( search_space: *mut SearchSpace, ) -> TelamonStatus { std::mem::drop(Box::from_raw(search_space)); TelamonStatus::Ok }
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque}; use std::fmt::Debug; use itertools::Itertools; use whiteread::parse_line; const ten97: usize = 1000_000_007; /// 2の逆元 mod ten97.割りたいときに使う const inv2ten97: u128 = 500_000_004; fn main() { let n: usize = parse_line().unwrap(); let mut abab: VecDeque<(f64, f64)> = VecDeque::new(); for _ in 0..n { abab.push_back(parse_line().unwrap()); } // TODO: n = 1の場合競争 if n == 1 { println!("{}", abab[0].0 / 2.0); return; } let mut lline = abab.pop_front().unwrap(); let mut rline = abab.pop_back().unwrap(); let mut lbyo: f64 = lline.0 / lline.1; let mut rbyo: f64 = rline.0 / rline.1; let mut burned = 0.0; while !abab.is_empty() { if lbyo > rbyo { rline = abab.pop_back().unwrap(); rbyo += rline.0 / rline.1; } else { burned += lline.0; lline = abab.pop_front().unwrap(); lbyo += lline.0 / lline.1; } } if (lbyo - rbyo).abs() < std::f64::EPSILON { println!("{}", burned + lline.0); } else if lbyo > rbyo { burned += lline.0 - (lbyo - rbyo) * lline.1; let half = (lbyo - rbyo) * lline.1 / 2.0; println!("{}", burned + half); } else { burned += lline.0; let half = ((rbyo - lbyo) * rline.1) / 2.0; println!("{}", burned + half); } }
pub mod gate_desc; pub mod circuit_desc_gen;
use crypto; use util; use rustc_serialize::Decodable; use rustc_serialize::base64::{self, ToBase64}; use rustc_serialize::json::{self, Json}; use rust_multihash::Multihash; use std::io::Read; use std::path::PathBuf; pub const DEFAULT_REPO_ROOT: &'static str = "~/"; pub const DEFAULT_REPO_PATH: &'static str = ".rust-ipfs"; pub const DEFAULT_CONFIG_FILE: &'static str = "config"; pub const ENV_NAME_REPO_DIR: &'static str = "IPFS_PATH"; pub const DEFAULT_KEYPAIR_NUM_BITS: usize = 2048; #[derive(RustcEncodable, RustcDecodable)] pub struct Identity { pub peer_id: Multihash, pub private_key: String, } #[derive(RustcEncodable, RustcDecodable)] pub struct Config { pub identity: Identity, } impl Config { pub fn from_reader<R: Read>(reader: &mut R) -> Result<Config, String> { let json = try!(Json::from_reader(reader) .map_err(|e| format!("Error parsing Json: {}", e))); let mut decoder = json::Decoder::new(json); Decodable::decode(&mut decoder) .map_err(|e| format!("Error decoding Config from reader: {}", e)) } pub fn to_json_string(&self) -> json::EncodeResult<String> { json::encode(self) } } pub fn repo_path_to_config_file(mut repo_path: PathBuf) -> PathBuf { repo_path.push(DEFAULT_CONFIG_FILE); repo_path } pub fn init(num_key_pair_bits: usize) -> Config { let pkey = crypto::gen_key_pair(num_key_pair_bits); let pub_bytes = pkey.save_pub(); let priv_b64_string = pkey.save_priv().to_base64(base64::STANDARD); Config { identity: Identity { peer_id: util::hash(&pub_bytes[..]), private_key: priv_b64_string, }, } }
extern "C" { pub fn fcntl(fd: i32, cmd: i32, ...) -> i32; } pub const F_GETFD: i32 = 1; pub const F_SETFD: i32 = 2; pub const FD_CLOEXEC: i32 = 2; pub const EBADF: i32 = 9;
//! Contains an ffi-safe equivalent of `std::string::String`. use std::{ borrow::{Borrow, Cow}, fmt::{self, Display, Formatter}, iter::{FromIterator, FusedIterator}, marker::PhantomData, ops::{Deref, Index, Range}, ptr, str::{from_utf8, Chars, FromStr, Utf8Error}, string::FromUtf16Error, }; use serde::{Deserialize, Deserializer, Serialize, Serializer}; #[allow(unused_imports)] use core_extensions::{SelfOps, SliceExt, StringExt}; use crate::std_types::{RStr, RVec}; mod iters; #[cfg(test)] // #[cfg(all(test, not(feature = "only_new_tests")))] mod tests; pub use self::iters::{Drain, IntoIter}; /// Ffi-safe equivalent of `std::string::String`. /// /// # Example /// /// This defines a function returning the last word of an `RString`. /// /// ``` /// use abi_stable::{sabi_extern_fn, std_types::RString}; /// /// #[sabi_extern_fn] /// fn first_word(phrase: RString) -> RString { /// match phrase.split_whitespace().next_back() { /// Some(x) => x.into(), /// None => RString::new(), /// } /// } /// /// /// ``` /// #[derive(Clone)] #[repr(C)] #[derive(StableAbi)] pub struct RString { inner: RVec<u8>, } impl RString { /// Creates a new, empty RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let str = RString::new(); /// /// assert_eq!(&str[..], ""); /// /// ``` pub const fn new() -> Self { Self::NEW } const NEW: Self = Self { inner: RVec::new() }; /// Creates a new, /// empty RString with the capacity for `cap` bytes without reallocating. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let str = RString::with_capacity(10); /// /// assert_eq!(&str[..], ""); /// assert_eq!(str.capacity(), 10); /// /// ``` pub fn with_capacity(cap: usize) -> Self { String::with_capacity(cap).into() } /// For slicing into `RStr`s. /// /// This is an inherent method instead of an implementation of the /// `std::ops::Index` trait because it does not return a reference. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RStr, RString}; /// /// let str = RString::from("What is that."); /// /// assert_eq!(str.slice(..), RStr::from("What is that.")); /// assert_eq!(str.slice(..4), RStr::from("What")); /// assert_eq!(str.slice(4..), RStr::from(" is that.")); /// assert_eq!(str.slice(4..7), RStr::from(" is")); /// /// ``` #[inline] #[allow(clippy::needless_lifetimes)] pub fn slice<'a, I>(&'a self, i: I) -> RStr<'a> where str: Index<I, Output = str>, { (&self[i]).into() } conditionally_const! { feature = "rust_1_64" /// Creates a `&str` with access to all the characters of the `RString`. /// ; /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let str = "What is that."; /// assert_eq!(RString::from(str).as_str(), str); /// /// ``` #[inline] pub fn as_str(&self) -> &str { unsafe { std::str::from_utf8_unchecked(self.inner.as_slice()) } } } /// Creates an `RStr<'_>` with access to all the characters of the `RString`. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RStr, RString}; /// /// let str = "What is that."; /// assert_eq!(RString::from(str).as_rstr(), RStr::from(str),); /// /// ``` #[inline] pub const fn as_rstr(&self) -> RStr<'_> { unsafe { RStr::from_raw_parts(self.as_ptr(), self.len()) } } /// Returns the current length (in bytes) of the RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// assert_eq!(RString::from("").len(), 0); /// assert_eq!(RString::from("a").len(), 1); /// assert_eq!(RString::from("Regular").len(), 7); /// /// ``` #[inline] pub const fn len(&self) -> usize { self.inner.len() } /// Returns whether the RString is empty. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// assert_eq!(RString::from("").is_empty(), true); /// assert_eq!(RString::from("a").is_empty(), false); /// assert_eq!(RString::from("Regular").is_empty(), false); /// /// ``` #[inline] pub const fn is_empty(&self) -> bool { self.inner.is_empty() } /// Gets a raw pointer to the start of this RString's buffer. pub const fn as_ptr(&self) -> *const u8 { self.inner.as_ptr() } /// Returns the current capacity (in bytes) of the RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::with_capacity(13); /// /// assert_eq!(str.capacity(), 13); /// /// str.push_str("What is that."); /// assert_eq!(str.capacity(), 13); /// /// str.push(' '); /// assert_ne!(str.capacity(), 13); /// /// ``` #[inline] pub const fn capacity(&self) -> usize { self.inner.capacity() } /// An unchecked conversion from a `RVec<u8>` to an `RString`. /// /// # Safety /// /// This has the same safety requirements as /// [`String::from_utf8_unchecked` /// ](https://doc.rust-lang.org/std/string/struct.String.html#method.from_utf8_unchecked). /// /// # Examples /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let bytes = RVec::from("hello".as_bytes()); /// /// unsafe { /// assert_eq!(RString::from_utf8_unchecked(bytes).as_str(), "hello"); /// } /// /// ``` #[inline] pub const unsafe fn from_utf8_unchecked(vec: RVec<u8>) -> Self { RString { inner: vec } } /// Converts the `vec` vector of bytes to an `RString`. /// /// # Errors /// /// This returns a `Err(FromUtf8Error{..})` if `vec` is not valid utf-8. /// /// # Examples /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let bytes_ok = RVec::from("hello".as_bytes()); /// let bytes_err = RVec::from(vec![255]); /// /// assert_eq!( /// RString::from_utf8(bytes_ok).unwrap(), /// RString::from("hello") /// ); /// assert!(RString::from_utf8(bytes_err).is_err()); /// /// ``` pub fn from_utf8<V>(vec: V) -> Result<Self, FromUtf8Error> where V: Into<RVec<u8>>, { let vec = vec.into(); match from_utf8(&vec) { Ok(..) => Ok(RString { inner: vec }), Err(e) => Err(FromUtf8Error { bytes: vec, error: e, }), } } /// Decodes a utf-16 encoded `&[u16]` to an `RString`. /// /// # Errors /// /// This returns a `Err(::std::string::FromUtf16Error{..})` /// if `vec` is not valid utf-8. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let str = "What the 😈."; /// let str_utf16 = str.encode_utf16().collect::<Vec<u16>>(); /// /// assert_eq!(RString::from_utf16(&str_utf16).unwrap(), RString::from(str),); /// ``` pub fn from_utf16(s: &[u16]) -> Result<Self, FromUtf16Error> { String::from_utf16(s).map(From::from) } /// Cheap conversion of this `RString` to a `RVec<u8>` /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let bytes = RVec::from("hello".as_bytes()); /// let str = RString::from("hello"); /// /// assert_eq!(str.into_bytes(), bytes); /// /// ``` #[allow(clippy::missing_const_for_fn)] pub fn into_bytes(self) -> RVec<u8> { self.inner } /// Converts this `RString` to a `String`. /// /// # Allocation /// /// If this is invoked outside of the dynamic library/binary that created it, /// it will allocate a new `String` and move the data into it. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let std_str = String::from("hello"); /// let str = RString::from("hello"); /// /// assert_eq!(str.into_string(), std_str); /// /// ``` pub fn into_string(self) -> String { unsafe { String::from_utf8_unchecked(self.inner.into_vec()) } } /// Copies the `RString` into a `String`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// assert_eq!(RString::from("world").to_string(), String::from("world")); /// /// ``` #[allow(clippy::inherent_to_string_shadow_display)] pub fn to_string(&self) -> String { self.as_str().to_string() } /// Reserves `àdditional` additional capacity for any extra string data. /// This may reserve more than necessary for the additional capacity. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::new(); /// /// str.reserve(10); /// assert!(str.capacity() >= 10); /// /// ``` pub fn reserve(&mut self, additional: usize) { self.inner.reserve(additional); } /// Shrinks the capacity of the RString to match its length. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::with_capacity(100); /// str.push_str("nope"); /// str.shrink_to_fit(); /// assert_eq!(str.capacity(), 4); /// /// ``` pub fn shrink_to_fit(&mut self) { self.inner.shrink_to_fit() } /// Reserves `àdditional` additional capacity for any extra string data. /// /// Prefer using `reserve` for most situations. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::new(); /// /// str.reserve_exact(10); /// assert_eq!(str.capacity(), 10); /// /// ``` pub fn reserve_exact(&mut self, additional: usize) { self.inner.reserve_exact(additional); } /// Appends `ch` at the end of this RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::new(); /// /// str.push('O'); /// str.push('O'); /// str.push('P'); /// /// assert_eq!(str.as_str(), "OOP"); /// /// ``` pub fn push(&mut self, ch: char) { match ch.len_utf8() { 1 => self.inner.push(ch as u8), _ => self.push_str(ch.encode_utf8(&mut [0; 4])), } } /// Appends `str` at the end of this RString. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let mut str = RString::new(); /// /// str.push_str("green "); /// str.push_str("frog"); /// /// assert_eq!(str.as_str(), "green frog"); /// /// ``` pub fn push_str(&mut self, str: &str) { self.inner.extend_from_copy_slice(str.as_bytes()); } /// Removes the last character, /// returns `Some(_)` if this `RString` is not empty, /// otherwise returns `None`. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let mut str = RString::from("yep"); /// /// assert_eq!(str.pop(), Some('p')); /// assert_eq!(str.pop(), Some('e')); /// assert_eq!(str.pop(), Some('y')); /// assert_eq!(str.pop(), None); /// /// ``` pub fn pop(&mut self) -> Option<char> { // literal copy-paste of std, so if this is wrong std is wrong. let ch = self.chars().rev().next()?; let newlen = self.len() - ch.len_utf8(); unsafe { self.inner.set_len(newlen); } Some(ch) } /// Removes and returns the character starting at the `idx` byte position, /// /// # Panics /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let mut str = RString::from("Galileo"); /// /// assert_eq!(str.remove(3), 'i'); /// assert_eq!(str.as_str(), "Galleo"); /// /// assert_eq!(str.remove(4), 'e'); /// assert_eq!(str.as_str(), "Gallo"); /// /// ``` pub fn remove(&mut self, idx: usize) -> char { // literal copy-paste of std, so if this is wrong std is wrong. let ch = match self[idx..].chars().next() { Some(ch) => ch, None => panic!("cannot remove a char beyond the end of a string"), }; let next = idx + ch.len_utf8(); let len = self.len(); unsafe { let ptr = self.inner.as_mut_ptr(); ptr::copy(ptr.add(next), ptr.add(idx), len - next); self.inner.set_len(len - (next - idx)); } ch } /// Insert the `ch` character at the `ìdx` byte position. /// /// # Panics /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let mut str = RString::from("Cap"); /// /// str.insert(1, 'r'); /// assert_eq!(str.as_str(), "Crap"); /// /// str.insert(4, 'p'); /// assert_eq!(str.as_str(), "Crapp"); /// /// str.insert(5, 'y'); /// assert_eq!(str.as_str(), "Crappy"); /// /// ``` pub fn insert(&mut self, idx: usize, ch: char) { let mut bits = [0; 4]; let str_ = ch.encode_utf8(&mut bits); self.insert_str(idx, str_); } /// Insert the `string` at the `ìdx` byte position. /// /// # Panics /// /// Panics if the index is out of bounds or if it is not on a char boundary. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let mut str = RString::from("rust"); /// /// str.insert_str(0, "T"); /// assert_eq!(str.as_str(), "Trust"); /// /// str.insert_str(5, " the source"); /// assert_eq!(str.as_str(), "Trust the source"); /// /// str.insert_str(5, " the types in"); /// assert_eq!(str.as_str(), "Trust the types in the source"); /// /// ``` pub fn insert_str(&mut self, idx: usize, string: &str) { // literal copy-paste of std, so if this is wrong std is wrong. assert!(self.is_char_boundary(idx)); unsafe { self.insert_bytes(idx, string.as_bytes()); } } unsafe fn insert_bytes(&mut self, idx: usize, bytes: &[u8]) { let len = self.len(); let amt = bytes.len(); self.inner.reserve(amt); let ptr = self.inner.as_mut_ptr(); unsafe { ptr::copy(ptr.add(idx), ptr.add(idx + amt), len - idx); ptr::copy(bytes.as_ptr(), self.inner.as_mut_ptr().add(idx), amt); self.inner.set_len(len + amt); } } /// Retains only the characters that satisfy the `pred` predicate /// /// This means that a character will be removed if `pred(that_character)` /// returns false. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// { /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| !c.is_numeric()); /// assert_eq!(str.as_str(), "There were people."); /// } /// { /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| !c.is_whitespace()); /// assert_eq!(str.as_str(), "Therewere10people."); /// } /// { /// let mut str = RString::from("There were 10 people."); /// str.retain(|c| c.is_numeric()); /// assert_eq!(str.as_str(), "10"); /// } /// /// ``` #[inline] pub fn retain<F>(&mut self, mut pred: F) where F: FnMut(char) -> bool, { let len = self.len(); let mut del_bytes = 0; let mut idx = 0; unsafe { self.inner.set_len(0); } let start = self.inner.as_mut_ptr(); while idx < len { let curr = unsafe { start.add(idx) }; let ch = unsafe { RStr::from_raw_parts(curr, len - idx) .chars() .next() .unwrap() }; let ch_len = ch.len_utf8(); if !pred(ch) { del_bytes += ch_len; } else if del_bytes > 0 { unsafe { ptr::copy(curr, curr.sub(del_bytes), ch_len); } } // Point idx to the next char idx += ch_len; } unsafe { self.inner.set_len(len - del_bytes); } } /// Turns this into an empty RString, keeping the same allocated buffer. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let mut str = RString::from("Nurse"); /// /// assert_eq!(str.as_str(), "Nurse"); /// /// str.clear(); /// /// assert_eq!(str.as_str(), ""); /// /// ``` pub fn clear(&mut self) { self.inner.clear(); } } /// Returns an empty RString impl Default for RString { fn default() -> Self { String::new().into() } } //////////////////// deref_coerced_impl_cmp_traits! { RString; coerce_to = str, [ String, str, &str, RStr<'_>, std::borrow::Cow<'_, str>, crate::std_types::RCowStr<'_>, ] } //////////////////// impl_into_rust_repr! { impl Into<String> for RString { fn(this){ this.into_string() } } } impl<'a> From<RString> for Cow<'a, str> { fn from(this: RString) -> Cow<'a, str> { this.into_string().piped(Cow::Owned) } } impl From<&str> for RString { fn from(this: &str) -> Self { this.to_owned().into() } } impl_from_rust_repr! { impl From<String> for RString { fn(this){ RString { inner: this.into_bytes().into(), } } } } impl<'a> From<Cow<'a, str>> for RString { fn from(this: Cow<'a, str>) -> Self { this.into_owned().into() } } //////////////////// impl FromStr for RString { type Err = <String as FromStr>::Err; fn from_str(s: &str) -> Result<Self, Self::Err> { s.parse::<String>().map(RString::from) } } //////////////////// impl Borrow<str> for RString { fn borrow(&self) -> &str { self } } impl AsRef<str> for RString { fn as_ref(&self) -> &str { self } } impl AsRef<[u8]> for RString { fn as_ref(&self) -> &[u8] { self.as_bytes() } } //////////////////// impl Deref for RString { type Target = str; #[inline] fn deref(&self) -> &Self::Target { self.as_str() } } impl Display for RString { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(self.as_str(), f) } } impl fmt::Write for RString { #[inline] fn write_str(&mut self, s: &str) -> fmt::Result { self.push_str(s); Ok(()) } #[inline] fn write_char(&mut self, c: char) -> fmt::Result { self.push(c); Ok(()) } } shared_impls! { mod = string_impls new_type = RString[][], original_type = str, } impl<'de> Deserialize<'de> for RString { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { String::deserialize(deserializer).map(From::from) } } impl Serialize for RString { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { self.as_str().serialize(serializer) } } ////////////////////////////////////////////////////// impl RString { /// Creates an iterator that yields the chars in the `range`, /// removing the characters in that range in the process. /// /// # Panic /// /// Panics if the start or end of the range are not on a on a char boundary, /// or if either are out of bounds. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let orig = "Not a single way"; /// /// { /// let mut str = RString::from(orig); /// assert_eq!(str.drain(..).collect::<String>(), orig,); /// assert_eq!(str.as_str(), ""); /// } /// { /// let mut str = RString::from(orig); /// assert_eq!(str.drain(..4).collect::<String>(), "Not ",); /// assert_eq!(str.as_str(), "a single way"); /// } /// { /// let mut str = RString::from(orig); /// assert_eq!(str.drain(4..).collect::<String>(), "a single way",); /// assert_eq!(str.as_str(), "Not "); /// } /// { /// let mut str = RString::from(orig); /// assert_eq!(str.drain(4..13).collect::<String>(), "a single ",); /// assert_eq!(str.as_str(), "Not way"); /// } /// /// ``` pub fn drain<I>(&mut self, range: I) -> Drain<'_> where str: Index<I, Output = str>, { let string = self as *mut _; let slic_ = &(*self)[range]; let start = self.offset_of_slice(slic_); let end = start + slic_.len(); Drain { string, removed: start..end, iter: slic_.chars(), variance: PhantomData, } } } impl IntoIterator for RString { type Item = char; type IntoIter = IntoIter; fn into_iter(self) -> IntoIter { unsafe { // Make sure that the buffer is not deallocated as long as the iterator is accessible. let text: &'static str = &*(&*self as *const str); IntoIter { iter: text.chars(), _buf: self, } } } } impl FromIterator<char> for RString { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = char>, { iter.piped(String::from_iter).piped(Self::from) } } impl<'a> FromIterator<&'a char> for RString { fn from_iter<I>(iter: I) -> Self where I: IntoIterator<Item = &'a char>, { iter.piped(String::from_iter).piped(Self::from) } } ////////////////////////////////////////////////////// /// Error that happens when attempting to convert an `RVec<u8>` into an `RString`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let err = RString::from_utf8(vec![0, 0, 0, 255]).unwrap_err(); /// /// assert_eq!(err.as_bytes(), &[0, 0, 0, 255]) /// /// ``` #[derive(Debug)] pub struct FromUtf8Error { bytes: RVec<u8>, error: Utf8Error, } #[allow(clippy::missing_const_for_fn)] impl FromUtf8Error { /// Unwraps this error into the bytes that failed to be converted into an `RString`. /// /// # Example /// /// ``` /// use abi_stable::std_types::{RString, RVec}; /// /// let bytes: RVec<u8> = vec![72, 111, 95, 95, 95, 95, 95, 99, 107, 255].into(); /// /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// /// assert_eq!(err.into_bytes(), bytes); /// /// ``` pub fn into_bytes(self) -> RVec<u8> { self.bytes } /// Gets access to the bytes that failed to be converted into an `RString`. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let bytes = vec![99, 114, 121, 115, 116, 97, 108, 255]; /// /// let err = RString::from_utf8(bytes.clone()).unwrap_err(); /// /// assert_eq!(err.as_bytes(), &bytes[..]); /// /// ``` pub fn as_bytes(&self) -> &[u8] { &self.bytes } /// Gets a Utf8Error with information about the conversion error. /// /// # Example /// /// ``` /// use abi_stable::std_types::RString; /// /// let err = RString::from_utf8(vec![0, 0, 255]).unwrap_err(); /// /// assert_eq!(err.error().valid_up_to(), 2); /// /// ``` pub fn error(&self) -> Utf8Error { self.error } } impl fmt::Display for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.error, f) } } impl std::error::Error for FromUtf8Error {}
/* * Copyright 2020 Fluence Labs Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use crate::ed25519::{Keypair as Libp2pKeyPair, PublicKey, SecretKey}; use libp2p_core::identity::error::DecodingError; pub type Signature = Vec<u8>; /// An Ed25519 keypair. #[derive(Clone, Debug)] pub struct KeyPair { pub key_pair: Libp2pKeyPair, } impl KeyPair { /// Generate a new Ed25519 keypair. #[allow(dead_code)] pub fn generate() -> Self { let kp = Libp2pKeyPair::generate(); kp.into() } pub fn from_bytes(sk_bytes: impl AsMut<[u8]>) -> Result<Self, DecodingError> { let sk = SecretKey::from_bytes(sk_bytes)?; Ok(Libp2pKeyPair::from(sk).into()) } /// Encode the keypair into a byte array by concatenating the bytes /// of the secret scalar and the compressed public point/ #[allow(dead_code)] pub fn encode(&self) -> [u8; 64] { self.key_pair.encode() } /// Decode a keypair from the format produced by `encode`. #[allow(dead_code)] pub fn decode(kp: &mut [u8]) -> Result<KeyPair, DecodingError> { let kp = Libp2pKeyPair::decode(kp)?; Ok(Self { key_pair: kp }) } /// Get the public key of this keypair. #[allow(dead_code)] pub fn public_key(&self) -> PublicKey { self.key_pair.public() } /// Sign a message using the private key of this keypair. pub fn sign(&self, msg: &[u8]) -> Vec<u8> { self.key_pair.sign(msg) } /// Verify the Ed25519 signature on a message using the public key. pub fn verify(pk: &PublicKey, msg: &[u8], signature: &[u8]) -> Result<(), String> { if pk.verify(msg, signature) { return Ok(()); } Err("Signature is not valid.".to_string()) } } impl From<Libp2pKeyPair> for KeyPair { fn from(kp: Libp2pKeyPair) -> Self { Self { key_pair: kp } } }
// 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. // aux-build:issue24687_lib.rs // compile-flags:-g extern crate issue24687_lib as d; fn main() { // Create a d, which has a destructor whose body will be codegen'ed // into the generated code here, and thus the local debuginfo will // need references into the original source locations from // `importer` above. let _d = d::D("Hi"); }
extern crate ansi_term; extern crate difference; pub mod macros; pub mod table; mod formater; mod test_case;
//https://leetcode.com/problems/di-string-match/submissions/ impl Solution { pub fn di_string_match(s: String) -> Vec<i32> { let mut perm = Vec::with_capacity(s.len()); let mut left: i32 = 0; let mut right = s.len() as i32; let mut last_char = s.chars().nth(0).unwrap(); let mut seq_len = 1; for c in s.chars() { if last_char == c { seq_len += 1; } else { match last_char { 'D' => { insert_sequence(&mut perm, seq_len, last_char, left); left += seq_len; }, 'I' => { insert_sequence(&mut perm, seq_len, last_char, right); right -= seq_len; }, _ => () } seq_len = 1; } last_char = c; } match last_char { 'D' => insert_sequence(&mut perm, seq_len, last_char, left), 'I' => insert_sequence(&mut perm, seq_len, last_char, right), _ => () } perm } } pub fn insert_sequence(perm: &mut Vec<i32>,cnt: i32, c: char, idx: i32) { match c { 'I' => { for i in (idx-cnt+1)..(idx+1) { perm.push(i); } }, 'D' => { for i in (idx..(idx+cnt)).rev() { perm.push(i); } }, _ => () } }
use std::time::SystemTime; fn main() { let server = tiny_http::Server::http("0.0.0.0:6099").unwrap(); loop { let request = match server.recv() { Ok(rq) => rq, Err(e) => { println!("error: {}", e); break } }; let response = tiny_http::Response::empty(200); println!("request! {:?}", SystemTime::now()); let _ = request.respond(response); } }
use crate::any::connection::AnyConnectionKind; use crate::any::{ Any, AnyColumn, AnyConnection, AnyQueryResult, AnyRow, AnyStatement, AnyTypeInfo, }; use crate::database::Database; use crate::describe::Describe; use crate::error::Error; use crate::executor::{Execute, Executor}; use either::Either; use futures_core::future::BoxFuture; use futures_core::stream::BoxStream; use futures_util::{StreamExt, TryStreamExt}; impl<'c> Executor<'c> for &'c mut AnyConnection { type Database = Any; fn fetch_many<'e, 'q: 'e, E: 'q>( self, mut query: E, ) -> BoxStream<'e, Result<Either<AnyQueryResult, AnyRow>, Error>> where 'c: 'e, E: Execute<'q, Self::Database>, { let arguments = query.take_arguments(); let query = query.sql(); match &mut self.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => conn .fetch_many((query, arguments.map(Into::into))) .map_ok(|v| v.map_right(Into::into).map_left(Into::into)) .boxed(), #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => conn .fetch_many((query, arguments.map(Into::into))) .map_ok(|v| v.map_right(Into::into).map_left(Into::into)) .boxed(), #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => conn .fetch_many((query, arguments.map(Into::into))) .map_ok(|v| v.map_right(Into::into).map_left(Into::into)) .boxed(), #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => conn .fetch_many((query, arguments.map(Into::into))) .map_ok(|v| v.map_right(Into::into).map_left(Into::into)) .boxed(), } } fn fetch_optional<'e, 'q: 'e, E: 'q>( self, mut query: E, ) -> BoxFuture<'e, Result<Option<AnyRow>, Error>> where 'c: 'e, E: Execute<'q, Self::Database>, { let arguments = query.take_arguments(); let query = query.sql(); Box::pin(async move { Ok(match &mut self.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => conn .fetch_optional((query, arguments.map(Into::into))) .await? .map(Into::into), #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => conn .fetch_optional((query, arguments.map(Into::into))) .await? .map(Into::into), #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => conn .fetch_optional((query, arguments.map(Into::into))) .await? .map(Into::into), #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => conn .fetch_optional((query, arguments.map(Into::into))) .await? .map(Into::into), }) }) } fn prepare_with<'e, 'q: 'e>( self, sql: &'q str, _parameters: &[AnyTypeInfo], ) -> BoxFuture<'e, Result<AnyStatement<'q>, Error>> where 'c: 'e, { Box::pin(async move { Ok(match &mut self.0 { // To match other databases here, we explicitly ignore the parameter types #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => conn.prepare(sql).await.map(Into::into)?, #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => conn.prepare(sql).await.map(Into::into)?, #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => conn.prepare(sql).await.map(Into::into)?, #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => conn.prepare(sql).await.map(Into::into)?, }) }) } fn describe<'e, 'q: 'e>( self, sql: &'q str, ) -> BoxFuture<'e, Result<Describe<Self::Database>, Error>> where 'c: 'e, { Box::pin(async move { Ok(match &mut self.0 { #[cfg(feature = "postgres")] AnyConnectionKind::Postgres(conn) => conn.describe(sql).await.map(map_describe)?, #[cfg(feature = "mysql")] AnyConnectionKind::MySql(conn) => conn.describe(sql).await.map(map_describe)?, #[cfg(feature = "sqlite")] AnyConnectionKind::Sqlite(conn) => conn.describe(sql).await.map(map_describe)?, #[cfg(feature = "mssql")] AnyConnectionKind::Mssql(conn) => conn.describe(sql).await.map(map_describe)?, }) }) } } fn map_describe<DB: Database>(info: Describe<DB>) -> Describe<Any> where AnyTypeInfo: From<DB::TypeInfo>, AnyColumn: From<DB::Column>, { let parameters = match info.parameters { None => None, Some(Either::Right(num)) => Some(Either::Right(num)), Some(Either::Left(params)) => { Some(Either::Left(params.into_iter().map(Into::into).collect())) } }; Describe { parameters, nullable: info.nullable, columns: info.columns.into_iter().map(Into::into).collect(), } }
//! Protobuf types for errors from the google standards and //! conversions to `tonic::Status` //! //! # Status Responses //! //! gRPC defines a standard set of [Status Codes] to use for various purposes. In general this //! combined with a textual error message are sufficient. The status code allows the client to //! handle classes of errors programmatically, whilst the error message provides additional context //! to the end user. This is the minimal error model supported by all implementations of gRPC. //! //! gRPC also has a concept of [Error Details]. These are just a list of `google.protobuf.Any` //! that can be bundled with the status message. A standard set of [Error Payloads] are used //! by Google APIs, and this is a convention IOx follows. //! //! As the encoding of these payloads is somewhat arcane, Rust types such as [`FieldViolation`], //! [`AlreadyExists`], [`NotFound`], [`PreconditionViolation`] etc... are provided that can be //! converted to a `tonic::Status` with `Into::into`. //! //! Unfortunately client support for details payloads is patchy. Therefore, whilst IOx does //! provide these payloads, they should be viewed as an optional extension and not mandatory //! functionality for a workable client implementation //! //! # Message Conversion //! //! Most of the logic within IOx is written in terms of types defined in the `data_types` crate, //! conversions are then defined to/from `generated_types` types generated by prost. //! //! In addition to avoiding a dependency on hyper, tonic, etc... within these crates, this serves //! to abstract away concerns such as API evolution, default values, etc... //! //! Unfortunately, writing this translation code is somewhat cumbersome and so this module //! contains a collection of extension traits to improve the ergonomics of writing the potentially //! fallible conversion from the protobuf representation to the corresponding `data_types` type //! //! Each type should implement the following: //! //! * `From<data_types::Type>` for `proto::Type` //! * `TryFrom<proto::Type, Error=FieldViolation>` for `data_types::Type` //! //! Where [`FieldViolation`] allows context propagation about the problematic field within a //! nested structure. A common error type is chosen because: //! //! * It integrates well with the expectations of gRPC and by extension tonic //! * It reduces boilerplate code //! //! [Status Codes]: https://grpc.github.io/grpc/core/md_doc_statuscodes.html //! [Error Details]: https://cloud.google.com/apis/design/errors#error_details //! [Error Payloads]: https://cloud.google.com/apis/design/errors#error_payloads //! pub mod protobuf { pub use pbjson_types::*; } pub mod rpc { include!(concat!(env!("OUT_DIR"), "/google.rpc.rs")); include!(concat!(env!("OUT_DIR"), "/google.rpc.serde.rs")); } pub mod longrunning { include!(concat!(env!("OUT_DIR"), "/google.longrunning.rs")); include!(concat!(env!("OUT_DIR"), "/google.longrunning.serde.rs")); impl Operation { /// Return the IOx operation `id`. This `id` can /// be passed to the various APIs in the /// operations client such as `influxdb_iox_client::operations::Client::wait_operation`; pub fn id(&self) -> usize { self.name .parse() .expect("Internal error: id returned from server was not an integer") } } } use self::protobuf::Any; use observability_deps::tracing::error; use prost::{bytes::BytesMut, Message}; use std::convert::TryInto; // A newtype struct to provide conversion into tonic::Status #[derive(Debug)] struct EncodeError(prost::EncodeError); impl From<EncodeError> for tonic::Status { fn from(error: EncodeError) -> Self { error!(error=%error.0, "failed to serialize error response details"); tonic::Status::unknown(format!("failed to serialize server error: {}", error.0)) } } impl From<prost::EncodeError> for EncodeError { fn from(e: prost::EncodeError) -> Self { Self(e) } } pub fn encode_status(code: tonic::Code, message: String, details: Any) -> tonic::Status { let mut buffer = BytesMut::new(); let status = rpc::Status { code: code as i32, message: message.clone(), details: vec![details], }; match status.encode(&mut buffer) { Ok(_) => tonic::Status::with_details(code, message, buffer.freeze()), Err(e) => EncodeError(e).into(), } } /// Returns an iterator over the [`protobuf::Any`] payloads in the provided [`tonic::Status`] fn get_details(status: &tonic::Status) -> impl Iterator<Item = protobuf::Any> { rpc::Status::decode(status.details()) .ok() .into_iter() .flat_map(|status| status.details) } /// Error returned if a request field has an invalid value. Includes /// machinery to add parent field names for context -- thus it will /// report `rules.write_timeout` than simply `write_timeout`. #[derive(Debug, Default, Clone, PartialEq)] pub struct FieldViolation { pub field: String, pub description: String, } impl FieldViolation { pub fn required(field: impl Into<String>) -> Self { Self { field: field.into(), description: "Field is required".to_string(), } } /// Re-scopes this error as the child of another field pub fn scope(self, field: impl Into<String>) -> Self { let field = if self.field.is_empty() { field.into() } else { [field.into(), self.field].join(".") }; Self { field, description: self.description, } } } impl std::error::Error for FieldViolation {} impl std::fmt::Display for FieldViolation { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( f, "Violation for field \"{}\": {}", self.field, self.description ) } } fn encode_bad_request(violation: Vec<FieldViolation>) -> Result<Any, EncodeError> { let mut buffer = BytesMut::new(); rpc::BadRequest { field_violations: violation .into_iter() .map(|f| rpc::bad_request::FieldViolation { field: f.field, description: f.description, }) .collect(), } .encode(&mut buffer)?; Ok(Any { type_url: "type.googleapis.com/google.rpc.BadRequest".to_string(), value: buffer.freeze(), }) } impl From<FieldViolation> for tonic::Status { fn from(f: FieldViolation) -> Self { let message = f.to_string(); match encode_bad_request(vec![f]) { Ok(details) => encode_status(tonic::Code::InvalidArgument, message, details), Err(e) => e.into(), } } } impl From<rpc::bad_request::FieldViolation> for FieldViolation { fn from(v: rpc::bad_request::FieldViolation) -> Self { Self { field: v.field, description: v.description, } } } /// Returns an iterator over the [`FieldViolation`] in the provided [`tonic::Status`] pub fn decode_field_violation(status: &tonic::Status) -> impl Iterator<Item = FieldViolation> { get_details(status) .filter(|details| details.type_url == "type.googleapis.com/google.rpc.BadRequest") .flat_map(|details| rpc::BadRequest::decode(details.value).ok()) .flat_map(|bad_request| bad_request.field_violations) .map(Into::into) } /// An internal error occurred, no context is provided to the client /// /// Should be reserved for when a fundamental invariant of the system has been broken #[derive(Debug, Default, Clone)] pub struct InternalError {} impl From<InternalError> for tonic::Status { fn from(_: InternalError) -> Self { tonic::Status::new(tonic::Code::Internal, "Internal Error") } } /// A resource type within [`AlreadyExists`] or [`NotFound`] #[derive(Debug, Clone, PartialEq)] pub enum ResourceType { Database, Table, Partition, Chunk, DatabaseUuid, Job, Router, Unknown(String), } impl ResourceType { pub fn as_str(&self) -> &str { match self { Self::Database => "database", Self::DatabaseUuid => "database_uuid", Self::Table => "table", Self::Partition => "partition", Self::Chunk => "chunk", Self::Job => "job", Self::Router => "router", Self::Unknown(unknown) => unknown, } } } impl From<String> for ResourceType { fn from(s: String) -> Self { match s.as_str() { "database" => Self::Database, "database_uuid" => Self::DatabaseUuid, "table" => Self::Table, "partition" => Self::Partition, "chunk" => Self::Chunk, "job" => Self::Job, "router" => Self::Router, _ => Self::Unknown(s), } } } impl std::fmt::Display for ResourceType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.as_str().fmt(f) } } /// Returns an iterator over the [`rpc::ResourceInfo`] payloads in the provided [`tonic::Status`] fn decode_resource_info(status: &tonic::Status) -> impl Iterator<Item = rpc::ResourceInfo> { get_details(status) .filter(|details| details.type_url == "type.googleapis.com/google.rpc.ResourceInfo") .flat_map(|details| rpc::ResourceInfo::decode(details.value).ok()) } /// IOx returns [`AlreadyExists`] when it is unable to create the requested entity /// as it already exists on the server #[derive(Debug, Clone, PartialEq)] pub struct AlreadyExists { pub resource_type: ResourceType, pub resource_name: String, pub owner: String, pub description: String, } impl AlreadyExists { pub fn new(resource_type: ResourceType, resource_name: String) -> Self { let description = format!("Resource {resource_type}/{resource_name} already exists"); Self { resource_type, resource_name, description, owner: Default::default(), } } } fn encode_resource_info( resource_type: String, resource_name: String, owner: String, description: String, ) -> Result<Any, EncodeError> { let mut buffer = BytesMut::new(); rpc::ResourceInfo { resource_type, resource_name, owner, description, } .encode(&mut buffer)?; Ok(Any { type_url: "type.googleapis.com/google.rpc.ResourceInfo".to_string(), value: buffer.freeze(), }) } impl From<AlreadyExists> for tonic::Status { fn from(exists: AlreadyExists) -> Self { match encode_resource_info( exists.resource_type.to_string(), exists.resource_name, exists.owner, exists.description.clone(), ) { Ok(details) => encode_status(tonic::Code::AlreadyExists, exists.description, details), Err(e) => e.into(), } } } impl From<rpc::ResourceInfo> for AlreadyExists { fn from(r: rpc::ResourceInfo) -> Self { Self { resource_type: r.resource_type.into(), resource_name: r.resource_name, owner: r.owner, description: r.description, } } } /// Returns an iterator over the [`AlreadyExists`] in the provided [`tonic::Status`] pub fn decode_already_exists(status: &tonic::Status) -> impl Iterator<Item = AlreadyExists> { decode_resource_info(status).map(Into::into) } /// IOx returns [`NotFound`] when it is unable to perform an operation on a resource /// because it doesn't exist on the server #[derive(Debug, Clone, PartialEq)] pub struct NotFound { pub resource_type: ResourceType, pub resource_name: String, pub owner: String, pub description: String, } impl NotFound { pub fn new(resource_type: ResourceType, resource_name: String) -> Self { let description = format!("Resource {resource_type}/{resource_name} not found"); Self { resource_type, resource_name, description, owner: Default::default(), } } } impl From<NotFound> for tonic::Status { fn from(not_found: NotFound) -> Self { match encode_resource_info( not_found.resource_type.to_string(), not_found.resource_name, not_found.owner, not_found.description.clone(), ) { Ok(details) => encode_status(tonic::Code::NotFound, not_found.description, details), Err(e) => e.into(), } } } impl From<rpc::ResourceInfo> for NotFound { fn from(r: rpc::ResourceInfo) -> Self { Self { resource_type: r.resource_type.into(), resource_name: r.resource_name, owner: r.owner, description: r.description, } } } /// Returns an iterator over the [`NotFound`] in the provided [`tonic::Status`] pub fn decode_not_found(status: &tonic::Status) -> impl Iterator<Item = NotFound> { decode_resource_info(status).map(Into::into) } /// A [`PreconditionViolation`] is returned by IOx when the system is in a state that /// prevents performing the requested operation #[derive(Debug, Clone, PartialEq)] pub enum PreconditionViolation { /// Database is not mutable DatabaseImmutable, /// Server not in required state for operation ServerInvalidState(String), /// Database not in required state for operation DatabaseInvalidState(String), /// Partition not in required state for operation PartitionInvalidState(String), /// Chunk not in required state for operation ChunkInvalidState(String), /// Configuration is immutable RouterConfigImmutable, /// Configuration is immutable DatabaseConfigImmutable, /// An unknown precondition violation Unknown { category: String, subject: String, description: String, }, } impl PreconditionViolation { fn description(&self) -> String { match self { Self::DatabaseImmutable => "database must be mutable".to_string(), Self::ServerInvalidState(description) => description.clone(), Self::DatabaseInvalidState(description) => description.clone(), Self::PartitionInvalidState(description) => description.clone(), Self::ChunkInvalidState(description) => description.clone(), Self::RouterConfigImmutable => "router configuration is not mutable".to_string(), Self::DatabaseConfigImmutable => "database configuration is not mutable".to_string(), Self::Unknown { description, .. } => description.clone(), } } } impl From<PreconditionViolation> for rpc::precondition_failure::Violation { fn from(v: PreconditionViolation) -> Self { match v { PreconditionViolation::ServerInvalidState(_) => Self { r#type: "state".to_string(), subject: "influxdata.com/iox".to_string(), description: v.description(), }, PreconditionViolation::DatabaseImmutable => Self { r#type: "mutable".to_string(), subject: "influxdata.com/iox/database".to_string(), description: v.description(), }, PreconditionViolation::DatabaseInvalidState(_) => Self { r#type: "state".to_string(), subject: "influxdata.com/iox/database".to_string(), description: v.description(), }, PreconditionViolation::PartitionInvalidState(_) => Self { r#type: "state".to_string(), subject: "influxdata.com/iox/partition".to_string(), description: v.description(), }, PreconditionViolation::ChunkInvalidState(_) => Self { r#type: "state".to_string(), subject: "influxdata.com/iox/chunk".to_string(), description: v.description(), }, PreconditionViolation::RouterConfigImmutable => Self { r#type: "config".to_string(), subject: "influxdata.com/iox/router".to_string(), description: v.description(), }, PreconditionViolation::DatabaseConfigImmutable => Self { r#type: "config".to_string(), subject: "influxdata.com/iox/database".to_string(), description: v.description(), }, PreconditionViolation::Unknown { category, subject, description, } => Self { r#type: category, subject, description, }, } } } impl From<rpc::precondition_failure::Violation> for PreconditionViolation { fn from(v: rpc::precondition_failure::Violation) -> Self { match (v.r#type.as_str(), v.subject.as_str()) { ("state", "influxdata.com/iox") => { PreconditionViolation::ServerInvalidState(v.description) } ("mutable", "influxdata.com/iox/database") => PreconditionViolation::DatabaseImmutable, ("state", "influxdata.com/iox/database") => { PreconditionViolation::DatabaseInvalidState(v.description) } ("state", "influxdata.com/iox/partition") => { PreconditionViolation::PartitionInvalidState(v.description) } ("state", "influxdata.com/iox/chunk") => { PreconditionViolation::ChunkInvalidState(v.description) } ("config", "influxdata.com/iox/router") => PreconditionViolation::RouterConfigImmutable, ("config", "influxdata.com/iox/database") => { PreconditionViolation::DatabaseConfigImmutable } _ => Self::Unknown { category: v.r#type, subject: v.subject, description: v.description, }, } } } /// Returns an iterator over the [`PreconditionViolation`] in the provided [`tonic::Status`] pub fn decode_precondition_violation( status: &tonic::Status, ) -> impl Iterator<Item = PreconditionViolation> { get_details(status) .filter(|details| details.type_url == "type.googleapis.com/google.rpc.PreconditionFailure") .flat_map(|details| rpc::PreconditionFailure::decode(details.value).ok()) .flat_map(|failure| failure.violations) .map(Into::into) } fn encode_precondition_failure(violations: Vec<PreconditionViolation>) -> Result<Any, EncodeError> { let mut buffer = BytesMut::new(); rpc::PreconditionFailure { violations: violations.into_iter().map(Into::into).collect(), } .encode(&mut buffer)?; Ok(Any { type_url: "type.googleapis.com/google.rpc.PreconditionFailure".to_string(), value: buffer.freeze(), }) } impl From<PreconditionViolation> for tonic::Status { fn from(violation: PreconditionViolation) -> Self { let message = violation.description(); match encode_precondition_failure(vec![violation]) { Ok(details) => encode_status(tonic::Code::FailedPrecondition, message, details), Err(e) => e.into(), } } } /// An extension trait that adds the ability to convert an error /// that can be converted to a String to a FieldViolation /// /// This is useful where a field has fallible `TryFrom` conversion logic, but which doesn't /// use [`FieldViolation`] as its error type. [`FieldViolationExt::scope`] will format the /// returned error and add the field name as context /// pub trait FieldViolationExt { type Output; fn scope(self, field: &'static str) -> Result<Self::Output, FieldViolation>; } impl<T, E> FieldViolationExt for Result<T, E> where E: ToString, { type Output = T; fn scope(self, field: &'static str) -> Result<T, FieldViolation> { self.map_err(|e| FieldViolation { field: field.to_string(), description: e.to_string(), }) } } #[derive(Debug, Default, Clone)] pub struct QuotaFailure { pub subject: String, pub description: String, } impl From<QuotaFailure> for tonic::Status { fn from(quota_failure: QuotaFailure) -> Self { tonic::Status::new( tonic::Code::ResourceExhausted, format!("{}: {}", quota_failure.subject, quota_failure.description), ) } } /// An extension trait that adds the method `field` to any type implementing /// `TryInto<U, Error = FieldViolation>` /// /// This is primarily used to define other extension traits but may be useful for: /// /// * Conversion code for a oneof enumeration /// * Converting from a scalar field to a custom Rust type /// /// In a lot of cases, the type will be `Option<proto::Type>` or `Vec<proto::Type>` /// in which case `FromOptionalField` or `FromRepeatedField` should be used instead /// pub trait FromField<T> { fn field(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromField<U> for T where T: TryInto<U, Error = FieldViolation>, { /// Try to convert type using TryInto calling [`FieldViolation::scope`] /// on any returned error fn field(self, field: impl Into<String>) -> Result<U, FieldViolation> { self.try_into().map_err(|e| e.scope(field)) } } /// An extension trait that adds the methods `from_optional` and `from_required` to any /// Option containing a type implementing `TryInto<U, Error = FieldViolation>` /// /// This is useful for converting message-typed fields such as `Option<prost::Type>` to /// `Option<data_types::Type>` and `data_types::Type` respectively pub trait FromOptionalField<T> { /// Converts an optional protobuf field to an option of a different type /// /// Returns None if the option is None, otherwise calls [`FromField::field`] /// on the contained data, returning any error encountered fn optional(self, field: impl Into<String>) -> Result<Option<T>, FieldViolation>; /// Converts an optional protobuf field to a different type, returning an error if None /// /// Returns `FieldViolation::required` if None, otherwise calls [`FromField::field`] /// on the contained data, returning any error encountered fn required(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromOptionalField<U> for Option<T> where T: TryInto<U, Error = FieldViolation>, { fn optional(self, field: impl Into<String>) -> Result<Option<U>, FieldViolation> { self.map(|t| t.field(field)).transpose() } fn required(self, field: impl Into<String>) -> Result<U, FieldViolation> { match self { None => Err(FieldViolation::required(field)), Some(t) => t.field(field), } } } /// An extension trait that adds the method `from_repeated` to any `Vec` of a type /// implementing `TryInto<U, Error = FieldViolation>` /// /// This is useful for converting message-typed repeated fields such as `Vec<prost::Type>` /// to `Vec<data_types::Type>` pub trait FromRepeatedField<T> { /// Converts to a `Vec<U>`, short-circuiting on the first error and /// returning a correctly scoped `FieldViolation` for where the error /// was encountered fn repeated(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T, U> FromRepeatedField<Vec<U>> for Vec<T> where T: TryInto<U, Error = FieldViolation>, { fn repeated(self, field: impl Into<String>) -> Result<Vec<U>, FieldViolation> { let res: Result<_, _> = self .into_iter() .enumerate() .map(|(i, t)| t.field(i.to_string())) .collect(); res.map_err(|e| e.scope(field)) } } /// An extension trait that adds the method `non_empty` to any `String` /// /// This is useful where code wishes to require a non-empty string is specified /// /// TODO: Replace with NonEmptyString type implementing TryFrom? pub trait NonEmptyString { /// Returns a Ok if the String is not empty fn non_empty(self, field: impl Into<String>) -> Result<String, FieldViolation>; } impl NonEmptyString for String { fn non_empty(self, field: impl Into<Self>) -> Result<String, FieldViolation> { if self.is_empty() { return Err(FieldViolation::required(field)); } Ok(self) } } /// An extension trait that adds the method `required` to any `Option<T>` /// /// This is useful for field types: /// /// * With infallible conversions (e.g. `field.required("field")?.into()`) /// * With conversion logic not implemented using `TryFrom` /// /// `FromOptionalField` should be preferred where applicable pub trait OptionalField<T> { fn unwrap_field(self, field: impl Into<String>) -> Result<T, FieldViolation>; } impl<T> OptionalField<T> for Option<T> { fn unwrap_field(self, field: impl Into<String>) -> Result<T, FieldViolation> { self.ok_or_else(|| FieldViolation::required(field)) } } #[cfg(test)] mod tests { use super::*; use bytes::Bytes; #[test] fn test_error_roundtrip() { let violation = FieldViolation::required("foobar"); let status = tonic::Status::from(violation.clone()); let collected: Vec<_> = decode_field_violation(&status).collect(); assert_eq!(collected, vec![violation]); let not_found = NotFound::new(ResourceType::Chunk, "chunky".to_string()); let status = tonic::Status::from(not_found.clone()); let collected: Vec<_> = decode_not_found(&status).collect(); assert_eq!(collected, vec![not_found]); let already_exists = AlreadyExists::new(ResourceType::Database, "my database".to_string()); let status = tonic::Status::from(already_exists.clone()); let collected: Vec<_> = decode_already_exists(&status).collect(); assert_eq!(collected, vec![already_exists]); let precondition = PreconditionViolation::PartitionInvalidState("mumbo".to_string()); let status = tonic::Status::from(precondition.clone()); let collected: Vec<_> = decode_precondition_violation(&status).collect(); assert_eq!(collected, vec![precondition]); } #[test] fn test_multiple() { // Should allow encoding multiple violations let violations = vec![ FieldViolation::required("fizbuz"), FieldViolation::required("bingo"), ]; let encoded = encode_bad_request(violations.clone()).unwrap(); let mut buffer = BytesMut::new(); let code = tonic::Code::InvalidArgument; let status = rpc::Status { code: code as i32, message: "message".to_string(), details: vec![ // Should ignore unrecognised details payloads protobuf::Any { type_url: "my_magic/type".to_string(), value: Bytes::from(&b"INVALID"[..]), }, encoded, ], }; status.encode(&mut buffer).unwrap(); let status = tonic::Status::with_details(code, status.message, buffer.freeze()); let collected: Vec<_> = decode_field_violation(&status).collect(); assert_eq!(collected, violations); } }
extern crate ggez; extern crate markedly; extern crate markedly_ggez; use std::env; use std::path; use ggez::{Context, GameResult, GameError}; use ggez::conf::{Conf, WindowMode, WindowSetup}; use ggez::event::{self, EventHandler, MouseButton, MouseState}; use ggez::graphics::{self, Point2, Vector2}; use markedly::class::{ComponentClasses}; use markedly::input::{Input}; use markedly::scripting::{ScriptRuntime, ScriptTable}; use markedly::template::{Template, Style}; use markedly::{Context as UiContext, Ui, Tree}; use markedly_ggez::{GgezRenderer, GgezCache, emtg}; fn main() { // Set up the ggez context let mut c = Conf::new(); c.window_mode = WindowMode { width: 1280, height: 720, .. Default::default() }; c.window_setup = WindowSetup { title: "Markedly Example".into(), .. Default::default() }; let ctx = &mut Context::load_from_conf("example", "markedly", c).unwrap(); // We add the CARGO_MANIFEST_DIR/resources do the filesystems paths so we we look in the cargo // project for files. if let Ok(manifest_dir) = env::var("CARGO_MANIFEST_DIR") { let mut path = path::PathBuf::from(manifest_dir); path.push("resources"); ctx.filesystem.mount(&path, true); } // Initialize and run the game let result = MainState::new(ctx) .and_then(|mut s| event::run(ctx, &mut s)); // Check if it ran successfully if let Err(e) = result { match e { GameError::UnknownError(text) => println!("Fatal:\n{}", text), e => println!("Fatal: {}", e) } } else { println!("Game exited cleanly"); } } struct MainState { ui_context: UiContext, ui: Ui, ui_input: Input, ui_cache: GgezCache, ui_root: Tree, model: ScriptTable, are_you_sure: bool, } impl MainState { pub fn new(ctx: &mut Context) -> GameResult<Self> { let screen_size = Vector2::new(1280.0, 720.0); // Register all the component classes, this makes them available to be used in templates. let mut classes = ComponentClasses::new(); classes.register::<markedly::class::ContainerClass>("container"); classes.register::<markedly::class::ButtonClass>("button"); // Set up the scripting runtime. // TODO: Here you can make custom helper functions available to templates. let runtime = ScriptRuntime::new(); // The context is a bundle of the systems needed for a UI to function. let ui_context = UiContext { classes, runtime, }; // This UI will make use of input. If your UI will not use input, for example if your UI is // an in-game screen, you don't need this. let ui_input = Input::new(); // Set up the UI cache. // This will keep track of rendering data, as well as resources to be used by templates. let mut ui_cache = GgezCache::new(); ui_cache.add_font("raleway", "/Raleway-Regular.ttf").map_err(emtg)?; ui_cache.add_font("cormorant", "/CormorantGaramond-Regular.ttf").map_err(emtg)?; // Load in a style template. // This defines some default styles and style classes to be used when displaying templates. let style = Style::from_reader(ctx.filesystem.open("/mark/_style.mark")?)?; // Load in the root template. // This template defines what the actual UI will look like, it contains components in the // layout you want them to be in, and with the attributes you want them to have. let root_template = Template::from_reader(ctx.filesystem.open("/mark/ui.mark")?)?; // Optionally we can provide a model with data to be used by the template. let mut model = ScriptTable::new(); model.set("are_you_sure", false); // Finally, actually set up the UI itself. let (ui, ui_root) = Ui::new( &root_template, Some(&model), style, screen_size, &ui_context, ).map_err(emtg)?; Ok(MainState { ui_context, ui, ui_input, ui_cache, ui_root, model, are_you_sure: false, }) } } impl EventHandler for MainState { fn update(&mut self, ctx: &mut Context) -> GameResult<()> { while let Some(event) = self.ui_root.event_sink().next() { match event.as_str() { "hello-pressed" => println!("Hello From UI!"), "goodbye-pressed" => { if self.are_you_sure { ctx.quit()?; } else { self.are_you_sure = true; // We can change the model at any point and update the UI. self.model.set("are_you_sure", true); self.ui.update_model(&self.ui_root, &self.model, &self.ui_context) .map_err(emtg)?; } }, _ => {}, } } Ok(()) } fn draw(&mut self, ctx: &mut Context) -> GameResult<()> { graphics::set_background_color(ctx, (0, 0, 0).into()); graphics::clear(ctx); // Draw the UI { let mut renderer = GgezRenderer::new(ctx, &mut self.ui_cache); markedly::render::render(&mut renderer, &mut self.ui).map_err(emtg)?; } graphics::present(ctx); Ok(()) } fn mouse_button_down_event( &mut self, _ctx: &mut Context, _button: MouseButton, x: i32, y: i32 ) { self.ui_input.handle_drag_started(Point2::new(x as f32, y as f32), &mut self.ui); } fn mouse_button_up_event( &mut self, _ctx: &mut Context, _button: MouseButton, x: i32, y: i32 ) { self.ui_input.handle_drag_ended(Point2::new(x as f32, y as f32), &mut self.ui); } fn mouse_motion_event( &mut self, _ctx: &mut Context, _state: MouseState, x: i32, y: i32, _xrel: i32, _yrel: i32 ) { self.ui_input.handle_cursor_moved(Point2::new(x as f32, y as f32), &mut self.ui); } }
use crate::erts::term::prelude::*; #[repr(C)] pub struct BinaryMatchResult { // The value matched by the match operation pub value: Term, // The rest of the binary (typically a MatchContext) pub rest: Term, // Whether the match was successful or not pub success: bool, } impl BinaryMatchResult { pub fn success(value: Term, rest: Term) -> Self { Self { value, rest, success: true, } } pub fn failed() -> Self { Self { value: Term::NONE, rest: Term::NONE, success: false, } } } pub fn match_raw<B>(bin: B, _unit: u8, size: Option<usize>) -> Result<BinaryMatchResult, ()> where B: Bitstring + MaybePartialByte, { let size = size.unwrap_or(0); let total_bits = bin.total_bit_len(); if size == 0 && total_bits == 0 { // TODO: t = bin_to_term let t = Term::NONE; return Ok(BinaryMatchResult::success(Term::NONE, t)); } unimplemented!() }
extern crate clap; extern crate sys_mount; use clap::{App, Arg}; use std::process::exit; use sys_mount::{unmount, UnmountFlags}; fn main() { let matches = App::new("umount") .arg(Arg::with_name("lazy").short("l").long("lazy")) .arg(Arg::with_name("source").required(true)) .get_matches(); let src = matches.value_of("source").unwrap(); let flags = if matches.is_present("lazy") { UnmountFlags::DETACH } else { UnmountFlags::empty() }; match unmount(src, flags) { Ok(()) => (), Err(why) => { eprintln!("failed to unmount {}: {}", src, why); exit(1); } } }
#![allow(clippy::nonstandard_macro_braces, clippy::too_many_arguments)] mod empty_structs; mod one_field_structs; mod structs_with_generic_type_params; mod two_field_structs; mod enums_ignore_variant; mod enums_with_generic_type_params; mod enums_with_items_with_and_without_fields; mod enums_with_multiple_empty_items; mod enums_with_one_empty_item; mod enums_with_one_item_multiple_fields; mod enums_with_one_item_one_field; mod recursive_enum; mod recursive_struct;
use crate::protocol::{AlphaKeys, BackKeys, Command, DirectionKeys, MetaKeys, Stick}; use crate::uinput::{Key, Side, UInputHandle}; pub fn apply_keys(input: &UInputHandle, command: Command) { match command { Command::Terminate => {} Command::Xbox(pressed) => send_xbox_key(input, pressed), Command::Keys { meta, alpha, direction, back, left_stick, right_stick, } => { let left_trigger = back.lt; let right_trigger = back.rt; send_meta_keys(input, meta); send_alpha_keys(input, alpha); send_direction_keys(input, direction); send_back_keys(input, back); send_left_stick(input, left_stick, left_trigger); send_right_stick(input, right_stick, right_trigger); } } } fn send_xbox_key(input: &UInputHandle, pressed: bool) { input.set_key_pressed(Key::Xbox, pressed); } fn send_meta_keys(input: &UInputHandle, keys: MetaKeys) { input.set_key_pressed(Key::Back, keys.back); input.set_key_pressed(Key::Select, keys.select); } fn send_alpha_keys(input: &UInputHandle, keys: AlphaKeys) { input.set_key_pressed(Key::A, keys.a); input.set_key_pressed(Key::B, keys.b); input.set_key_pressed(Key::X, keys.x); input.set_key_pressed(Key::Y, keys.y); } fn send_direction_keys(input: &UInputHandle, keys: DirectionKeys) { input.set_key_pressed(Key::Up, keys.up); input.set_key_pressed(Key::Down, keys.down); input.set_key_pressed(Key::Left, keys.left); input.set_key_pressed(Key::Right, keys.right); } fn send_back_keys(input: &UInputHandle, keys: BackKeys) { input.set_key_pressed(Key::LB, keys.lb); input.set_key_pressed(Key::RB, keys.rb); } fn send_left_stick(input: &UInputHandle, stick: Stick, trigger: u16) { input.update_axis(Side::Left, stick.x, stick.y, trigger); input.set_key_pressed(Key::ThumbLeft, stick.clicked); } fn send_right_stick(input: &UInputHandle, stick: Stick, trigger: u16) { input.update_axis(Side::Right, stick.x, stick.y, trigger); input.set_key_pressed(Key::ThumbRight, stick.clicked); }
//! Reading and writing sequentially from buffers. //! //! This is called buffered I/O, and allow buffers to support sequential reading //! and writing to and from buffer. //! //! The primary traits that govern this is [ReadBuf] and [WriteBuf]. pub use audio_core::{ReadBuf, WriteBuf}; mod utils; pub use self::utils::{copy_remaining, translate_remaining}; mod read; pub use self::read::Read; mod write; pub use self::write::Write; mod read_write; pub use self::read_write::ReadWrite;
use super::*; #[test] fn without_boolean_right_errors_badarg() { run!( |arc_process| strategy::term::is_not_boolean(arc_process.clone()), |right_boolean| { prop_assert_is_not_boolean!(result(true.into(), right_boolean), right_boolean); Ok(()) }, ); } #[test] fn with_boolean_right_returns_true() { TestRunner::new(Config::with_source_file(file!())) .run(&strategy::term::is_boolean(), |right| { prop_assert_eq!(result(true.into(), right), Ok(true.into())); Ok(()) }) .unwrap(); }
mod lexer; mod parser; mod token_stream; mod graphviz; use std::fs; use std::env; fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { println!("Usage: [invocation] filename") } else { let contents: String = fs::read_to_string(&args[1]).expect("Could not open file"); let tokens = lexer::lex_string(contents); let result = parser::parser::parse_stream(&tokens); println!("done! {:?}", result.expect("WHOOPS")); } }
use std::env; use std::error::Error; use std::fs; use std::str; use bioinformatics_algorithms::{pos_to_nt, profile_most_probable, score, Matrix}; pub fn profile_matrix_with_pseudocounts(motifs: &[String], k: usize) -> Matrix { let mut matrix: Matrix = vec![vec![0.0; k]; 4]; for i in 0..k { for nt in 0..4 { matrix[nt][i] = (motifs .iter() .filter(|motif| motif.as_bytes()[i] == pos_to_nt(nt)) .count() as f64 + 1.) / (motifs.len() as f64 + 4.); } } matrix } pub fn greedy_motif_search_with_pseudocounts(text: &[&str], k: usize) -> Vec<String> { let t = text.len(); let mut best: Vec<String> = text.iter().map(|motif| motif[..k].into()).collect(); let mut score_best = score(&best); for motif in text[0].as_bytes().windows(k) { let mut motifs = vec![String::from_utf8_lossy(motif).into()]; for j in 1..t { let profile = profile_matrix_with_pseudocounts(&motifs, k); let motifs_j = profile_most_probable(text[j], k, &profile); motifs.push(motifs_j); } let score_motifs = score(&motifs); if score_motifs < score_best { best = motifs; score_best = score_motifs; } } best.into_iter().map(String::from).collect() } fn main() -> Result<(), Box<dyn Error>> { let input: String = env::args() .nth(1) .unwrap_or("data/rosalind_ba2e.txt".into()); let data = fs::read_to_string(input)?; let mut lines = data.lines(); let mut ints = lines .next() .unwrap() .split(' ') .map(|x| x.parse().unwrap()) .take(2); let k = ints.next().unwrap(); let _t = ints.next().unwrap(); let text: Vec<&str> = lines.collect(); for kmer in greedy_motif_search_with_pseudocounts(&text, k) { println!("{}", kmer); } Ok(()) }
#![crate_type = "staticlib"] type ScriptFn = unsafe extern "C" fn() -> (); static mut THREADS: Vec<std::thread::JoinHandle<()>> = Vec::new(); #[no_mangle] extern "C" fn support_spawn_script(f: ScriptFn) { unsafe { THREADS.push(std::thread::spawn(move || { f() })); } } #[no_mangle] extern "C" fn support_detach_scripts() { unsafe { THREADS.clear() } } #[no_mangle] extern "C" fn support_join_scripts() { unsafe { for t in THREADS.drain(0..) { t.join().unwrap(); } } } #[no_mangle] extern "C" fn support_write_float(f: f64) { println!("{}", f); } #[no_mangle] extern "C" fn support_sleep(s: f64) { std::thread::sleep(std::time::Duration::from_secs_f64(s)) }
#![warn(clippy::all, clippy::pedantic)] #![allow(dead_code)] mod http; mod io; mod lttp; use crate::{ io::logic_files, lttp::{ AppState, DungeonState, GameState, LocationState, ServerConfig, }, }; use anyhow::{ bail, Result, }; use clap::{ crate_authors, crate_description, value_parser, Arg, ArgAction, ArgGroup, Command, }; use std::{ env, sync::{ Arc, RwLock, }, }; use tokio::sync::broadcast; use tracing::Level; use tracing_subscriber::{ filter::EnvFilter, prelude::*, }; #[allow(clippy::too_many_lines)] #[tokio::main] async fn main() -> Result<()> { let version_string = match option_env!("VERGEN_GIT_DESCRIBE") { Some(v) => v, None => env!("CARGO_PKG_VERSION"), }; let matches = Command::new("SD2SNES LttP Randomizer Tracker") .version(version_string) .author(crate_authors!(", ")) .about(crate_description!()) .arg( Arg::new("device") .help("The SD2SNES device to use in the Qusb2snes server.") .short('d') .long("device") .num_args(1), ) .arg( Arg::new("file") .help("JSON file to read game state from") .short('f') .long("file") .num_args(1), ) .group(ArgGroup::new("source").args(["device", "file"])) .arg( Arg::new("verbose") .help("Enable more verbose output (can be provided multiple times to increase verbosity)") .short('v') .long("verbose") .action(ArgAction::Count), ) .arg( Arg::new("port") .help("Port number to run the web UI server on") .short('p') .long("port") .num_args(1) .default_value("8000") .value_parser(value_parser!(u16)), ) .arg( Arg::new("server-address") .help("Address to bind the UI & websocket server to") .short('a') .long("address") .num_args(1) .default_value("0.0.0.0") .value_parser(value_parser!(std::net::IpAddr)), ) .get_matches(); let log_level = match matches.get_one::<u8>("verbose").copied() { None | Some(0) => Level::ERROR, Some(1) => Level::WARN, Some(2) => Level::INFO, Some(3) => Level::DEBUG, Some(_) => Level::TRACE, }; let server_port: u16 = match matches.try_get_one("port") { Ok(p) => { match p { Some(i) => *i, None => panic!("No port number provided."), } } Err(e) => panic!("Invalid port number: {e:?}"), }; let server_address: std::net::IpAddr = match matches.try_get_one("server-address") { Ok(a) => { match a { Some(a) => *a, None => panic!("No address provided."), } } Err(e) => panic!("Invalid address: {e:?}"), }; if std::env::var_os("RUST_LOG").is_none() { use std::ops::Add; let mut rust_log_setting = "sd2snes_lttp_rando_tracker=info,tower_http=debug".to_owned(); if log_level == Level::TRACE { rust_log_setting = rust_log_setting.add(",tokio=trace,runtime=trace"); }; std::env::set_var("RUST_LOG", rust_log_setting); } let console_layer = console_subscriber::spawn(); let filter = EnvFilter::from_default_env().add_directive(log_level.into()); if let Err(e) = tracing_subscriber::registry() .with(console_layer) .with(tracing_subscriber::fmt::layer()) .with(filter) .try_init() { bail!("Unable to initialize logging: {:?}", e); } let (source_type, data_source) = if let Some(file_name) = matches.get_one::<String>("file") { (lttp::server_config::DataSourceType::LocalFile, file_name.to_string()) } else if let Some(device_name) = matches.get_one::<String>("device") { (lttp::server_config::DataSourceType::QUsb2snes, device_name.to_string()) } else { (lttp::server_config::DataSourceType::default(), String::default()) }; let server_config = ServerConfig { data_poll_rate: 1_000, source_type, data_source, api_port: server_port, ..ServerConfig::default() }; let dungeons = logic_files::base_dungeon_data()?; let locations = logic_files::base_location_data()?; let (sender, _) = broadcast::channel(16); let app_state = Arc::new(AppState { dungeon_state: RwLock::new(DungeonState { dungeons, }), game_state: RwLock::new(GameState::default()), location_state: RwLock::new(LocationState { locations, }), server_config: RwLock::new(server_config), update_sender: sender, }); let app = http::build(app_state.clone()); let game_state_poller_app_state = app_state.clone(); tokio::spawn(async move { io::game_state_poller(game_state_poller_app_state).await; }); tokio::spawn(async move { io::device_list_poller(app_state).await; }); axum::Server::bind(&format!("{server_address}:{server_port}").parse().unwrap()) .serve(app.into_make_service()) .await .unwrap(); Ok(()) }
//! # Elements of Programming Languages //! //! These are short recipes for accomplishing common tasks. //! //! * [Whitespace](#whitespace) //! + [Wrapper combinators that eat whitespace before and after a parser](#wrapper-combinators-that-eat-whitespace-before-and-after-a-parser) //! * [Comments](#comments) //! + [`// C++/EOL-style comments`](#-ceol-style-comments) //! + [`/* C-style comments */`](#-c-style-comments-) //! * [Identifiers](#identifiers) //! + [`Rust-Style Identifiers`](#rust-style-identifiers) //! * [Literal Values](#literal-values) //! + [Escaped Strings](#escaped-strings) //! + [Integers](#integers) //! - [Hexadecimal](#hexadecimal) //! - [Octal](#octal) //! - [Binary](#binary) //! - [Decimal](#decimal) //! + [Floating Point Numbers](#floating-point-numbers) //! //! ## Whitespace //! //! //! //! ### Wrapper combinators that eat whitespace before and after a parser //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! error::ParserError, //! combinator::delimited, //! ascii::multispace0, //! }; //! //! /// A combinator that takes a parser `inner` and produces a parser that also consumes both leading and //! /// trailing whitespace, returning the output of `inner`. //! fn ws<'a, F, O, E: ParserError<&'a str>>(inner: F) -> impl Parser<&'a str, O, E> //! where //! F: Parser<&'a str, O, E>, //! { //! delimited( //! multispace0, //! inner, //! multispace0 //! ) //! } //! ``` //! //! To eat only trailing whitespace, replace `delimited(...)` with `terminated(&inner, multispace0)`. //! Likewise, the eat only leading whitespace, replace `delimited(...)` with `preceded(multispace0, //! &inner)`. You can use your own parser instead of `multispace0` if you want to skip a different set //! of lexemes. //! //! ## Comments //! //! ### `// C++/EOL-style comments` //! //! This version uses `%` to start a comment, does not consume the newline character, and returns an //! output of `()`. //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! error::ParserError, //! token::take_till1, //! }; //! //! pub fn peol_comment<'a, E: ParserError<&'a str>>(i: &mut &'a str) -> PResult<(), E> //! { //! ('%', take_till1(['\n', '\r'])) //! .void() // Output is thrown away. //! .parse_next(i) //! } //! ``` //! //! ### `/* C-style comments */` //! //! Inline comments surrounded with sentinel tags `(*` and `*)`. This version returns an output of `()` //! and does not handle nested comments. //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! error::ParserError, //! token::{tag, take_until0}, //! }; //! //! pub fn pinline_comment<'a, E: ParserError<&'a str>>(i: &mut &'a str) -> PResult<(), E> { //! ( //! "(*", //! take_until0("*)"), //! "*)" //! ) //! .void() // Output is thrown away. //! .parse_next(i) //! } //! ``` //! //! ## Identifiers //! //! ### `Rust-Style Identifiers` //! //! Parsing identifiers that may start with a letter (or underscore) and may contain underscores, //! letters and numbers may be parsed like this: //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! stream::AsChar, //! token::take_while, //! token::one_of, //! }; //! //! pub fn identifier<'s>(input: &mut &'s str) -> PResult<&'s str> { //! ( //! one_of(|c: char| c.is_alpha() || c == '_'), //! take_while(0.., |c: char| c.is_alphanum() || c == '_') //! ) //! .recognize() //! .parse_next(input) //! } //! ``` //! //! Let's say we apply this to the identifier `hello_world123abc`. The first element of the tuple //! would uses [`one_of`][crate::token::one_of] which would recognize `h`. The tuple ensures that //! `ello_world123abc` will be piped to the next [`take_while`][crate::token::take_while] parser, //! which recognizes every remaining character. However, the tuple returns a tuple of the results //! of its sub-parsers. The [`recognize`][crate::Parser::recognize] parser produces a `&str` of the //! input text that was parsed, which in this case is the entire `&str` `hello_world123abc`. //! //! ## Literal Values //! //! ### Escaped Strings //! //! ```rust #![doc = include_str!("../../examples/string/parser.rs")] //! ``` //! //! See also [`escaped`] and [`escaped_transform`]. //! //! ### Integers //! //! The following recipes all return string slices rather than integer values. How to obtain an //! integer value instead is demonstrated for hexadecimal integers. The others are similar. //! //! The parsers allow the grouping character `_`, which allows one to group the digits by byte, for //! example: `0xA4_3F_11_28`. If you prefer to exclude the `_` character, the lambda to convert from a //! string slice to an integer value is slightly simpler. You can also strip the `_` from the string //! slice that is returned, which is demonstrated in the second hexadecimal number parser. //! //! #### Hexadecimal //! //! The parser outputs the string slice of the digits without the leading `0x`/`0X`. //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::alt, //! combinator::{repeat}, //! combinator::{preceded, terminated}, //! token::one_of, //! token::tag, //! }; //! //! fn hexadecimal<'s>(input: &mut &'s str) -> PResult<&'s str> { // <'a, E: ParserError<&'a str>> //! preceded( //! alt(("0x", "0X")), //! repeat(1.., //! terminated(one_of(('0'..='9', 'a'..='f', 'A'..='F')), repeat(0.., '_').map(|()| ())) //! ).map(|()| ()).recognize() //! ).parse_next(input) //! } //! ``` //! //! If you want it to return the integer value instead, use map: //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::alt, //! combinator::{repeat}, //! combinator::{preceded, terminated}, //! token::one_of, //! token::tag, //! }; //! //! fn hexadecimal_value(input: &mut &str) -> PResult<i64> { //! preceded( //! alt(("0x", "0X")), //! repeat(1.., //! terminated(one_of(('0'..='9', 'a'..='f', 'A'..='F')), repeat(0.., '_').map(|()| ())) //! ).map(|()| ()).recognize() //! ).try_map( //! |out: &str| i64::from_str_radix(&str::replace(&out, "_", ""), 16) //! ).parse_next(input) //! } //! ``` //! //! See also [`hex_uint`] //! //! #### Octal //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::alt, //! combinator::{repeat}, //! combinator::{preceded, terminated}, //! token::one_of, //! token::tag, //! }; //! //! fn octal<'s>(input: &mut &'s str) -> PResult<&'s str> { //! preceded( //! alt(("0o", "0O")), //! repeat(1.., //! terminated(one_of('0'..='7'), repeat(0.., '_').map(|()| ())) //! ).map(|()| ()).recognize() //! ).parse_next(input) //! } //! ``` //! //! #### Binary //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::alt, //! combinator::{repeat}, //! combinator::{preceded, terminated}, //! token::one_of, //! token::tag, //! }; //! //! fn binary<'s>(input: &mut &'s str) -> PResult<&'s str> { //! preceded( //! alt(("0b", "0B")), //! repeat(1.., //! terminated(one_of('0'..='1'), repeat(0.., '_').map(|()| ())) //! ).map(|()| ()).recognize() //! ).parse_next(input) //! } //! ``` //! //! #### Decimal //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::{repeat}, //! combinator::terminated, //! token::one_of, //! }; //! //! fn decimal<'s>(input: &mut &'s str) -> PResult<&'s str> { //! repeat(1.., //! terminated(one_of('0'..='9'), repeat(0.., '_').map(|()| ())) //! ).map(|()| ()) //! .recognize() //! .parse_next(input) //! } //! ``` //! //! See also [`dec_uint`] and [`dec_int`] //! //! ### Floating Point Numbers //! //! The following is adapted from [the Python parser by Valentin Lorentz](https://github.com/ProgVal/rust-python-parser/blob/master/src/numbers.rs). //! //! ```rust //! use winnow::prelude::*; //! use winnow::{ //! combinator::alt, //! combinator::{repeat}, //! combinator::opt, //! combinator::{preceded, terminated}, //! token::one_of, //! }; //! //! fn float<'s>(input: &mut &'s str) -> PResult<&'s str> { //! alt(( //! // Case one: .42 //! ( //! '.', //! decimal, //! opt(( //! one_of(['e', 'E']), //! opt(one_of(['+', '-'])), //! decimal //! )) //! ).recognize() //! , // Case two: 42e42 and 42.42e42 //! ( //! decimal, //! opt(preceded( //! '.', //! decimal, //! )), //! one_of(['e', 'E']), //! opt(one_of(['+', '-'])), //! decimal //! ).recognize() //! , // Case three: 42. and 42.42 //! ( //! decimal, //! '.', //! opt(decimal) //! ).recognize() //! )).parse_next(input) //! } //! //! fn decimal<'s>(input: &mut &'s str) -> PResult<&'s str> { //! repeat(1.., //! terminated(one_of('0'..='9'), repeat(0.., '_').map(|()| ())) //! ). //! map(|()| ()) //! .recognize() //! .parse_next(input) //! } //! ``` //! //! See also [`float`] #![allow(unused_imports)] use crate::ascii::dec_int; use crate::ascii::dec_uint; use crate::ascii::escaped; use crate::ascii::escaped_transform; use crate::ascii::float; use crate::ascii::hex_uint;
/// File to define symbols in LaTeX /// #[derive(Debug, PartialEq, Clone)] pub enum Symbols { /// = Equals, /// <= LessOrEquals, /// < Less, /// >= MoreOrEquals, /// > More, /// != Diff, } impl Symbols { /// Returns the enum corresponding to the String pub fn get_symbol(symb: String) -> Self { match symb.as_ref() { "=" => Symbols::Equals, "==" => Symbols::Equals, "<=" => Symbols::LessOrEquals, "<" => Symbols::Less, ">=" => Symbols::MoreOrEquals, ">" => Symbols::More, "!=" => Symbols::Diff, "<>" => Symbols::Diff, _ => panic!("get_symbol: The symbol {} is not a valid symbol !", symb), } } /// Returns the string corresponding to the enum pub fn get_string(&self) -> &str { match *self { Symbols::Equals => "=", Symbols::LessOrEquals => "<=", Symbols::Less => "<", Symbols::MoreOrEquals => ">=", Symbols::More => ">", Symbols::Diff => "!=", } } /// Returns the LaTeX "code" for each item pub fn latex_code(&self) -> String { let x = match *self { Symbols::Equals => " = ", Symbols::LessOrEquals => " \\leq ", Symbols::Less => " < ", Symbols::MoreOrEquals => " \\geq ", Symbols::More => " > ", Symbols::Diff => " \\neq ", }; String::from(x) } } pub fn is_op(s: &str) -> bool { s == "==" || s == "=" || s == "<" || s == "<=" || s == ">" || s == ">=" || s == "!=" || s == "<>" } #[cfg(test)] mod tests_symbols { use super::*; #[test] fn getting_symbols() { assert_eq!(Symbols::get_symbol("==".to_string()), Symbols::Equals); assert_eq!(Symbols::get_symbol("=".to_string()), Symbols::Equals); assert_eq!(Symbols::get_symbol(">=".to_string()), Symbols::MoreOrEquals); assert_eq!(Symbols::get_symbol("<=".to_string()), Symbols::LessOrEquals); assert_eq!(Symbols::get_symbol("<".to_string()), Symbols::Less); assert_eq!(Symbols::get_symbol(">".to_string()), Symbols::More); assert_eq!(Symbols::get_symbol("!=".to_string()), Symbols::Diff); assert_eq!(Symbols::get_symbol("<>".to_string()), Symbols::Diff); } #[test] fn getting_strings() { assert_eq!(Symbols::get_string(&Symbols::Equals), "="); assert_eq!(Symbols::get_string(&Symbols::More), ">"); assert_eq!(Symbols::get_string(&Symbols::MoreOrEquals), ">="); assert_eq!(Symbols::get_string(&Symbols::LessOrEquals), "<=");; assert_eq!(Symbols::get_string(&Symbols::Less), "<"); assert_eq!(Symbols::get_string(&Symbols::Diff), "!="); } }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::BTreeMap; use common_exception::Result; use common_meta_app::share::ShareDatabaseSpec; use common_meta_app::share::ShareSpec; use common_meta_app::share::ShareTableInfoMap; use common_meta_app::share::ShareTableSpec; use opendal::Operator; pub const SHARE_CONFIG_PREFIX: &str = "_share_config"; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub struct ShareSpecVec { share_specs: BTreeMap<String, ext::ShareSpecExt>, } pub fn share_table_info_location(tenant: &str, share_name: &str) -> String { format!( "{}/{}/{}_table_info.json", tenant, SHARE_CONFIG_PREFIX, share_name ) } pub async fn save_share_spec( tenant: &String, operator: Operator, spec_vec: Option<Vec<ShareSpec>>, share_table_info: Option<&ShareTableInfoMap>, ) -> Result<()> { if let Some(share_spec) = spec_vec { let location = format!("{}/{}/share_specs.json", tenant, SHARE_CONFIG_PREFIX); let mut share_spec_vec = ShareSpecVec::default(); for spec in share_spec { let share_name = spec.name.clone(); let share_spec_ext = ext::ShareSpecExt::from_share_spec(spec, &operator); share_spec_vec .share_specs .insert(share_name, share_spec_ext); } operator .write(&location, serde_json::to_vec(&share_spec_vec)?) .await?; } // save share table info if let Some((share_name, share_table_info)) = share_table_info { let share_name = share_name.clone(); let location = share_table_info_location(tenant, &share_name); match share_table_info { Some(table_info_map) => { operator .write(&location, serde_json::to_vec(table_info_map)?) .await?; } None => { operator.delete(&location).await?; } } } Ok(()) } mod ext { use storages_common_table_meta::table::database_storage_prefix; use storages_common_table_meta::table::table_storage_prefix; use super::*; #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] struct WithLocation<T> { location: String, #[serde(flatten)] t: T, } /// An extended form of [ShareSpec], which decorates [ShareDatabaseSpec] and [ShareTableSpec] /// with location #[derive(serde::Serialize, serde::Deserialize, Clone, Debug, Default, Eq, PartialEq)] pub(super) struct ShareSpecExt { name: String, share_id: u64, version: u64, database: Option<WithLocation<ShareDatabaseSpec>>, tables: Vec<WithLocation<ShareTableSpec>>, tenants: Vec<String>, } impl ShareSpecExt { pub fn from_share_spec(spec: ShareSpec, operator: &Operator) -> Self { Self { name: spec.name, share_id: spec.share_id, version: spec.version, database: spec.database.map(|db_spec| WithLocation { location: shared_database_prefix(operator, db_spec.id), t: db_spec, }), tables: spec .tables .into_iter() .map(|tbl_spec| WithLocation { location: shared_table_prefix( operator, tbl_spec.database_id, tbl_spec.table_id, ), t: tbl_spec, }) .collect(), tenants: spec.tenants, } } } /// Returns prefix path which covers all the data of give table. /// something like "query-storage-bd5efc6/tnc7yee14/501248/501263/", where /// - "/query-storage-bd5efc6/tnc7yee14/" is the storage prefix /// - "501248/" is the database id suffixed with '/' /// - "501263/" is the table id suffixed with '/' fn shared_table_prefix(operator: &Operator, database_id: u64, table_id: u64) -> String { let operator_meta_data = operator.info(); let storage_prefix = operator_meta_data.root(); let table_storage_prefix = table_storage_prefix(database_id, table_id); // storage_prefix has suffix character '/' format!("{}{}/", storage_prefix, table_storage_prefix) } /// Returns prefix path which covers all the data of give database. /// something like "query-storage-bd5efc6/tnc7yee14/501248/", where /// - "/query-storage-bd5efc6/tnc7yee14/" is the storage prefix /// - "501248/" is the database id suffixed with '/' fn shared_database_prefix(operator: &Operator, database_id: u64) -> String { let operator_meta_data = operator.info(); let storage_prefix = operator_meta_data.root(); let database_storage_prefix = database_storage_prefix(database_id); // storage_prefix has suffix character '/' format!("{}{}/", storage_prefix, database_storage_prefix) } #[cfg(test)] mod tests { use opendal::services::Fs; use super::*; #[test] fn test_serialize_share_spec_ext() -> Result<()> { let share_spec = ShareSpec { name: "test_share_name".to_string(), version: 1, share_id: 1, database: Some(ShareDatabaseSpec { name: "share_database".to_string(), id: 1, }), tables: vec![ShareTableSpec { name: "share_table".to_string(), database_id: 1, table_id: 1, presigned_url_timeout: "100s".to_string(), }], tenants: vec!["test_tenant".to_owned()], }; let tmp_dir = tempfile::tempdir()?; let test_root = tmp_dir.path().join("test_cluster_id/test_tenant_id"); let test_root_str = test_root.to_str().unwrap(); let operator = { let mut builder = Fs::default(); builder.root(test_root_str); Operator::new(builder)?.finish() }; let share_spec_ext = ShareSpecExt::from_share_spec(share_spec, &operator); let spec_json_value = serde_json::to_value(share_spec_ext).unwrap(); use serde_json::json; let expected = json!({ "name": "test_share_name", "version": 1, "share_id": 1, "database": { "location": format!("{}/1/", test_root_str), "name": "share_database", "id": 1 }, "tables": [ { "location": format!("{}/1/1/", test_root_str), "name": "share_table", "database_id": 1, "table_id": 1, "presigned_url_timeout": "100s" } ], "tenants": [ "test_tenant" ] }); assert_eq!(expected, spec_json_value); Ok(()) } } }
//! EVM module. pub mod backend; pub mod derive_caller; pub mod precompile; pub mod raw_tx; pub mod types; use evm::{ executor::{MemoryStackState, StackExecutor, StackSubstateMetadata}, Config as EVMConfig, }; use thiserror::Error; use oasis_runtime_sdk::{ context::{BatchContext, Context, TxContext}, error, module::{self, CallResult, Module as _}, modules::{ self, accounts::API as _, core::{self, Error as CoreError, API as _}, }, storage, types::{ address::{self, Address}, token, transaction, transaction::Transaction, }, }; use evm::backend::ApplyBackend; use types::{H160, H256, U256}; #[cfg(test)] mod test; /// Unique module name. const MODULE_NAME: &str = "evm"; /// State schema constants. pub mod state { use super::{storage, H160}; /// Prefix for Ethereum account code in our storage (maps H160 -> Vec<u8>). pub const CODES: &[u8] = &[0x01]; /// Prefix for Ethereum account storage in our storage (maps H160||H256 -> H256). pub const STORAGES: &[u8] = &[0x02]; /// Prefix for Ethereum block hashes (only for last BLOCK_HASH_WINDOW_SIZE blocks /// excluding current) storage in our storage (maps Round -> H256). pub const BLOCK_HASHES: &[u8] = &[0x03]; /// The number of hash blocks that can be obtained from the current blockchain. pub const BLOCK_HASH_WINDOW_SIZE: u64 = 256; /// Get a typed store for the given address' storage. pub fn storage<'a, S: storage::Store + 'a>( state: S, address: &'a H160, ) -> storage::TypedStore<impl storage::Store + 'a> { let store = storage::PrefixStore::new(state, &crate::MODULE_NAME); let storages = storage::PrefixStore::new(store, &STORAGES); storage::TypedStore::new(storage::HashedStore::<_, blake3::Hasher>::new( storage::PrefixStore::new(storages, address), )) } /// Get a typed store for codes of all contracts. pub fn codes<'a, S: storage::Store + 'a>( state: S, ) -> storage::TypedStore<impl storage::Store + 'a> { let store = storage::PrefixStore::new(state, &crate::MODULE_NAME); storage::TypedStore::new(storage::PrefixStore::new(store, &CODES)) } /// Get a typed store for historic block hashes. pub fn block_hashes<'a, S: storage::Store + 'a>( state: S, ) -> storage::TypedStore<impl storage::Store + 'a> { let store = storage::PrefixStore::new(state, &crate::MODULE_NAME); storage::TypedStore::new(storage::PrefixStore::new(store, &BLOCK_HASHES)) } } /// Module configuration. pub trait Config: 'static { /// Module that is used for accessing accounts. type Accounts: modules::accounts::API; /// The chain ID to supply when a contract requests it. Ethereum-format transactions must use /// this chain ID. const CHAIN_ID: u64; /// Token denomination used as the native EVM token. const TOKEN_DENOMINATION: token::Denomination; /// Maps an Ethereum address into an SDK account address. fn map_address(address: primitive_types::H160) -> Address { Address::new( address::ADDRESS_V0_SECP256K1ETH_CONTEXT, address::ADDRESS_V0_VERSION, address.as_ref(), ) } } pub struct Module<Cfg: Config> { _cfg: std::marker::PhantomData<Cfg>, } /// Errors emitted by the EVM module. #[derive(Error, Debug, oasis_runtime_sdk::Error)] pub enum Error { #[error("invalid argument")] #[sdk_error(code = 1)] InvalidArgument, #[error("EVM error: {0}")] #[sdk_error(code = 2)] EVMError(String), #[error("invalid signer type")] #[sdk_error(code = 3)] InvalidSignerType, #[error("fee overflow")] #[sdk_error(code = 4)] FeeOverflow, #[error("gas limit too low: {0} required")] #[sdk_error(code = 5)] GasLimitTooLow(u64), #[error("insufficient balance")] #[sdk_error(code = 6)] InsufficientBalance, #[error("core: {0}")] #[sdk_error(transparent)] Core(#[from] CoreError), } /// Gas costs. #[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)] pub struct GasCosts {} /// Parameters for the EVM module. #[derive(Clone, Default, Debug, cbor::Encode, cbor::Decode)] pub struct Parameters { /// Gas costs. pub gas_costs: GasCosts, } impl module::Parameters for Parameters { type Error = (); fn validate_basic(&self) -> Result<(), Self::Error> { Ok(()) } } /// Genesis state for the EVM module. #[derive(Clone, Debug, Default, cbor::Encode, cbor::Decode)] pub struct Genesis { pub parameters: Parameters, } /// Events emitted by the EVM module. #[derive(Debug, cbor::Encode, oasis_runtime_sdk::Event)] #[cbor(untagged)] pub enum Event { #[sdk_event(code = 1)] Log { address: H160, topics: Vec<H256>, data: Vec<u8>, }, } impl<Cfg: Config> module::Module for Module<Cfg> { const NAME: &'static str = MODULE_NAME; type Error = Error; type Event = Event; type Parameters = Parameters; } /// Interface that can be called from other modules. pub trait API { /// Perform an Ethereum CREATE transaction. /// Returns 160-bit address of created contract. fn create<C: TxContext>(ctx: &mut C, value: U256, init_code: Vec<u8>) -> Result<Vec<u8>, Error>; /// Perform an Ethereum CALL transaction. fn call<C: TxContext>( ctx: &mut C, address: H160, value: U256, data: Vec<u8>, ) -> Result<Vec<u8>, Error>; /// Peek into EVM storage. /// Returns 256-bit value stored at given contract address and index (slot) /// in the storage. fn get_storage<C: Context>(ctx: &mut C, address: H160, index: H256) -> Result<Vec<u8>, Error>; /// Peek into EVM code storage. /// Returns EVM bytecode of contract at given address. fn get_code<C: Context>(ctx: &mut C, address: H160) -> Result<Vec<u8>, Error>; /// Get EVM account balance. fn get_balance<C: Context>(ctx: &mut C, address: H160) -> Result<u128, Error>; /// Simulate an Ethereum CALL. fn simulate_call<C: Context>( ctx: &mut C, gas_price: U256, gas_limit: u64, caller: H160, address: H160, value: U256, data: Vec<u8>, ) -> Result<Vec<u8>, Error>; } impl<Cfg: Config> API for Module<Cfg> { fn create<C: TxContext>( ctx: &mut C, value: U256, init_code: Vec<u8>, ) -> Result<Vec<u8>, Error> { let caller = Self::derive_caller(ctx)?; if ctx.is_check_only() { return Ok(vec![]); } Self::do_evm(caller, ctx, |exec, gas_limit| { let address = exec.create_address(evm::CreateScheme::Legacy { caller: caller.into(), }); ( exec.transact_create(caller.into(), value.into(), init_code, gas_limit), address.as_bytes().to_vec(), ) }) } fn call<C: TxContext>( ctx: &mut C, address: H160, value: U256, data: Vec<u8>, ) -> Result<Vec<u8>, Error> { let caller = Self::derive_caller(ctx)?; if ctx.is_check_only() { return Ok(vec![]); } Self::do_evm(caller, ctx, |exec, gas_limit| { exec.transact_call(caller.into(), address.into(), value.into(), data, gas_limit) }) } fn get_storage<C: Context>(ctx: &mut C, address: H160, index: H256) -> Result<Vec<u8>, Error> { let store = storage::PrefixStore::new(ctx.runtime_state(), &crate::MODULE_NAME); let storages = storage::PrefixStore::new(store, &state::STORAGES); let s = storage::TypedStore::new(storage::HashedStore::<_, blake3::Hasher>::new( storage::PrefixStore::new(storages, &address), )); let result: H256 = s.get(&index).unwrap_or_default(); Ok(result.as_bytes().to_vec()) } fn get_code<C: Context>(ctx: &mut C, address: H160) -> Result<Vec<u8>, Error> { let store = storage::PrefixStore::new(ctx.runtime_state(), &crate::MODULE_NAME); let codes = storage::TypedStore::new(storage::PrefixStore::new(store, &state::CODES)); Ok(codes.get(&address).unwrap_or_default()) } fn get_balance<C: Context>(ctx: &mut C, address: H160) -> Result<u128, Error> { let state = ctx.runtime_state(); let address = Cfg::map_address(address.into()); Ok(Cfg::Accounts::get_balance(state, address, Cfg::TOKEN_DENOMINATION).unwrap_or_default()) } fn simulate_call<C: Context>( ctx: &mut C, gas_price: U256, gas_limit: u64, caller: H160, address: H160, value: U256, data: Vec<u8>, ) -> Result<Vec<u8>, Error> { ctx.with_simulation(|mut sctx| { let call_tx = transaction::Transaction { version: 1, call: transaction::Call { format: transaction::CallFormat::Plain, method: "evm.Call".to_owned(), body: cbor::to_value(types::Call { address, value, data: data.clone(), }), }, auth_info: transaction::AuthInfo { signer_info: vec![], fee: transaction::Fee { amount: token::BaseUnits::new( gas_price .checked_mul(U256::from(gas_limit)) .ok_or(Error::FeeOverflow)? .as_u128(), Cfg::TOKEN_DENOMINATION, ), gas: gas_limit, consensus_messages: 0, }, }, }; sctx.with_tx(0, call_tx, |mut txctx, _call| { Self::do_evm(caller, &mut txctx, |exec, gas_limit| { exec.transact_call(caller.into(), address.into(), value.into(), data, gas_limit) }) }) }) } } impl<Cfg: Config> Module<Cfg> { const EVM_CONFIG: EVMConfig = EVMConfig::istanbul(); fn do_evm<C, F, V>(source: H160, ctx: &mut C, f: F) -> Result<V, Error> where F: FnOnce( &mut StackExecutor<'static, MemoryStackState<'_, 'static, backend::Backend<'_, C, Cfg>>>, u64, ) -> (evm::ExitReason, V), C: TxContext, { let gas_limit: u64 = core::Module::remaining_tx_gas(ctx); let gas_price: primitive_types::U256 = ctx.tx_auth_info().fee.gas_price().into(); let fee_denomination = ctx.tx_auth_info().fee.amount.denomination().clone(); let vicinity = backend::Vicinity { gas_price: gas_price.into(), origin: source, }; // The maximum gas fee has already been withdrawn in authenticate_tx(). let max_gas_fee = gas_price .checked_mul(primitive_types::U256::from(gas_limit)) .ok_or(Error::FeeOverflow)?; let mut backend = backend::Backend::<'_, C, Cfg>::new(ctx, vicinity); let metadata = StackSubstateMetadata::new(gas_limit, &Self::EVM_CONFIG); let stackstate = MemoryStackState::new(metadata, &backend); let mut executor = StackExecutor::new_with_precompile( stackstate, &Self::EVM_CONFIG, precompile::precompiled_contract, ); // Run EVM. let (exit_reason, exit_value) = f(&mut executor, gas_limit); if !exit_reason.is_succeed() { return Err(Error::EVMError(format!("{:?}", exit_reason))); } let gas_used = executor.used_gas(); if gas_used > gas_limit { // NOTE: This should never happen as the gas was accounted for in advance. core::Module::use_tx_gas(ctx, gas_limit)?; return Err(Error::GasLimitTooLow(gas_used)); } // Return the difference between the pre-paid max_gas and actually used gas. let fee = executor.fee(gas_price); let return_fee = max_gas_fee .checked_sub(fee) .ok_or(Error::InsufficientBalance)?; let (vals, logs) = executor.into_state().deconstruct(); backend.apply(vals, logs, true); core::Module::use_tx_gas(ctx, gas_used)?; // Move the difference from the fee accumulator back to the caller. let caller_address = Cfg::map_address(source.into()); Cfg::Accounts::move_from_fee_accumulator( ctx, caller_address, &token::BaseUnits::new(return_fee.as_u128(), fee_denomination), ) .map_err(|_| Error::InsufficientBalance)?; Ok(exit_value) } fn derive_caller<C>(ctx: &mut C) -> Result<H160, Error> where C: TxContext, { derive_caller::from_tx_auth_info(ctx.tx_auth_info()) } fn tx_create<C: TxContext>(ctx: &mut C, body: types::Create) -> Result<Vec<u8>, Error> { Self::create(ctx, body.value, body.init_code) } fn tx_call<C: TxContext>(ctx: &mut C, body: types::Call) -> Result<Vec<u8>, Error> { Self::call(ctx, body.address, body.value, body.data) } fn query_storage<C: Context>(ctx: &mut C, body: types::StorageQuery) -> Result<Vec<u8>, Error> { Self::get_storage(ctx, body.address, body.index) } fn query_code<C: Context>(ctx: &mut C, body: types::CodeQuery) -> Result<Vec<u8>, Error> { Self::get_code(ctx, body.address) } fn query_balance<C: Context>(ctx: &mut C, body: types::BalanceQuery) -> Result<u128, Error> { Self::get_balance(ctx, body.address) } fn query_simulate_call<C: Context>( ctx: &mut C, body: types::SimulateCallQuery, ) -> Result<Vec<u8>, Error> { Self::simulate_call( ctx, body.gas_price, body.gas_limit, body.caller, body.address, body.value, body.data, ) } } impl<Cfg: Config> module::MethodHandler for Module<Cfg> { fn dispatch_call<C: TxContext>( ctx: &mut C, method: &str, body: cbor::Value, ) -> module::DispatchResult<cbor::Value, CallResult> { match method { "evm.Create" => module::dispatch_call(ctx, body, Self::tx_create), "evm.Call" => module::dispatch_call(ctx, body, Self::tx_call), _ => module::DispatchResult::Unhandled(body), } } fn dispatch_query<C: Context>( ctx: &mut C, method: &str, args: cbor::Value, ) -> module::DispatchResult<cbor::Value, Result<cbor::Value, error::RuntimeError>> { match method { "evm.Storage" => module::dispatch_query(ctx, args, Self::query_storage), "evm.Code" => module::dispatch_query(ctx, args, Self::query_code), "evm.Balance" => module::dispatch_query(ctx, args, Self::query_balance), "evm.SimulateCall" => module::dispatch_query(ctx, args, Self::query_simulate_call), _ => module::DispatchResult::Unhandled(args), } } } impl<Cfg: Config> Module<Cfg> { /// Initialize state from genesis. fn init<C: Context>(ctx: &mut C, genesis: Genesis) { // Set genesis parameters. Self::set_params(ctx.runtime_state(), genesis.parameters); } /// Migrate state from a previous version. fn migrate<C: Context>(_ctx: &mut C, _from: u32) -> bool { // No migrations currently supported. false } } impl<Cfg: Config> module::MigrationHandler for Module<Cfg> { type Genesis = Genesis; fn init_or_migrate<C: Context>( ctx: &mut C, meta: &mut modules::core::types::Metadata, genesis: Self::Genesis, ) -> bool { let version = meta.versions.get(Self::NAME).copied().unwrap_or_default(); if version == 0 { // Initialize state from genesis. Self::init(ctx, genesis); meta.versions.insert(Self::NAME.to_owned(), Self::VERSION); return true; } // Perform migration. Self::migrate(ctx, version) } } impl<Cfg: Config> module::AuthHandler for Module<Cfg> { fn decode_tx<C: Context>( _ctx: &mut C, scheme: &str, body: &[u8], ) -> Result<Option<Transaction>, CoreError> { match scheme { "evm.ethereum.v0" => Ok(Some( raw_tx::decode(body, Some(Cfg::CHAIN_ID)) .map_err(CoreError::MalformedTransaction)?, )), _ => Ok(None), } } } impl<Cfg: Config> module::BlockHandler for Module<Cfg> { fn end_block<C: Context>(ctx: &mut C) { // Update the list of historic block hashes. let block_number = ctx.runtime_header().round; let block_hash = ctx.runtime_header().encoded_hash(); let mut block_hashes = state::block_hashes(ctx.runtime_state()); let current_number = block_number; block_hashes.insert(&block_number.to_be_bytes(), block_hash); if current_number > state::BLOCK_HASH_WINDOW_SIZE { let start_number = current_number - state::BLOCK_HASH_WINDOW_SIZE; block_hashes.remove(&start_number.to_be_bytes()); } } } impl<Cfg: Config> module::InvariantHandler for Module<Cfg> {}
// FIXME: Most of these should be uints. const rc_base_field_refcnt: int = 0; // FIXME: import from std::dbg when imported consts work. const const_refcount: uint = 0x7bad_face_u; const task_field_refcnt: int = 0; const task_field_stk: int = 2; const task_field_runtime_sp: int = 3; const task_field_rust_sp: int = 4; const task_field_gc_alloc_chain: int = 5; const task_field_dom: int = 6; const n_visible_task_fields: int = 7; const dom_field_interrupt_flag: int = 1; const frame_glue_fns_field_mark: int = 0; const frame_glue_fns_field_drop: int = 1; const frame_glue_fns_field_reloc: int = 2; const box_rc_field_refcnt: int = 0; const box_rc_field_body: int = 1; const general_code_alignment: int = 16; const vec_elt_rc: int = 0; const vec_elt_alloc: int = 1; const vec_elt_fill: int = 2; const vec_elt_pad: int = 3; const vec_elt_data: int = 4; const tydesc_field_first_param: int = 0; const tydesc_field_size: int = 1; const tydesc_field_align: int = 2; const tydesc_field_copy_glue: int = 3; const tydesc_field_drop_glue: int = 4; const tydesc_field_free_glue: int = 5; const tydesc_field_sever_glue: int = 6; const tydesc_field_mark_glue: int = 7; // FIXME no longer used in rustc, drop when rustboot is gone const tydesc_field_obj_drop_glue: int = 8; const tydesc_field_is_stateful: int = 9; const tydesc_field_cmp_glue: int = 10; const n_tydesc_fields: int = 11; const cmp_glue_op_eq: uint = 0u; const cmp_glue_op_lt: uint = 1u; const cmp_glue_op_le: uint = 2u; const obj_field_vtbl: int = 0; const obj_field_box: int = 1; const obj_body_elt_tydesc: int = 0; const obj_body_elt_typarams: int = 1; const obj_body_elt_fields: int = 2; // The base object to which an anonymous object is attached. const obj_body_elt_inner_obj: int = 3; // The two halves of a closure: code and environment. const fn_field_code: int = 0; const fn_field_box: int = 1; const closure_elt_tydesc: int = 0; const closure_elt_bindings: int = 1; const closure_elt_ty_params: int = 2; const ivec_default_length: uint = 4u; const ivec_elt_len: uint = 0u; const ivec_elt_alen: uint = 1u; const ivec_elt_elems: uint = 2u; const ivec_heap_stub_elt_zero: uint = 0u; const ivec_heap_stub_elt_alen: uint = 1u; const ivec_heap_stub_elt_ptr: uint = 2u; const ivec_heap_elt_len: uint = 0u; const ivec_heap_elt_elems: uint = 1u; const worst_case_glue_call_args: int = 7; fn memcpy_glue_name() -> str { ret "rust_memcpy_glue"; } fn bzero_glue_name() -> str { ret "rust_bzero_glue"; } fn yield_glue_name() -> str { ret "rust_yield_glue"; } fn no_op_type_glue_name() -> str { ret "rust_no_op_type_glue"; } // // Local Variables: // mode: rust // fill-column: 78; // indent-tabs-mode: nil // c-basic-offset: 4 // buffer-file-coding-system: utf-8-unix // compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'"; // End: //
//! Clause allocator. use std::{mem::transmute, slice}; use varisat_formula::{lit::LitIdx, Lit}; use super::{Clause, ClauseHeader, HEADER_LEN}; /// Integer type used to store offsets into [`ClauseAlloc`]'s memory. type ClauseOffset = u32; /// Bump allocator for clause storage. /// /// Clauses are allocated from a single continuous buffer. Clauses cannot be freed individually. To /// reclaim space from deleted clauses, a new `ClauseAlloc` is created and the remaining clauses are /// copied over. /// /// When the `ClauseAlloc`'s buffer is full, it is reallocated using the growing strategy of /// [`Vec`]. External references ([`ClauseRef`]) store an offset into the `ClauseAlloc`'s memory and /// remaind valid when the buffer is grown. Clauses are aligned and the offset represents a multiple /// of the alignment size. This allows using 32-bit offsets while still supporting up to 16GB of /// clauses. #[derive(Default)] pub struct ClauseAlloc { buffer: Vec<LitIdx>, } impl ClauseAlloc { /// Create an emtpy clause allocator. pub fn new() -> ClauseAlloc { ClauseAlloc::default() } /// Create a clause allocator with preallocated capacity. pub fn with_capacity(capacity: usize) -> ClauseAlloc { ClauseAlloc { buffer: Vec::with_capacity(capacity), } } /// Allocate space for and add a new clause. /// /// Clauses have a minimal size of 3, as binary and unit clauses are handled separately. This is /// enforced on the ClauseAlloc level to safely avoid extra bound checks when accessing the /// initial literals of a clause. /// /// The size of the header will be set to the size of the given slice. The returned /// [`ClauseRef`] can be used to access the new clause. pub fn add_clause(&mut self, mut header: ClauseHeader, lits: &[Lit]) -> ClauseRef { let offset = self.buffer.len(); assert!( lits.len() >= 3, "ClauseAlloc can only store ternary and larger clauses" ); // TODO Maybe let the caller handle this? assert!( offset <= (ClauseRef::max_offset() as usize), "Exceeded ClauseAlloc's maximal buffer size" ); header.set_len(lits.len()); self.buffer.extend_from_slice(&header.data); let lit_idx_slice = unsafe { // This is safe as Lit and LitIdx have the same representation slice::from_raw_parts(lits.as_ptr() as *const LitIdx, lits.len()) }; self.buffer.extend_from_slice(lit_idx_slice); ClauseRef { offset: offset as ClauseOffset, } } /// Access the header of a clause. pub fn header(&self, cref: ClauseRef) -> &ClauseHeader { let offset = cref.offset as usize; assert!( offset as usize + HEADER_LEN <= self.buffer.len(), "ClauseRef out of bounds" ); unsafe { self.header_unchecked(cref) } } /// Mutate the header of a clause. pub fn header_mut(&mut self, cref: ClauseRef) -> &mut ClauseHeader { let offset = cref.offset as usize; assert!( offset as usize + HEADER_LEN <= self.buffer.len(), "ClauseRef out of bounds" ); unsafe { self.header_unchecked_mut(cref) } } unsafe fn header_unchecked(&self, cref: ClauseRef) -> &ClauseHeader { let offset = cref.offset as usize; let header_pointer = self.buffer.as_ptr().add(offset) as *const ClauseHeader; &*header_pointer } /// Mutate the header of a clause without bound checks. pub unsafe fn header_unchecked_mut(&mut self, cref: ClauseRef) -> &mut ClauseHeader { let offset = cref.offset as usize; let header_pointer = self.buffer.as_mut_ptr().add(offset) as *mut ClauseHeader; &mut *header_pointer } /// Access a clause. pub fn clause(&self, cref: ClauseRef) -> &Clause { let header = self.header(cref); let len = header.len(); // Even on 32 bit systems these additions can't overflow as we never create clause refs with // an offset larger than ClauseRef::max_offset() let lit_offset = cref.offset as usize + HEADER_LEN; let lit_end = lit_offset + len; assert!(lit_end <= self.buffer.len(), "ClauseRef out of bounds"); unsafe { self.clause_with_len_unchecked(cref, len) } } /// Mutate a clause. pub fn clause_mut(&mut self, cref: ClauseRef) -> &mut Clause { let header = self.header(cref); let len = header.len(); // Even on 32 bit systems these additions can't overflow as we never create clause refs with // an offset larger than ClauseRef::max_offset() let lit_offset = cref.offset as usize + HEADER_LEN; let lit_end = lit_offset + len; assert!(lit_end <= self.buffer.len(), "ClauseRef out of bounds"); unsafe { self.clause_with_len_unchecked_mut(cref, len) } } /// Mutate the literals of a clause without bound checks. pub unsafe fn lits_ptr_mut_unchecked(&mut self, cref: ClauseRef) -> *mut Lit { let offset = cref.offset as usize; self.buffer.as_ptr().add(offset + HEADER_LEN) as *mut Lit } /// Perform a manual bound check on a ClauseRef assuming a given clause length. pub fn check_bounds(&self, cref: ClauseRef, len: usize) { // Even on 32 bit systems these additions can't overflow as we never create clause refs with // an offset larger than ClauseRef::max_offset() let lit_offset = cref.offset as usize + HEADER_LEN; let lit_end = lit_offset + len; assert!(lit_end <= self.buffer.len(), "ClauseRef out of bounds"); } unsafe fn clause_with_len_unchecked(&self, cref: ClauseRef, len: usize) -> &Clause { let offset = cref.offset as usize; #[allow(clippy::transmute_ptr_to_ptr)] transmute::<&[LitIdx], &Clause>(slice::from_raw_parts( self.buffer.as_ptr().add(offset), len + HEADER_LEN, )) } unsafe fn clause_with_len_unchecked_mut(&mut self, cref: ClauseRef, len: usize) -> &mut Clause { let offset = cref.offset as usize; #[allow(clippy::transmute_ptr_to_ptr)] transmute::<&mut [LitIdx], &mut Clause>(slice::from_raw_parts_mut( self.buffer.as_mut_ptr().add(offset), len + HEADER_LEN, )) } /// Current buffer size in multiples of [`LitIdx`]. pub fn buffer_size(&self) -> usize { self.buffer.len() } } /// Compact reference to a clause. /// /// Used with [`ClauseAlloc`] to access the clause. #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)] pub struct ClauseRef { offset: ClauseOffset, } impl ClauseRef { /// The largest offset supported by the ClauseAlloc const fn max_offset() -> ClauseOffset { // Make sure we can savely add a length to an offset without overflowing usize ((usize::max_value() >> 1) & (ClauseOffset::max_value() as usize)) as ClauseOffset } } #[cfg(test)] mod tests { use super::*; use varisat_formula::{cnf::strategy::*, CnfFormula, ExtendFormula}; use proptest::*; proptest! { #[test] fn roundtrip_from_cnf_formula(input in cnf_formula(1..100usize, 0..1000, 3..30)) { let mut clause_alloc = ClauseAlloc::new(); let mut clause_refs = vec![]; for clause_lits in input.iter() { let header = ClauseHeader::new(); clause_refs.push(clause_alloc.add_clause(header, clause_lits)); } let mut recovered = CnfFormula::new(); for cref in clause_refs { let clause = clause_alloc.clause(cref); prop_assert_eq!(clause.header().len(), clause.lits().len()); recovered.add_clause(clause.lits()); } // Ignore difference caused by unused vars recovered.set_var_count(input.var_count()); prop_assert_eq!(input, recovered); } #[test] fn clause_mutation(input in cnf_formula(1..100usize, 0..1000, 3..30)) { let mut clause_alloc = ClauseAlloc::new(); let mut clause_refs = vec![]; for clause_lits in input.iter() { let header = ClauseHeader::new(); clause_refs.push(clause_alloc.add_clause(header, clause_lits)); } for &cref in clause_refs.iter() { let clause = clause_alloc.clause_mut(cref); clause.lits_mut().reverse(); } for &cref in clause_refs.iter() { let clause_len = clause_alloc.clause(cref).lits().len(); if clause_len > 3 { clause_alloc.header_mut(cref).set_len(clause_len - 1); } } for (&cref, lits) in clause_refs.iter().zip(input.iter()) { let expected = if lits.len() > 3 { lits[1..].iter().rev() } else { lits.iter().rev() }; prop_assert!(clause_alloc.clause(cref).lits().iter().eq(expected)); } } } }
fn main() { if_let_expressions(); while_loop(); for_loop(); let_statement(); function_parameters(); } /* The line if let Ok(age) = age introduces a new shadowed age variable that contains the value inside the Ok variant. This means we need to place the if age > 30 condition within that block: we can’t combine these two conditions into if let Ok(age) = age && age > 30. The shadowed age we want to compare to 30 isn’t valid until the new scope starts with the curly bracket. The downside of using if let expressions is that the compiler doesn’t check exhaustiveness, whereas with match expressions it does. If we omitted the last else block and therefore missed handling some cases, the compiler would not alert us to the possible logic bug. */ fn if_let_expressions() { let favorite_color: Option<&str> = None; let is_tuesday = false; let age: Result<u8, _> = "34".parse(); if let Some(color) = favorite_color { println!("if_let_expressions: Using your favorite color, {}, as the background", color); } else if is_tuesday { println!("if_let_expressions: Tuesday is green day!"); } else if let Ok(age) = age { if age > 30 { println!("if_let_expressions: Using purple as the background color"); } else { println!("if_let_expressions: Using orange as the background color"); } } else { println!("if_let_expressions: Using blue as the background color"); } } fn while_loop() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("while_loop: {}", top); } } fn for_loop() { let v = vec!['a', 'b', 'c']; for (index, value) in v.iter().enumerate() { println!("for_looop: {} is at index {}", value, index); } } fn let_statement() { let (x, y, z) = (1, 2, 3); println!("let_statemnt: x={}, y={}, z={}.", x, y, z); } fn print_coordinates(&(x, y): &(i32, i32)) { println!("Current location from function_parameters/print_coordinates: ({}, {})", x, y); } fn function_parameters() { let point = (3, 5); print_coordinates(&point); }
use proconio::{input, marker::Usize1}; fn solve(i: usize, g: &Vec<Vec<usize>>, y: &Vec<u64>, acc: u64, cover: &mut Vec<bool>) { // eprintln!("i = {}, y[i] = {}, acc = {}",i, y[i], acc); cover[i] = y[i].max(acc) >= 1; for &j in &g[i] { solve( j, g, y, y[i].max(acc.saturating_sub(1)), cover, ); } } fn main() { input! { n: usize, m: usize, p: [Usize1; n - 1], xy: [(Usize1, u64); m], }; let mut y = vec![0; n]; for (x, y_) in xy { y[x] = y[x].max(y_); } let mut g = vec![vec![]; n]; for i in 1..n { g[p[i - 1]].push(i); } let mut cover = vec![false; n]; solve(0, &g, &y, 0, &mut cover); let ans = cover.iter().filter(|&&f| f).count(); println!("{}", ans); }
use std::{ mem::MaybeUninit, sync::atomic::{ fence, AtomicPtr, Ordering::{Acquire, Relaxed, Release}, }, }; use crate::ebr::Ebr; /// A simple lock-free Treiber stack pub struct Stack<T: Send + 'static> { head: AtomicPtr<Node<T>>, ebr: Ebr<Box<Node<T>>>, } impl<T: Send + 'static> Default for Stack<T> { fn default() -> Stack<T> { Stack { head: Default::default(), ebr: Default::default(), } } } impl<T: Send + 'static> Drop for Stack<T> { fn drop(&mut self) { let mut curr = self.head.load(Acquire); while !curr.is_null() { unsafe { let node: Box<Node<T>> = Box::from_raw(curr); curr = (*curr).next.load(Acquire); drop(node); } } } } #[derive(Debug)] struct Node<T: Send + 'static> { item: MaybeUninit<T>, next: AtomicPtr<Node<T>>, } impl<T: Send + Sync + 'static> Stack<T> { /// Add an item to the stack pub fn push(&self, item: T) { let node_ptr = Box::into_raw(Box::new(Node { item: MaybeUninit::new(item), next: AtomicPtr::default(), })); let mut cur_head_ptr = self.head.load(Acquire); loop { unsafe { (*node_ptr).next.store(cur_head_ptr, Relaxed); } fence(Acquire); let result = self .head .compare_exchange(cur_head_ptr, node_ptr, Relaxed, Relaxed); match result { Ok(_) => return, Err(current) => cur_head_ptr = current, } } } /// Pop an item off of the stack. Note that this /// requires a mutable self reference, because it /// involves the use of epoch based reclamation to /// properly GC deallocated memory once complete. pub fn pop(&mut self) -> Option<T> { let mut guard = self.ebr.pin(); let mut cur_head_ptr = self.head.load(Acquire); loop { if cur_head_ptr.is_null() { return None; } let next = unsafe { (*cur_head_ptr).next.load(Acquire) }; let result = self .head .compare_exchange(cur_head_ptr, next, Release, Release); if let Err(current) = result { cur_head_ptr = current; } else { unsafe { let node: Box<Node<T>> = Box::from_raw(cur_head_ptr); let item = node.item.as_ptr().read(); guard.defer_drop(node); return Some(item); } } } } }
mod option; pub use option::*;
mod errors; mod qrcode; use crate::qrcode::route::route_qrcode; use actix_cors::Cors; use actix_web::*; use serde_derive::*; use std::env; #[derive(Clone, Deserialize)] pub struct Config { github_url: String, redis_url: String, redis_ttl: usize, } const DEFAULT_REDIS_TTL: usize = 2592000; const DEFAULT_GITHUB_URL: &str = "https://github.com/"; #[actix_rt::main] async fn main() -> std::io::Result<()> { env_logger::init(); let app_host = env::var("APP_HOST").expect("APP_HOST not set"); let app_port = env::var("APP_PORT").expect("APP_PORT not set"); let addr = format!("{}:{}", app_host, app_port); HttpServer::new(|| { let redis_url = env::var("REDIS_URL").expect("REDIS_URL not set"); let redis_ttl = match env::var("REDIS_TTL") { Ok(s) => usize::from_str_radix(s.as_str(), 10).unwrap(), Err(_) => DEFAULT_REDIS_TTL, }; let github_url = env::var("GITHUB_URL").unwrap_or(String::from(DEFAULT_GITHUB_URL)); let config = Config { redis_url, redis_ttl, github_url, }; App::new() .data(config) .wrap(Cors::new().send_wildcard().finish()) .configure(route_qrcode) }) .bind(addr)? .run() .await }
use avro_rs::types::Value; use rdkafka::client::ClientContext; use rdkafka::config::{ClientConfig, RDKafkaLogLevel}; use rdkafka::consumer::base_consumer::BaseConsumer; use rdkafka::consumer::{Consumer, ConsumerContext, Rebalance}; use rdkafka::message::BorrowedMessage; use rdkafka::Message; use schema_registry_converter::Decoder; // A context can be used to change the behavior of producers and consumers by adding callbacks // that will be executed by librdkafka. // This particular context sets up custom callbacks to log rebalancing events. pub struct CustomContext; impl ClientContext for CustomContext {} impl ConsumerContext for CustomContext { fn pre_rebalance(&self, rebalance: &Rebalance) { println!("Pre rebalance {:?}", rebalance); } fn post_rebalance(&self, rebalance: &Rebalance) { println!("Post rebalance {:?}", rebalance); } } #[derive(Debug)] pub struct DeserializedRecord<'a> { pub key: Value, pub value: Value, pub topic: &'a str, pub partition: i32, pub offset: i64, } type TestConsumer = BaseConsumer<CustomContext>; pub fn consume( brokers: &str, group_id: &str, registry: String, topics: &[&str], test: Box<dyn Fn(DeserializedRecord) -> ()>, ) { let mut decoder = Decoder::new(registry); let consumer = get_consumer(brokers, group_id, topics); for message in consumer.iter() { match message { Err(e) => { assert!(false, "Got error consuming message: {}", e); } Ok(m) => { let des_r = get_deserialized_record(&m, &mut decoder); test(des_r); return; } }; } } fn get_deserialized_record<'a>( m: &'a BorrowedMessage, decoder: &'a mut Decoder, ) -> DeserializedRecord<'a> { let key = match decoder.decode(m.key()) { Ok(v) => v, Err(e) => panic!("Error getting value: {}", e), }; let value = match decoder.decode(m.payload()) { Ok(v) => v, Err(e) => panic!("Error getting value: {}", e), }; DeserializedRecord { key, value, topic: m.topic(), partition: m.partition(), offset: m.offset(), } } fn get_consumer(brokers: &str, group_id: &str, topics: &[&str]) -> TestConsumer { let context = CustomContext; let consumer: TestConsumer = ClientConfig::new() .set("group.id", group_id) .set("bootstrap.servers", brokers) .set("enable.partition.eof", "false") .set("session.timeout.ms", "6000") .set("enable.auto.commit", "true") .set("statistics.interval.ms", "30000") .set("auto.offset.reset", "earliest") .set_log_level(RDKafkaLogLevel::Warning) .create_with_context(context) .expect("Consumer creation failed"); consumer .subscribe(&topics.to_vec()) .expect("Can't subscribe to specified topics"); consumer }
use ethcontract::prelude::*; use std::str::FromStr; use std::fmt::{Display, Formatter}; /// Trait for CLI arguments that represent an amount of some currency. pub trait Currency: FromStr { /// Get the underlying int type. fn as_inner(&self) -> U256; } /// For CLI arguments that take amount of ether. /// /// Supports parsing ether values in human-readable form, /// i.e. `1eth` or `100gwei` or others. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct Eth(U256); impl Eth { pub fn new(inner: U256) -> Self { Self(inner) } } impl Currency for Eth { fn as_inner(&self) -> U256 { self.0 } } impl FromStr for Eth { type Err = uint::FromStrRadixErr; fn from_str(s: &str) -> Result<Self, Self::Err> { let s = s.to_ascii_lowercase(); let (s, modifier) = if let Some(s) = s.strip_suffix("ether") { (s, U256::exp10(18)) } else if let Some(s) = s.strip_suffix("eth") { (s, U256::exp10(18)) } else if let Some(s) = s.strip_suffix("pwei") { (s, U256::exp10(15)) } else if let Some(s) = s.strip_suffix("twei") { (s, U256::exp10(12)) } else if let Some(s) = s.strip_suffix("gwei") { (s, U256::exp10(9)) } else if let Some(s) = s.strip_suffix("mwei") { (s, U256::exp10(6)) } else if let Some(s) = s.strip_suffix("kwei") { (s, U256::exp10(3)) } else if let Some(s) = s.strip_suffix("wei") { (s, U256::exp10(0)) } else { (s.as_str(), U256::exp10(0)) }; if s.starts_with("0x") { Ok(Eth(U256::from_str_radix(s, 16)? * modifier)) } else { Ok(Eth(U256::from_str_radix(s, 10)? * modifier)) } } } impl Display for Eth { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let (eth, wei) = self.0.div_mod(U256::exp10(18)); f.write_fmt(format_args!("{}.{:0>18}eth", eth, wei.as_u64())) } } #[cfg(test)] mod test_eth { use super::*; #[test] fn eth_from_str() -> Result<(), Box<dyn std::error::Error>> { assert_eq!(Eth::from_str("0")?.0, U256::from(0)); assert_eq!(Eth::from_str("1")?.0, U256::from_dec_str("1")?); assert_eq!(Eth::from_str("15")?.0, U256::from_dec_str("15")?); assert_eq!(Eth::from_str("0x1")?.0, U256::from_dec_str("1")?); assert_eq!(Eth::from_str("0x15")?.0, U256::from_dec_str("21")?); assert_eq!(Eth::from_str("5wei")?.0, U256::from_dec_str("5")?); assert_eq!(Eth::from_str("5kwei")?.0, U256::from_dec_str("5000")?); assert_eq!(Eth::from_str("5mwei")?.0, U256::from_dec_str("5000000")?); assert_eq!(Eth::from_str("5gwei")?.0, U256::from_dec_str("5000000000")?); assert_eq!(Eth::from_str("5twei")?.0, U256::from_dec_str("5000000000000")?); assert_eq!(Eth::from_str("5pwei")?.0, U256::from_dec_str("5000000000000000")?); assert_eq!(Eth::from_str("5eth")?.0, U256::from_dec_str("5000000000000000000")?); assert_eq!(Eth::from_str("5ether")?.0, U256::from_dec_str("5000000000000000000")?); Ok(()) } #[test] fn eth_to_str() -> Result<(), Box<dyn std::error::Error>> { assert_eq!(Eth::from_str("10eth")?.to_string(), "10.000000000000000000eth"); assert_eq!(Eth::from_str("1500pwei")?.to_string(), "1.500000000000000000eth"); Ok(()) } } /// For CLI arguments that take amount of SCM tokens. /// /// Supports parsing ether values in human-readable form, /// i.e. `1scm` or `100asc` or others. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct Scm(U256); impl Scm { pub fn new(inner: U256) -> Self { Self(inner) } } impl Currency for Scm { fn as_inner(&self) -> U256 { self.0 } } impl FromStr for Scm { type Err = uint::FromStrRadixErr; fn from_str(s: &str) -> Result<Self, Self::Err> { let s = s.to_ascii_lowercase(); let (s, modifier) = if let Some(s) = s.strip_suffix("scam") { (s, U256::exp10(18)) } else if let Some(s) = s.strip_suffix("scm") { (s, U256::exp10(18)) } else if let Some(s) = s.strip_suffix("msc") { (s, U256::exp10(15)) } else if let Some(s) = s.strip_suffix("usc") { (s, U256::exp10(12)) } else if let Some(s) = s.strip_suffix("nsc") { (s, U256::exp10(9)) } else if let Some(s) = s.strip_suffix("psc") { (s, U256::exp10(6)) } else if let Some(s) = s.strip_suffix("fsc") { (s, U256::exp10(3)) } else if let Some(s) = s.strip_suffix("asc") { (s, U256::exp10(0)) } else { (s.as_str(), U256::exp10(0)) }; if s.starts_with("0x") { Ok(Scm(U256::from_str_radix(s, 16)? * modifier)) } else { Ok(Scm(U256::from_str_radix(s, 10)? * modifier)) } } } impl Display for Scm { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let (eth, wei) = self.0.div_mod(U256::exp10(18)); f.write_fmt(format_args!("{}.{:0>18}scm", eth, wei.as_u64())) } } #[cfg(test)] mod test_scm { use super::*; #[test] fn eth_from_str() -> Result<(), Box<dyn std::error::Error>> { assert_eq!(Scm::from_str("0")?.0, U256::from(0)); assert_eq!(Scm::from_str("1")?.0, U256::from_dec_str("1")?); assert_eq!(Scm::from_str("15")?.0, U256::from_dec_str("15")?); assert_eq!(Scm::from_str("0x1")?.0, U256::from_dec_str("1")?); assert_eq!(Scm::from_str("0x15")?.0, U256::from_dec_str("21")?); assert_eq!(Scm::from_str("5asc")?.0, U256::from_dec_str("5")?); assert_eq!(Scm::from_str("5fsc")?.0, U256::from_dec_str("5000")?); assert_eq!(Scm::from_str("5psc")?.0, U256::from_dec_str("5000000")?); assert_eq!(Scm::from_str("5nsc")?.0, U256::from_dec_str("5000000000")?); assert_eq!(Scm::from_str("5usc")?.0, U256::from_dec_str("5000000000000")?); assert_eq!(Scm::from_str("5msc")?.0, U256::from_dec_str("5000000000000000")?); assert_eq!(Scm::from_str("5scm")?.0, U256::from_dec_str("5000000000000000000")?); assert_eq!(Scm::from_str("5scam")?.0, U256::from_dec_str("5000000000000000000")?); Ok(()) } #[test] fn scm_to_str() -> Result<(), Box<dyn std::error::Error>> { assert_eq!(Scm::from_str("10scm")?.to_string(), "10.000000000000000000scm"); assert_eq!(Scm::from_str("1500msc")?.to_string(), "1.500000000000000000scm"); Ok(()) } }
use futures::{Future, Stream, Poll, Async}; use futures::executor::{spawn, Spawn, Notify}; use std::time::{Duration, Instant}; use std::sync::{Arc, Mutex, Condvar}; use std::sync::atomic::{AtomicUsize, Ordering}; /// Wraps a future, providing an API to interact with it while off task. /// /// This wrapper is intended to use from the context of tests. The future is /// effectively wrapped by a task and this harness tracks received notifications /// as well as provides APIs to perform non-blocking polling as well blocking /// polling with or without timeout. #[derive(Debug)] pub struct Harness<T> { spawn: Spawn<T>, notify: Arc<ThreadNotify>, } /// Error produced by `TestHarness` operations with timeout. #[derive(Debug)] pub struct TimeoutError<T> { /// If `None`, represents a timeout error inner: Option<T>, } #[derive(Debug)] struct ThreadNotify { state: AtomicUsize, mutex: Mutex<()>, condvar: Condvar, } const IDLE: usize = 0; const NOTIFY: usize = 1; const SLEEP: usize = 2; impl<T> Harness<T> { /// Wraps `obj` in a test harness, enabling interacting with the future /// while not on a `Task`. pub fn new(obj: T) -> Self { Harness { spawn: spawn(obj), notify: Arc::new(ThreadNotify::new()), } } pub fn with<F, R>(&mut self, f: F) -> R where F: FnOnce(&mut Self) -> R, { f(self) } /// Returns `true` if the inner future has received a readiness notification /// since the last action has been performed. pub fn is_notified(&self) -> bool { self.notify.is_notified() } /// Returns a reference to the inner future. pub fn get_ref(&self) -> &T { self.spawn.get_ref() } /// Returns a mutable reference to the inner future. pub fn get_mut(&mut self) -> &mut T { self.spawn.get_mut() } /// Consumes `self`, returning the inner future. pub fn into_inner(self) -> T { self.spawn.into_inner() } } impl<F, T, E> Harness<::futures::future::PollFn<F>> where F: FnMut() -> Poll<T, E>, { /// Wraps the `poll_fn` in a harness. pub fn poll_fn(f: F) -> Self { Harness::new(::futures::future::poll_fn(f)) } } impl<T: Future> Harness<T> { /// Polls the inner future. /// /// This function returns immediately. If the inner future is not currently /// ready, `NotReady` is returned. Readiness notifications are tracked and /// can be queried using `is_notified`. pub fn poll(&mut self) -> Poll<T::Item, T::Error> { self.spawn.poll_future_notify(&self.notify, 0) } /// Waits for the internal future to complete, blocking this thread's /// execution until it does. pub fn wait(&mut self) -> Result<T::Item, T::Error> { self.notify.clear(); loop { match self.spawn.poll_future_notify(&self.notify, 0)? { Async::NotReady => self.notify.park(), Async::Ready(e) => return Ok(e), } } } /// Waits for the internal future to complete, blocking this thread's /// execution for at most `dur`. pub fn wait_timeout(&mut self, dur: Duration) -> Result<T::Item, TimeoutError<T::Error>> { let until = Instant::now() + dur; self.notify.clear(); loop { let res = self.spawn.poll_future_notify(&self.notify, 0) .map_err(TimeoutError::new); match res? { Async::NotReady => { let now = Instant::now(); if now >= until { return Err(TimeoutError::timeout()); } self.notify.park_timeout(Some(until - now)); } Async::Ready(e) => return Ok(e), } } } } impl<T: Stream> Harness<T> { /// Polls the inner future. /// /// This function returns immediately. If the inner future is not currently /// ready, `NotReady` is returned. Readiness notifications are tracked and /// can be queried using `is_notified`. pub fn poll_next(&mut self) -> Poll<Option<T::Item>, T::Error> { self.spawn.poll_stream_notify(&self.notify, 0) } } impl<T> TimeoutError<T> { fn new(inner: T) -> Self { TimeoutError { inner: Some(inner) } } fn timeout() -> Self { TimeoutError { inner: None } } pub fn is_timeout(&self) -> bool { self.inner.is_none() } /// Consumes `self`, returning the inner error. Returns `None` if `self` /// represents a timeout. pub fn into_inner(self) -> Option<T> { self.inner } } impl ThreadNotify { fn new() -> Self { ThreadNotify { state: AtomicUsize::new(IDLE), mutex: Mutex::new(()), condvar: Condvar::new(), } } /// Clears any previously received notify, avoiding potential spurrious /// notifications. This should only be called immediately before running the /// task. fn clear(&self) { self.state.store(IDLE, Ordering::SeqCst); } fn is_notified(&self) -> bool { match self.state.load(Ordering::SeqCst) { IDLE => false, NOTIFY => true, _ => unreachable!(), } } fn park(&self) { self.park_timeout(None); } fn park_timeout(&self, dur: Option<Duration>) { // If currently notified, then we skip sleeping. This is checked outside // of the lock to avoid acquiring a mutex if not necessary. match self.state.compare_and_swap(NOTIFY, IDLE, Ordering::SeqCst) { NOTIFY => return, IDLE => {}, _ => unreachable!(), } // The state is currently idle, so obtain the lock and then try to // transition to a sleeping state. let mut m = self.mutex.lock().unwrap(); // Transition to sleeping match self.state.compare_and_swap(IDLE, SLEEP, Ordering::SeqCst) { NOTIFY => { // Notified before we could sleep, consume the notification and // exit self.state.store(IDLE, Ordering::SeqCst); return; } IDLE => {}, _ => unreachable!(), } // Track (until, remaining) let mut time = dur.map(|dur| (Instant::now() + dur, dur)); loop { m = match time { Some((until, rem)) => { let (guard, _) = self.condvar.wait_timeout(m, rem).unwrap(); let now = Instant::now(); if now >= until { // Timed out... exit sleep state self.state.store(IDLE, Ordering::SeqCst); return; } time = Some((until, until - now)); guard } None => self.condvar.wait(m).unwrap(), }; // Transition back to idle, loop otherwise if NOTIFY == self.state.compare_and_swap(NOTIFY, IDLE, Ordering::SeqCst) { return; } } } } impl Notify for ThreadNotify { fn notify(&self, _unpark_id: usize) { // First, try transitioning from IDLE -> NOTIFY, this does not require a // lock. match self.state.compare_and_swap(IDLE, NOTIFY, Ordering::SeqCst) { IDLE | NOTIFY => return, SLEEP => {} _ => unreachable!(), } // The other half is sleeping, this requires a lock let _m = self.mutex.lock().unwrap(); // Transition from SLEEP -> NOTIFY match self.state.compare_and_swap(SLEEP, NOTIFY, Ordering::SeqCst) { SLEEP => {} _ => return, } // Wakeup the sleeper self.condvar.notify_one(); } }
/* * Copyright (c) 2016 Boucher, Antoni <bouanto@zoho.com> * * 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. */ #![allow(deprecated)] extern crate glib; #[macro_use] extern crate webkit2gtk_webextension; extern crate libc; use glib::closure::Closure; use glib::variant::Variant; use glib::Cast; use glib::Object; use webkit2gtk_webextension::{ DOMDocumentExt, DOMElementExt, DOMEventTargetExt, DOMMouseEvent, DOMMouseEventExt, WebExtension, WebExtensionExt, WebPage, WebPageExt, }; /*web_extension_init!(); pub fn web_extension_initialize(extension: &WebExtension) { extension.connect_page_created(|_, page| { page.connect_document_loaded(|page| { println!("Page {} created for {:?}", page.get_id(), page.get_uri()); let document = page.get_dom_document().unwrap(); println!("URL: {:?}", document.get_url()); println!("Title: {:?}", document.get_title()); document.set_title("My Web Page"); let handler = Closure::new(|values| { if let Some(event) = values[1].get::<Object>() { if let Ok(mouse_event) = event.downcast::<DOMMouseEvent>() { println!("Click at ({}, {})", mouse_event.get_x(), mouse_event.get_y()); } } None }); document.add_event_listener_with_closure("click", &handler, false); println!("{}%", scroll_percentage(page)); scroll_by(page, 45); println!("{}%", scroll_percentage(page)); scroll_bottom(page); println!("{}%", scroll_percentage(page)); scroll_top(page); println!("{}%", scroll_percentage(page)); }); }); }*/ web_extension_init_with_data!(); pub fn web_extension_initialize(extension: &WebExtension, user_data: Option<&Variant>) { let user_string: Option<String> = user_data.and_then(Variant::get_str).map(ToOwned::to_owned); dbg!(user_string); extension.connect_page_created(|_, page| { page.connect_document_loaded(|page| { println!("Page {} created for {:?}", page.get_id(), page.get_uri()); let document = page.get_dom_document().unwrap(); println!("URL: {:?}", document.get_url()); println!("Title: {:?}", document.get_title()); document.set_title("My Web Page"); let handler = Closure::new(|values| { if let Some(event) = values[1].get::<Object>() { if let Ok(mouse_event) = event.downcast::<DOMMouseEvent>() { println!( "Click at ({}, {})", mouse_event.get_x(), mouse_event.get_y() ); } } None }); document.add_event_listener_with_closure("click", &handler, false); println!("{}%", scroll_percentage(page)); scroll_by(page, 45); println!("{}%", scroll_percentage(page)); scroll_bottom(page); println!("{}%", scroll_percentage(page)); scroll_top(page); println!("{}%", scroll_percentage(page)); }); }); } fn scroll_by(page: &WebPage, pixels: i64) { let document = page.get_dom_document().unwrap(); let body = document.get_body().unwrap(); body.set_scroll_top(body.get_scroll_top() + pixels as libc::c_long); } fn scroll_bottom(page: &WebPage) { let document = page.get_dom_document().unwrap(); let body = document.get_body().unwrap(); body.set_scroll_top(body.get_scroll_height()); } fn scroll_percentage(page: &WebPage) -> i64 { let document = page.get_dom_document().unwrap(); let body = document.get_body().unwrap(); let document = document.get_document_element().unwrap(); let height = document.get_client_height(); (body.get_scroll_top() as f64 / (body.get_scroll_height() as f64 - height) * 100.0) as i64 } fn scroll_top(page: &WebPage) { let document = page.get_dom_document().unwrap(); let body = document.get_body().unwrap(); body.set_scroll_top(0); }
use crate::{Call, Error, Trait}; use frame_support::debug; use frame_system::offchain::{SendSignedTransaction, Signer}; pub fn send_signed<T: Trait>( signer: Signer<T, T::AuthorityId>, call: Call<T>, ) -> Result<(), Error<T>> { // `result` is in the type of `Option<(Account<T>, Result<(), ()>)>`. It is: // - `None`: no account is available for sending transaction // - `Some((account, Ok(())))`: transaction is successfully sent // - `Some((account, Err(())))`: error occured when sending the transaction let result = signer.send_signed_transaction(|_acct| call.clone()); // display error if the signed tx fails. if let Some((acc, res)) = result { if res.is_err() { debug::error!("failure: offchain_signed_tx: tx sent: {:?}", acc.id); return Err(<Error<T>>::OffchainSignedTxError); } // Transaction is sent successfully return Ok(()); } // The case of `None`: no account is available for sending debug::error!("No local account available"); Err(<Error<T>>::NoLocalAcctForSigning) }
use input_i_scanner::{scan_with, InputIScanner}; use join::Join; use std::cmp::Reverse; use std::collections::BinaryHeap; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); let (n, m) = scan_with!(_i_i, (usize, usize)); let mut g = vec![vec![]; n]; for _ in 0..m { let (a, b) = scan_with!(_i_i, (usize, usize)); g[a - 1].push(b - 1); } let mut deg = vec![0; n]; for u in 0..n { for &v in &g[u] { deg[v] += 1; } } let mut heap = BinaryHeap::new(); let mut seen = vec![false; n]; let mut perm = Vec::new(); for v in 0..n { if deg[v] == 0 { heap.push(Reverse(v)); } } while let Some(Reverse(u)) = heap.pop() { if seen[u] { continue; } seen[u] = true; perm.push(u); for &v in &g[u] { if seen[v] { continue; } deg[v] -= 1; if deg[v] == 0 { heap.push(Reverse(v)); } } } if perm.len() == n { println!("{}", perm.iter().map(|x| x + 1).join(" ")); } else { println!("-1"); } }
// 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 crate::{ channel::ChannelConfigs, inspect::{AppsNode, StateNode}, }; use failure::{bail, Error, ResultExt}; use fidl_fuchsia_update::{ CheckStartedResult, Initiator, ManagerRequest, ManagerRequestStream, ManagerState, MonitorControlHandle, State, }; use fidl_fuchsia_update_channelcontrol::{ChannelControlRequest, ChannelControlRequestStream}; use fuchsia_async as fasync; use fuchsia_component::server::{ServiceFs, ServiceObjLocal}; use futures::{lock::Mutex, prelude::*}; use log::{error, info, warn}; use omaha_client::{ common::{AppSet, CheckOptions}, http_request::HttpRequest, installer::Installer, metrics::MetricsReporter, policy::PolicyEngine, protocol::request::InstallSource, state_machine::{self, StateMachine, Timer}, storage::Storage, }; use std::cell::RefCell; use std::rc::Rc; use sysconfig_client::{channel::OtaUpdateChannelConfig, SysconfigPartition}; #[cfg(not(test))] use sysconfig_client::channel::write_channel_config; #[cfg(test)] fn write_channel_config(config: &OtaUpdateChannelConfig) -> Result<(), Error> { assert_eq!(config.channel_name(), "target-channel"); assert_eq!(config.tuf_config_name(), "target-channel-repo"); Ok(()) } #[cfg(not(test))] use sysconfig_client::write_partition; #[cfg(test)] fn write_partition(partition: SysconfigPartition, data: &[u8]) -> Result<(), Error> { assert_eq!(partition, SysconfigPartition::Config); assert_eq!(data, &[] as &[u8]); Ok(()) } pub struct FidlServer<PE, HR, IN, TM, MR, ST> where PE: PolicyEngine, HR: HttpRequest, IN: Installer, TM: Timer, MR: MetricsReporter, ST: Storage, { state_machine_ref: Rc<RefCell<StateMachine<PE, HR, IN, TM, MR, ST>>>, storage_ref: Rc<Mutex<ST>>, app_set: AppSet, apps_node: AppsNode, state_node: StateNode, channel_configs: Option<ChannelConfigs>, // The current State table, defined in fuchsia.update.fidl. state: State, /// The monitor handles for monitoring all updates. monitor_handles: Vec<MonitorControlHandle>, /// The monitor handles for monitoring the current update only, will be cleared after each /// update. current_monitor_handles: Vec<MonitorControlHandle>, } pub enum IncomingServices { Manager(ManagerRequestStream), ChannelControl(ChannelControlRequestStream), } impl<PE, HR, IN, TM, MR, ST> FidlServer<PE, HR, IN, TM, MR, ST> where PE: PolicyEngine + 'static, HR: HttpRequest + 'static, IN: Installer + 'static, TM: Timer + 'static, MR: MetricsReporter + 'static, ST: Storage + 'static, { pub fn new( state_machine_ref: Rc<RefCell<StateMachine<PE, HR, IN, TM, MR, ST>>>, storage_ref: Rc<Mutex<ST>>, app_set: AppSet, apps_node: AppsNode, state_node: StateNode, channel_configs: Option<ChannelConfigs>, ) -> Self { let state = State { state: Some(ManagerState::Idle), version_available: None }; state_node.set(&state); FidlServer { state_machine_ref, storage_ref, app_set, apps_node, state_node, channel_configs, state, monitor_handles: vec![], current_monitor_handles: vec![], } } /// Starts the FIDL Server and the StateMachine. pub async fn start(self, mut fs: ServiceFs<ServiceObjLocal<'_, IncomingServices>>) { fs.dir("svc") .add_fidl_service(IncomingServices::Manager) .add_fidl_service(IncomingServices::ChannelControl); const MAX_CONCURRENT: usize = 1000; let server = Rc::new(RefCell::new(self)); // Handle each client connection concurrently. let fs_fut = fs.for_each_concurrent(MAX_CONCURRENT, |stream| { Self::handle_client(server.clone(), stream).unwrap_or_else(|e| error!("{:?}", e)) }); Self::setup_state_callback(server.clone()); fs_fut.await; } /// Setup the state callback from state machine. fn setup_state_callback(server: Rc<RefCell<Self>>) { let state_machine_ref = server.borrow().state_machine_ref.clone(); let mut state_machine = state_machine_ref.borrow_mut(); state_machine.set_state_callback(move |state| { let server = server.clone(); async move { let mut server = server.borrow_mut(); server.on_state_change(state).await; } .boxed_local() }); } /// Handle an incoming FIDL connection from a client. async fn handle_client( server: Rc<RefCell<Self>>, stream: IncomingServices, ) -> Result<(), Error> { match stream { IncomingServices::Manager(mut stream) => { while let Some(request) = stream.try_next().await.context("error receiving Manager request")? { Self::handle_manager_request(server.clone(), request)?; } } IncomingServices::ChannelControl(mut stream) => { while let Some(request) = stream.try_next().await.context("error receiving ChannelControl request")? { Self::handle_channel_control_request(server.clone(), request).await?; } } } Ok(()) } /// Handle fuchsia.update.Manager requests. fn handle_manager_request( server: Rc<RefCell<Self>>, request: ManagerRequest, ) -> Result<(), Error> { let mut server = server.borrow_mut(); match request { ManagerRequest::CheckNow { options, monitor, responder } => { info!("Received CheckNow request with {:?} and {:?}", options, monitor); // Attach the monitor if passed for current update. if let Some(monitor) = monitor { let (_stream, handle) = monitor.into_stream_and_control_handle()?; handle.send_on_state(clone(&server.state))?; server.current_monitor_handles.push(handle); } match server.state.state { Some(ManagerState::Idle) => { let options = CheckOptions { source: match options.initiator { Some(Initiator::User) => InstallSource::OnDemand, Some(Initiator::Service) => InstallSource::ScheduledTask, None => bail!("Options.Initiator is required"), }, }; let state_machine_ref = server.state_machine_ref.clone(); // Drop the borrowed server before starting update check because the state // callback also need to borrow the server. drop(server); // TODO: Detect and return CheckStartedResult::Throttled. fasync::spawn_local(async move { let mut state_machine = state_machine_ref.borrow_mut(); state_machine.start_update_check(options).await; }); responder .send(CheckStartedResult::Started) .context("error sending response")?; } _ => { responder .send(CheckStartedResult::InProgress) .context("error sending response")?; } } } ManagerRequest::GetState { responder } => { info!("Received GetState request"); responder.send(clone(&server.state)).context("error sending response")?; } ManagerRequest::AddMonitor { monitor, control_handle: _ } => { info!("Received AddMonitor request with {:?}", monitor); let (_stream, handle) = monitor.into_stream_and_control_handle()?; handle.send_on_state(clone(&server.state))?; server.monitor_handles.push(handle); } } Ok(()) } /// Handle fuchsia.update.channelcontrol.ChannelControl requests. async fn handle_channel_control_request( server: Rc<RefCell<Self>>, request: ChannelControlRequest, ) -> Result<(), Error> { let server = server.borrow(); match request { ChannelControlRequest::SetTarget { channel, responder } => { info!("Received SetTarget request with {}", channel); // TODO: Verify that channel is valid. if channel.is_empty() { // TODO: Remove this when fxb/36608 is fixed. warn!( "Empty channel passed to SetTarget, erasing all channel data in SysConfig." ); write_partition(SysconfigPartition::Config, &[])?; let target_channel = match &server.channel_configs { Some(channel_configs) => channel_configs.default_channel.clone(), None => None, }; server.app_set.set_target_channel(target_channel).await; } else { let tuf_repo = if let Some(channel_configs) = &server.channel_configs { if let Some(channel_config) = channel_configs .known_channels .iter() .find(|channel_config| channel_config.name == channel) { &channel_config.repo } else { error!( "Channel {} not found in known channels, using channel name as \ TUF repo name.", &channel ); &channel } } else { warn!("No channel configs found, using channel name as TUF repo name."); &channel }; let config = OtaUpdateChannelConfig::new(&channel, tuf_repo)?; write_channel_config(&config)?; let mut storage = server.storage_ref.lock().await; server.app_set.set_target_channel(Some(channel)).await; server.app_set.persist(&mut *storage).await; if let Err(e) = storage.commit().await { error!("Unable to commit target channel change: {}", e); } } server.apps_node.set(&server.app_set.to_vec().await); responder.send().context("error sending response")?; } ChannelControlRequest::GetTarget { responder } => { let channel = server.app_set.get_target_channel().await; responder.send(&channel).context("error sending response")?; } ChannelControlRequest::GetCurrent { responder } => { let channel = server.app_set.get_current_channel().await; responder.send(&channel).context("error sending response")?; } ChannelControlRequest::GetTargetList { responder } => { let channel_names: Vec<&str> = match &server.channel_configs { Some(channel_configs) => { channel_configs.known_channels.iter().map(|cfg| cfg.name.as_ref()).collect() } None => Vec::new(), }; responder .send(&mut channel_names.iter().copied()) .context("error sending channel list response")?; } } Ok(()) } /// The state change callback from StateMachine. async fn on_state_change(&mut self, state: state_machine::State) { self.state.state = Some(match state { state_machine::State::Idle => ManagerState::Idle, state_machine::State::CheckingForUpdates => ManagerState::CheckingForUpdates, state_machine::State::UpdateAvailable => ManagerState::UpdateAvailable, state_machine::State::PerformingUpdate => ManagerState::PerformingUpdate, state_machine::State::WaitingForReboot => ManagerState::WaitingForReboot, state_machine::State::FinalizingUpdate => ManagerState::FinalizingUpdate, state_machine::State::EncounteredError => ManagerState::EncounteredError, }); // Send the new state to all monitor handles and remove the handle if it fails. let state = clone(&self.state); let send_state_and_remove_failed = |handle: &MonitorControlHandle| match handle.send_on_state(clone(&state)) { Ok(()) => true, Err(e) => { error!( "Failed to send on_state callback to {:?}: {:?}, removing handle.", handle, e ); false } }; self.current_monitor_handles.retain(send_state_and_remove_failed); self.monitor_handles.retain(send_state_and_remove_failed); // State is back to idle, clear the current update monitor handles. if self.state.state == Some(ManagerState::Idle) { self.current_monitor_handles.clear(); } self.state_node.set(&self.state); // The state machine might make changes to apps only when state changes to `Idle` or // `WaitingForReboot`, update the apps node in inspect. if self.state.state == Some(ManagerState::Idle) || self.state.state == Some(ManagerState::WaitingForReboot) { self.apps_node.set(&self.app_set.to_vec().await); } } } /// Manually clone |State| because FIDL table doesn't derive clone. fn clone(state: &State) -> State { State { state: state.state.clone(), version_available: state.version_available.clone() } } #[cfg(test)] mod tests { use super::*; use crate::{channel::ChannelConfig, configuration}; use fidl::endpoints::{create_proxy, create_proxy_and_stream}; use fidl_fuchsia_update::{ManagerMarker, MonitorEvent, MonitorMarker, Options}; use fidl_fuchsia_update_channelcontrol::ChannelControlMarker; use fuchsia_inspect::{assert_inspect_tree, Inspector}; use omaha_client::{ common::App, http_request::StubHttpRequest, installer::stub::StubInstaller, metrics::StubMetricsReporter, policy::StubPolicyEngine, protocol::Cohort, state_machine::StubTimer, storage::MemStorage, }; type StubFidlServer = FidlServer< StubPolicyEngine, StubHttpRequest, StubInstaller, StubTimer, StubMetricsReporter, MemStorage, >; struct FidlServerBuilder { apps: Vec<App>, channel_configs: Option<ChannelConfigs>, apps_node: Option<AppsNode>, state_node: Option<StateNode>, } impl FidlServerBuilder { fn new() -> Self { Self { apps: Vec::new(), channel_configs: None, apps_node: None, state_node: None } } fn with_apps(mut self, mut apps: Vec<App>) -> Self { self.apps.append(&mut apps); self } fn with_apps_node(mut self, apps_node: AppsNode) -> Self { self.apps_node = Some(apps_node); self } fn with_state_node(mut self, state_node: StateNode) -> Self { self.state_node = Some(state_node); self } fn with_channel_configs(mut self, channel_configs: ChannelConfigs) -> Self { self.channel_configs = Some(channel_configs); self } async fn build(self) -> StubFidlServer { let config = configuration::get_config("0.1.2"); let storage_ref = Rc::new(Mutex::new(MemStorage::new())); let app_set = if self.apps.is_empty() { AppSet::new(vec![App::new("id", [1, 0], Cohort::default())]) } else { AppSet::new(self.apps) }; let state_machine = StateMachine::new( StubPolicyEngine, StubHttpRequest, StubInstaller::default(), &config, StubTimer, StubMetricsReporter, storage_ref.clone(), app_set.clone(), ) .await; let inspector = Inspector::new(); let root = inspector.root(); let apps_node = self.apps_node.unwrap_or(AppsNode::new(root.create_child("apps"))); let state_node = self.state_node.unwrap_or(StateNode::new(root.create_child("state"))); FidlServer::new( Rc::new(RefCell::new(state_machine)), storage_ref, app_set, apps_node, state_node, self.channel_configs, ) } } fn spawn_fidl_server<M: fidl::endpoints::ServiceMarker>( fidl: Rc<RefCell<StubFidlServer>>, service: fn(M::RequestStream) -> IncomingServices, ) -> M::Proxy { let (proxy, stream) = create_proxy_and_stream::<M>().unwrap(); fasync::spawn_local( FidlServer::handle_client(fidl, service(stream)).unwrap_or_else(|e| panic!(e)), ); proxy } #[fasync::run_singlethreaded(test)] async fn test_on_state_change() { let mut fidl = FidlServerBuilder::new().build().await; fidl.on_state_change(state_machine::State::CheckingForUpdates).await; assert_eq!(Some(ManagerState::CheckingForUpdates), fidl.state.state); } #[fasync::run_singlethreaded(test)] async fn test_get_state() { let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().build().await)); let proxy = spawn_fidl_server::<ManagerMarker>(fidl.clone(), IncomingServices::Manager); let state = proxy.get_state().await.unwrap(); let fidl = fidl.borrow(); assert_eq!(state, fidl.state); } #[fasync::run_singlethreaded(test)] async fn test_monitor() { let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().build().await)); let proxy = spawn_fidl_server::<ManagerMarker>(fidl.clone(), IncomingServices::Manager); let (client_proxy, server_end) = create_proxy::<MonitorMarker>().unwrap(); proxy.add_monitor(server_end).unwrap(); let mut stream = client_proxy.take_event_stream(); let event = stream.next().await.unwrap().unwrap(); let fidl = fidl.borrow(); match event { MonitorEvent::OnState { state } => { assert_eq!(state, fidl.state); } } assert_eq!(fidl.monitor_handles.len(), 1); } #[fasync::run_singlethreaded(test)] async fn test_check_now() { let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().build().await)); let proxy = spawn_fidl_server::<ManagerMarker>(fidl, IncomingServices::Manager); let options = Options { initiator: Some(Initiator::User) }; let result = proxy.check_now(options, None).await.unwrap(); assert_eq!(result, CheckStartedResult::Started); } #[fasync::run_singlethreaded(test)] async fn test_check_now_with_monitor() { let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().build().await)); FidlServer::setup_state_callback(fidl.clone()); let proxy = spawn_fidl_server::<ManagerMarker>(fidl.clone(), IncomingServices::Manager); let (client_proxy, server_end) = create_proxy::<MonitorMarker>().unwrap(); let options = Options { initiator: Some(Initiator::User) }; let result = proxy.check_now(options, Some(server_end)).await.unwrap(); assert_eq!(result, CheckStartedResult::Started); let mut expected_states = [ State { state: Some(ManagerState::Idle), version_available: None }, State { state: Some(ManagerState::CheckingForUpdates), version_available: None }, State { state: Some(ManagerState::EncounteredError), version_available: None }, State { state: Some(ManagerState::Idle), version_available: None }, ] .iter(); let mut stream = client_proxy.take_event_stream(); while let Some(event) = stream.try_next().await.unwrap() { match event { MonitorEvent::OnState { state } => { assert_eq!(Some(&state), expected_states.next()); } } } assert_eq!(None, expected_states.next()); assert!(fidl.borrow().current_monitor_handles.is_empty()); } #[fasync::run_singlethreaded(test)] async fn test_get_channel() { let apps = vec![App::new( "id", [1, 0], Cohort { name: Some("current-channel".to_string()), ..Cohort::default() }, )]; let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().with_apps(apps).build().await)); let proxy = spawn_fidl_server::<ChannelControlMarker>(fidl, IncomingServices::ChannelControl); assert_eq!("current-channel", proxy.get_current().await.unwrap()); } #[fasync::run_singlethreaded(test)] async fn test_get_target() { let apps = vec![App::new("id", [1, 0], Cohort::from_hint("target-channel"))]; let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().with_apps(apps).build().await)); let proxy = spawn_fidl_server::<ChannelControlMarker>(fidl, IncomingServices::ChannelControl); assert_eq!("target-channel", proxy.get_target().await.unwrap()); } #[fasync::run_singlethreaded(test)] async fn test_set_target() { let fidl = Rc::new(RefCell::new( FidlServerBuilder::new() .with_channel_configs(ChannelConfigs { default_channel: None, known_channels: vec![ ChannelConfig::new("some-channel"), ChannelConfig::new("target-channel"), ], }) .build() .await, )); let proxy = spawn_fidl_server::<ChannelControlMarker>( fidl.clone(), IncomingServices::ChannelControl, ); proxy.set_target("target-channel").await.unwrap(); let fidl = fidl.borrow(); let apps = fidl.app_set.to_vec().await; assert_eq!("target-channel", apps[0].get_target_channel()); let storage = fidl.storage_ref.lock().await; storage.get_string(&apps[0].id).await.unwrap(); assert!(storage.committed()); } #[fasync::run_singlethreaded(test)] async fn test_set_target_empty() { let fidl = Rc::new(RefCell::new( FidlServerBuilder::new() .with_channel_configs(ChannelConfigs { default_channel: Some("default-channel".to_string()), known_channels: vec![], }) .build() .await, )); let proxy = spawn_fidl_server::<ChannelControlMarker>( fidl.clone(), IncomingServices::ChannelControl, ); proxy.set_target("").await.unwrap(); let fidl = fidl.borrow(); let apps = fidl.app_set.to_vec().await; assert_eq!("default-channel", apps[0].get_target_channel()); let storage = fidl.storage_ref.lock().await; // Default channel should not be persisted to storage. assert_eq!(None, storage.get_string(&apps[0].id).await); } #[fasync::run_singlethreaded(test)] async fn test_get_target_list() { let fidl = Rc::new(RefCell::new( FidlServerBuilder::new() .with_channel_configs(ChannelConfigs { default_channel: None, known_channels: vec![ ChannelConfig::new("some-channel"), ChannelConfig::new("some-other-channel"), ], }) .build() .await, )); let proxy = spawn_fidl_server::<ChannelControlMarker>(fidl, IncomingServices::ChannelControl); let response = proxy.get_target_list().await.unwrap(); assert_eq!(2, response.len()); assert!(response.contains(&"some-channel".to_string())); assert!(response.contains(&"some-other-channel".to_string())); } #[fasync::run_singlethreaded(test)] async fn test_get_target_list_when_no_channels_configured() { let fidl = Rc::new(RefCell::new(FidlServerBuilder::new().build().await)); let proxy = spawn_fidl_server::<ChannelControlMarker>(fidl, IncomingServices::ChannelControl); let response = proxy.get_target_list().await.unwrap(); assert!(response.is_empty()); } #[fasync::run_singlethreaded(test)] async fn test_inspect_apps_on_state_change() { let inspector = Inspector::new(); let apps_node = AppsNode::new(inspector.root().create_child("apps")); let mut fidl = FidlServerBuilder::new().with_apps_node(apps_node).build().await; fidl.on_state_change(state_machine::State::Idle).await; assert_inspect_tree!( inspector, root: { apps: { apps: format!("{:?}", fidl.app_set.to_vec().await), } } ); } #[fasync::run_singlethreaded(test)] async fn test_inspect_apps_on_channel_change() { let inspector = Inspector::new(); let apps_node = AppsNode::new(inspector.root().create_child("apps")); let fidl = Rc::new(RefCell::new( FidlServerBuilder::new() .with_apps_node(apps_node) .with_channel_configs(ChannelConfigs { default_channel: None, known_channels: vec![ChannelConfig::new("target-channel")], }) .build() .await, )); let proxy = spawn_fidl_server::<ChannelControlMarker>( fidl.clone(), IncomingServices::ChannelControl, ); proxy.set_target("target-channel").await.unwrap(); let fidl = fidl.borrow(); assert_inspect_tree!( inspector, root: { apps: { apps: format!("{:?}", fidl.app_set.to_vec().await), } } ); } #[fasync::run_singlethreaded(test)] async fn test_inspect_state() { let inspector = Inspector::new(); let state_node = StateNode::new(inspector.root().create_child("state")); let mut fidl = FidlServerBuilder::new().with_state_node(state_node).build().await; assert_inspect_tree!( inspector, root: { state: { state: format!("{:?}", fidl.state), } } ); fidl.on_state_change(state_machine::State::PerformingUpdate).await; assert_inspect_tree!( inspector, root: { state: { state: format!("{:?}", fidl.state), } } ); } }
// compile-flags: -Zalways-encode-mir static S: usize = 42; pub fn f() -> &'static usize { &S }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct APPLICATION_EVENT_DATA { pub cbApplicationEventData: u32, pub ApplicationId: ::windows::core::GUID, pub EndpointId: ::windows::core::GUID, pub dwEventId: u32, pub cbEventData: u32, pub bEventData: [u8; 1], } impl APPLICATION_EVENT_DATA {} impl ::core::default::Default for APPLICATION_EVENT_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for APPLICATION_EVENT_DATA { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for APPLICATION_EVENT_DATA {} unsafe impl ::windows::core::Abi for APPLICATION_EVENT_DATA { type Abi = Self; } pub const CONTENT_ID_GLANCE: u32 = 0u32; pub const CONTENT_ID_HOME: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct CONTENT_MISSING_EVENT_DATA { pub cbContentMissingEventData: u32, pub ApplicationId: ::windows::core::GUID, pub EndpointId: ::windows::core::GUID, pub ContentId: u32, } impl CONTENT_MISSING_EVENT_DATA {} impl ::core::default::Default for CONTENT_MISSING_EVENT_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for CONTENT_MISSING_EVENT_DATA { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for CONTENT_MISSING_EVENT_DATA {} unsafe impl ::windows::core::Abi for CONTENT_MISSING_EVENT_DATA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct DEVICE_USER_CHANGE_EVENT_DATA { pub cbDeviceUserChangeEventData: u32, pub wszUser: u16, } impl DEVICE_USER_CHANGE_EVENT_DATA {} impl ::core::default::Default for DEVICE_USER_CHANGE_EVENT_DATA { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for DEVICE_USER_CHANGE_EVENT_DATA { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for DEVICE_USER_CHANGE_EVENT_DATA {} unsafe impl ::windows::core::Abi for DEVICE_USER_CHANGE_EVENT_DATA { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct EVENT_DATA_HEADER { pub cbEventDataHeader: u32, pub guidEventType: ::windows::core::GUID, pub dwVersion: u32, pub cbEventDataSid: u32, } impl EVENT_DATA_HEADER {} impl ::core::default::Default for EVENT_DATA_HEADER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for EVENT_DATA_HEADER { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for EVENT_DATA_HEADER {} unsafe impl ::windows::core::Abi for EVENT_DATA_HEADER { type Abi = Self; } pub const GUID_DEVINTERFACE_SIDESHOW: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x152e5811_feb9_4b00_90f4_d32947ae1681); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowBulkCapabilities(pub ::windows::core::IUnknown); impl ISideShowBulkCapabilities { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe fn GetCapability(&self, in_keycapability: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, inout_pvalue: *mut super::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_keycapability), ::core::mem::transmute(inout_pvalue)).ok() } pub unsafe fn GetCapabilities<'a, Param0: ::windows::core::IntoParam<'a, ISideShowKeyCollection>>(&self, in_keycollection: Param0, inout_pvalues: *mut ::core::option::Option<ISideShowPropVariantCollection>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), in_keycollection.into_param().abi(), ::core::mem::transmute(inout_pvalues)).ok() } } unsafe impl ::windows::core::Interface for ISideShowBulkCapabilities { type Vtable = ISideShowBulkCapabilities_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3a2b7fbc_3ad5_48bd_bbf1_0e6cfbd10807); } impl ::core::convert::From<ISideShowBulkCapabilities> for ::windows::core::IUnknown { fn from(value: ISideShowBulkCapabilities) -> Self { value.0 } } impl ::core::convert::From<&ISideShowBulkCapabilities> for ::windows::core::IUnknown { fn from(value: &ISideShowBulkCapabilities) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowBulkCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowBulkCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ISideShowBulkCapabilities> for ISideShowCapabilities { fn from(value: ISideShowBulkCapabilities) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ISideShowBulkCapabilities> for ISideShowCapabilities { fn from(value: &ISideShowBulkCapabilities) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, ISideShowCapabilities> for ISideShowBulkCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ISideShowCapabilities> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, ISideShowCapabilities> for &ISideShowBulkCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ISideShowCapabilities> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowBulkCapabilities_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, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_keycapability: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, inout_pvalue: *mut ::core::mem::ManuallyDrop<super::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_keycollection: ::windows::core::RawPtr, inout_pvalues: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowCapabilities(pub ::windows::core::IUnknown); impl ISideShowCapabilities { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe fn GetCapability(&self, in_keycapability: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, inout_pvalue: *mut super::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_keycapability), ::core::mem::transmute(inout_pvalue)).ok() } } unsafe impl ::windows::core::Interface for ISideShowCapabilities { type Vtable = ISideShowCapabilities_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x535e1379_c09e_4a54_a511_597bab3a72b8); } impl ::core::convert::From<ISideShowCapabilities> for ::windows::core::IUnknown { fn from(value: ISideShowCapabilities) -> Self { value.0 } } impl ::core::convert::From<&ISideShowCapabilities> for ::windows::core::IUnknown { fn from(value: &ISideShowCapabilities) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowCapabilities { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowCapabilities_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, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_keycapability: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY, inout_pvalue: *mut ::core::mem::ManuallyDrop<super::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage", feature = "Win32_UI_Shell_PropertiesSystem")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowCapabilitiesCollection(pub ::windows::core::IUnknown); impl ISideShowCapabilitiesCollection { pub unsafe fn GetCount(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn GetAt(&self, in_dwindex: u32) -> ::windows::core::Result<ISideShowCapabilities> { let mut result__: <ISideShowCapabilities as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_dwindex), &mut result__).from_abi::<ISideShowCapabilities>(result__) } } unsafe impl ::windows::core::Interface for ISideShowCapabilitiesCollection { type Vtable = ISideShowCapabilitiesCollection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x50305597_5e0d_4ff7_b3af_33d0d9bd52dd); } impl ::core::convert::From<ISideShowCapabilitiesCollection> for ::windows::core::IUnknown { fn from(value: ISideShowCapabilitiesCollection) -> Self { value.0 } } impl ::core::convert::From<&ISideShowCapabilitiesCollection> for ::windows::core::IUnknown { fn from(value: &ISideShowCapabilitiesCollection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowCapabilitiesCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowCapabilitiesCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowCapabilitiesCollection_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, out_pdwcount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_dwindex: u32, out_ppcapabilities: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowContent(pub ::windows::core::IUnknown); impl ISideShowContent { pub unsafe fn GetContent<'a, Param0: ::windows::core::IntoParam<'a, ISideShowCapabilities>>(&self, in_picapabilities: Param0, out_pdwsize: *mut u32, out_ppbdata: *mut *mut u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), in_picapabilities.into_param().abi(), ::core::mem::transmute(out_pdwsize), ::core::mem::transmute(out_ppbdata)).ok() } pub unsafe fn ContentId(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn DifferentiateContent(&self) -> ::windows::core::Result<super::super::Foundation::BOOL> { let mut result__: <super::super::Foundation::BOOL as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::BOOL>(result__) } } unsafe impl ::windows::core::Interface for ISideShowContent { type Vtable = ISideShowContent_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc18552ed_74ff_4fec_be07_4cfed29d4887); } impl ::core::convert::From<ISideShowContent> for ::windows::core::IUnknown { fn from(value: ISideShowContent) -> Self { value.0 } } impl ::core::convert::From<&ISideShowContent> for ::windows::core::IUnknown { fn from(value: &ISideShowContent) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowContent { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowContent { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowContent_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, in_picapabilities: ::windows::core::RawPtr, out_pdwsize: *mut u32, out_ppbdata: *mut *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_pcontentid: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_pfdifferentiatecontent: *mut super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowContentManager(pub ::windows::core::IUnknown); impl ISideShowContentManager { pub unsafe fn Add<'a, Param0: ::windows::core::IntoParam<'a, ISideShowContent>>(&self, in_picontent: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), in_picontent.into_param().abi()).ok() } pub unsafe fn Remove(&self, in_contentid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_contentid)).ok() } pub unsafe fn RemoveAll(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn SetEventSink<'a, Param0: ::windows::core::IntoParam<'a, ISideShowEvents>>(&self, in_pievents: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), in_pievents.into_param().abi()).ok() } pub unsafe fn GetDeviceCapabilities(&self) -> ::windows::core::Result<ISideShowCapabilitiesCollection> { let mut result__: <ISideShowCapabilitiesCollection as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<ISideShowCapabilitiesCollection>(result__) } } unsafe impl ::windows::core::Interface for ISideShowContentManager { type Vtable = ISideShowContentManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5d5b66b_eef9_41db_8d7e_e17c33ab10b0); } impl ::core::convert::From<ISideShowContentManager> for ::windows::core::IUnknown { fn from(value: ISideShowContentManager) -> Self { value.0 } } impl ::core::convert::From<&ISideShowContentManager> for ::windows::core::IUnknown { fn from(value: &ISideShowContentManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowContentManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowContentManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowContentManager_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, in_picontent: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_contentid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_pievents: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_ppcollection: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowEvents(pub ::windows::core::IUnknown); impl ISideShowEvents { pub unsafe fn ContentMissing(&self, in_contentid: u32) -> ::windows::core::Result<ISideShowContent> { let mut result__: <ISideShowContent as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_contentid), &mut result__).from_abi::<ISideShowContent>(result__) } pub unsafe fn ApplicationEvent<'a, Param0: ::windows::core::IntoParam<'a, ISideShowCapabilities>>(&self, in_picapabilities: Param0, in_dweventid: u32, in_dweventsize: u32, in_pbeventdata: *const u8) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), in_picapabilities.into_param().abi(), ::core::mem::transmute(in_dweventid), ::core::mem::transmute(in_dweventsize), ::core::mem::transmute(in_pbeventdata)).ok() } pub unsafe fn DeviceAdded<'a, Param0: ::windows::core::IntoParam<'a, ISideShowCapabilities>>(&self, in_pidevice: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), in_pidevice.into_param().abi()).ok() } pub unsafe fn DeviceRemoved<'a, Param0: ::windows::core::IntoParam<'a, ISideShowCapabilities>>(&self, in_pidevice: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), in_pidevice.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for ISideShowEvents { type Vtable = ISideShowEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x61feca4c_deb4_4a7e_8d75_51f1132d615b); } impl ::core::convert::From<ISideShowEvents> for ::windows::core::IUnknown { fn from(value: ISideShowEvents) -> Self { value.0 } } impl ::core::convert::From<&ISideShowEvents> for ::windows::core::IUnknown { fn from(value: &ISideShowEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowEvents_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, in_contentid: u32, out_ppicontent: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_picapabilities: ::windows::core::RawPtr, in_dweventid: u32, in_dweventsize: u32, in_pbeventdata: *const u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_pidevice: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_pidevice: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowKeyCollection(pub ::windows::core::IUnknown); impl ISideShowKeyCollection { #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub unsafe fn Add(&self, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(key)).ok() } pub unsafe fn Clear(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub unsafe fn GetAt(&self, dwindex: u32, pkey: *mut super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwindex), ::core::mem::transmute(pkey)).ok() } pub unsafe fn GetCount(&self, pcelems: *const u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcelems)).ok() } pub unsafe fn RemoveAt(&self, dwindex: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwindex)).ok() } } unsafe impl ::windows::core::Interface for ISideShowKeyCollection { type Vtable = ISideShowKeyCollection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x045473bc_a37b_4957_b144_68105411ed8e); } impl ::core::convert::From<ISideShowKeyCollection> for ::windows::core::IUnknown { fn from(value: ISideShowKeyCollection) -> Self { value.0 } } impl ::core::convert::From<&ISideShowKeyCollection> for ::windows::core::IUnknown { fn from(value: &ISideShowKeyCollection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowKeyCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowKeyCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowKeyCollection_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, #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, key: *const super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_UI_Shell_PropertiesSystem"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwindex: u32, pkey: *mut super::super::UI::Shell::PropertiesSystem::PROPERTYKEY) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_UI_Shell_PropertiesSystem"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcelems: *const u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwindex: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowNotification(pub ::windows::core::IUnknown); impl ISideShowNotification { pub unsafe fn NotificationId(&self) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__) } pub unsafe fn SetNotificationId(&self, in_notificationid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_notificationid)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Title(&self) -> ::windows::core::Result<super::super::Foundation::PWSTR> { let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetTitle<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, in_pwsztitle: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), in_pwsztitle.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Message(&self) -> ::windows::core::Result<super::super::Foundation::PWSTR> { let mut result__: <super::super::Foundation::PWSTR as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::PWSTR>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetMessage<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, in_pwszmessage: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), in_pwszmessage.into_param().abi()).ok() } #[cfg(feature = "Win32_UI_WindowsAndMessaging")] pub unsafe fn Image(&self) -> ::windows::core::Result<super::super::UI::WindowsAndMessaging::HICON> { let mut result__: <super::super::UI::WindowsAndMessaging::HICON as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::UI::WindowsAndMessaging::HICON>(result__) } #[cfg(feature = "Win32_UI_WindowsAndMessaging")] pub unsafe fn SetImage<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::WindowsAndMessaging::HICON>>(&self, in_hicon: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), in_hicon.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ExpirationTime(&self) -> ::windows::core::Result<super::super::Foundation::SYSTEMTIME> { let mut result__: <super::super::Foundation::SYSTEMTIME as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::Foundation::SYSTEMTIME>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetExpirationTime(&self, in_ptime: *const super::super::Foundation::SYSTEMTIME) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_ptime)).ok() } } unsafe impl ::windows::core::Interface for ISideShowNotification { type Vtable = ISideShowNotification_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x03c93300_8ab2_41c5_9b79_46127a30e148); } impl ::core::convert::From<ISideShowNotification> for ::windows::core::IUnknown { fn from(value: ISideShowNotification) -> Self { value.0 } } impl ::core::convert::From<&ISideShowNotification> for ::windows::core::IUnknown { fn from(value: &ISideShowNotification) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowNotification { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowNotification { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowNotification_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, out_pnotificationid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_notificationid: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_ppwsztitle: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_pwsztitle: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_ppwszmessage: *mut super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_pwszmessage: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_UI_WindowsAndMessaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_phicon: *mut super::super::UI::WindowsAndMessaging::HICON) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_UI_WindowsAndMessaging"))] usize, #[cfg(feature = "Win32_UI_WindowsAndMessaging")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_hicon: super::super::UI::WindowsAndMessaging::HICON) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_UI_WindowsAndMessaging"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, out_ptime: *mut super::super::Foundation::SYSTEMTIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_ptime: *const super::super::Foundation::SYSTEMTIME) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowNotificationManager(pub ::windows::core::IUnknown); impl ISideShowNotificationManager { pub unsafe fn Show<'a, Param0: ::windows::core::IntoParam<'a, ISideShowNotification>>(&self, in_pinotification: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), in_pinotification.into_param().abi()).ok() } pub unsafe fn Revoke(&self, in_notificationid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_notificationid)).ok() } pub unsafe fn RevokeAll(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for ISideShowNotificationManager { type Vtable = ISideShowNotificationManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x63cea909_f2b9_4302_b5e1_c68e6d9ab833); } impl ::core::convert::From<ISideShowNotificationManager> for ::windows::core::IUnknown { fn from(value: ISideShowNotificationManager) -> Self { value.0 } } impl ::core::convert::From<&ISideShowNotificationManager> for ::windows::core::IUnknown { fn from(value: &ISideShowNotificationManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowNotificationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowNotificationManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowNotificationManager_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, in_pinotification: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_notificationid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowPropVariantCollection(pub ::windows::core::IUnknown); impl ISideShowPropVariantCollection { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe fn Add(&self, pvalue: *const super::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvalue)).ok() } pub unsafe fn Clear(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe fn GetAt(&self, dwindex: u32, pvalue: *mut super::Com::StructuredStorage::PROPVARIANT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwindex), ::core::mem::transmute(pvalue)).ok() } pub unsafe fn GetCount(&self, pcelems: *const u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcelems)).ok() } pub unsafe fn RemoveAt(&self, dwindex: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwindex)).ok() } } unsafe impl ::windows::core::Interface for ISideShowPropVariantCollection { type Vtable = ISideShowPropVariantCollection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2ea7a549_7bff_4aae_bab0_22d43111de49); } impl ::core::convert::From<ISideShowPropVariantCollection> for ::windows::core::IUnknown { fn from(value: ISideShowPropVariantCollection) -> Self { value.0 } } impl ::core::convert::From<&ISideShowPropVariantCollection> for ::windows::core::IUnknown { fn from(value: &ISideShowPropVariantCollection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowPropVariantCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowPropVariantCollection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowPropVariantCollection_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, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvalue: *const ::core::mem::ManuallyDrop<super::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwindex: u32, pvalue: *mut ::core::mem::ManuallyDrop<super::Com::StructuredStorage::PROPVARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcelems: *const u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwindex: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ISideShowSession(pub ::windows::core::IUnknown); impl ISideShowSession { pub unsafe fn RegisterContent(&self, in_applicationid: *const ::windows::core::GUID, in_endpointid: *const ::windows::core::GUID) -> ::windows::core::Result<ISideShowContentManager> { let mut result__: <ISideShowContentManager as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_applicationid), ::core::mem::transmute(in_endpointid), &mut result__).from_abi::<ISideShowContentManager>(result__) } pub unsafe fn RegisterNotifications(&self, in_applicationid: *const ::windows::core::GUID) -> ::windows::core::Result<ISideShowNotificationManager> { let mut result__: <ISideShowNotificationManager as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(in_applicationid), &mut result__).from_abi::<ISideShowNotificationManager>(result__) } } unsafe impl ::windows::core::Interface for ISideShowSession { type Vtable = ISideShowSession_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe22331ee_9e7d_4922_9fc2_ab7aa41ce491); } impl ::core::convert::From<ISideShowSession> for ::windows::core::IUnknown { fn from(value: ISideShowSession) -> Self { value.0 } } impl ::core::convert::From<&ISideShowSession> for ::windows::core::IUnknown { fn from(value: &ISideShowSession) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISideShowSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a ISideShowSession { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISideShowSession_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, in_applicationid: *const ::windows::core::GUID, in_endpointid: *const ::windows::core::GUID, out_ppicontent: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, in_applicationid: *const ::windows::core::GUID, out_ppinotification: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(1))] pub struct NEW_EVENT_DATA_AVAILABLE { pub cbNewEventDataAvailable: u32, pub dwVersion: u32, } impl NEW_EVENT_DATA_AVAILABLE {} impl ::core::default::Default for NEW_EVENT_DATA_AVAILABLE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::cmp::PartialEq for NEW_EVENT_DATA_AVAILABLE { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } impl ::core::cmp::Eq for NEW_EVENT_DATA_AVAILABLE {} unsafe impl ::windows::core::Abi for NEW_EVENT_DATA_AVAILABLE { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SCF_BUTTON_IDS(pub i32); pub const SCF_BUTTON_MENU: SCF_BUTTON_IDS = SCF_BUTTON_IDS(1i32); pub const SCF_BUTTON_SELECT: SCF_BUTTON_IDS = SCF_BUTTON_IDS(2i32); pub const SCF_BUTTON_UP: SCF_BUTTON_IDS = SCF_BUTTON_IDS(3i32); pub const SCF_BUTTON_DOWN: SCF_BUTTON_IDS = SCF_BUTTON_IDS(4i32); pub const SCF_BUTTON_LEFT: SCF_BUTTON_IDS = SCF_BUTTON_IDS(5i32); pub const SCF_BUTTON_RIGHT: SCF_BUTTON_IDS = SCF_BUTTON_IDS(6i32); pub const SCF_BUTTON_PLAY: SCF_BUTTON_IDS = SCF_BUTTON_IDS(7i32); pub const SCF_BUTTON_PAUSE: SCF_BUTTON_IDS = SCF_BUTTON_IDS(8i32); pub const SCF_BUTTON_FASTFORWARD: SCF_BUTTON_IDS = SCF_BUTTON_IDS(9i32); pub const SCF_BUTTON_REWIND: SCF_BUTTON_IDS = SCF_BUTTON_IDS(10i32); pub const SCF_BUTTON_STOP: SCF_BUTTON_IDS = SCF_BUTTON_IDS(11i32); pub const SCF_BUTTON_BACK: SCF_BUTTON_IDS = SCF_BUTTON_IDS(65280i32); impl ::core::convert::From<i32> for SCF_BUTTON_IDS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SCF_BUTTON_IDS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCF_CONTEXTMENU_EVENT { pub PreviousPage: u32, pub TargetPage: u32, pub PreviousItemId: u32, pub MenuPage: u32, pub MenuItemId: u32, } impl SCF_CONTEXTMENU_EVENT {} impl ::core::default::Default for SCF_CONTEXTMENU_EVENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCF_CONTEXTMENU_EVENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCF_CONTEXTMENU_EVENT").field("PreviousPage", &self.PreviousPage).field("TargetPage", &self.TargetPage).field("PreviousItemId", &self.PreviousItemId).field("MenuPage", &self.MenuPage).field("MenuItemId", &self.MenuItemId).finish() } } impl ::core::cmp::PartialEq for SCF_CONTEXTMENU_EVENT { fn eq(&self, other: &Self) -> bool { self.PreviousPage == other.PreviousPage && self.TargetPage == other.TargetPage && self.PreviousItemId == other.PreviousItemId && self.MenuPage == other.MenuPage && self.MenuItemId == other.MenuItemId } } impl ::core::cmp::Eq for SCF_CONTEXTMENU_EVENT {} unsafe impl ::windows::core::Abi for SCF_CONTEXTMENU_EVENT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCF_EVENT_HEADER { pub PreviousPage: u32, pub TargetPage: u32, } impl SCF_EVENT_HEADER {} impl ::core::default::Default for SCF_EVENT_HEADER { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCF_EVENT_HEADER { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCF_EVENT_HEADER").field("PreviousPage", &self.PreviousPage).field("TargetPage", &self.TargetPage).finish() } } impl ::core::cmp::PartialEq for SCF_EVENT_HEADER { fn eq(&self, other: &Self) -> bool { self.PreviousPage == other.PreviousPage && self.TargetPage == other.TargetPage } } impl ::core::cmp::Eq for SCF_EVENT_HEADER {} unsafe impl ::windows::core::Abi for SCF_EVENT_HEADER { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SCF_EVENT_IDS(pub i32); pub const SCF_EVENT_NAVIGATION: SCF_EVENT_IDS = SCF_EVENT_IDS(1i32); pub const SCF_EVENT_MENUACTION: SCF_EVENT_IDS = SCF_EVENT_IDS(2i32); pub const SCF_EVENT_CONTEXTMENU: SCF_EVENT_IDS = SCF_EVENT_IDS(3i32); impl ::core::convert::From<i32> for SCF_EVENT_IDS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SCF_EVENT_IDS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCF_MENUACTION_EVENT { pub PreviousPage: u32, pub TargetPage: u32, pub Button: u32, pub ItemId: u32, } impl SCF_MENUACTION_EVENT {} impl ::core::default::Default for SCF_MENUACTION_EVENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCF_MENUACTION_EVENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCF_MENUACTION_EVENT").field("PreviousPage", &self.PreviousPage).field("TargetPage", &self.TargetPage).field("Button", &self.Button).field("ItemId", &self.ItemId).finish() } } impl ::core::cmp::PartialEq for SCF_MENUACTION_EVENT { fn eq(&self, other: &Self) -> bool { self.PreviousPage == other.PreviousPage && self.TargetPage == other.TargetPage && self.Button == other.Button && self.ItemId == other.ItemId } } impl ::core::cmp::Eq for SCF_MENUACTION_EVENT {} unsafe impl ::windows::core::Abi for SCF_MENUACTION_EVENT { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct SCF_NAVIGATION_EVENT { pub PreviousPage: u32, pub TargetPage: u32, pub Button: u32, } impl SCF_NAVIGATION_EVENT {} impl ::core::default::Default for SCF_NAVIGATION_EVENT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for SCF_NAVIGATION_EVENT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("SCF_NAVIGATION_EVENT").field("PreviousPage", &self.PreviousPage).field("TargetPage", &self.TargetPage).field("Button", &self.Button).finish() } } impl ::core::cmp::PartialEq for SCF_NAVIGATION_EVENT { fn eq(&self, other: &Self) -> bool { self.PreviousPage == other.PreviousPage && self.TargetPage == other.TargetPage && self.Button == other.Button } } impl ::core::cmp::Eq for SCF_NAVIGATION_EVENT {} unsafe impl ::windows::core::Abi for SCF_NAVIGATION_EVENT { type Abi = Self; } pub const SIDESHOW_APPLICATION_EVENT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4cb572fa_1d3b_49b3_a17a_2e6bff052854); #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_CLIENT_AREA_HEIGHT: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 16u32, }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_CLIENT_AREA_WIDTH: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 15u32, }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_COLOR_DEPTH: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 5u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_COLOR_TYPE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 6u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_CURRENT_LANGUAGE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 9u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_DATA_CACHE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 7u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_DEVICE_ID: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 1u32 }; pub const SIDESHOW_CAPABILITY_DEVICE_PROPERTIES: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99); #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SCREEN_HEIGHT: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 4u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SCREEN_TYPE: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 2u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SCREEN_WIDTH: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 3u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SUPPORTED_IMAGE_FORMATS: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 14u32, }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SUPPORTED_LANGUAGES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 8u32 }; #[cfg(feature = "Win32_UI_Shell_PropertiesSystem")] pub const SIDESHOW_CAPABILITY_SUPPORTED_THEMES: super::super::UI::Shell::PropertiesSystem::PROPERTYKEY = super::super::UI::Shell::PropertiesSystem::PROPERTYKEY { fmtid: ::windows::core::GUID::from_u128(0x8abc88a8_857b_4ad7_a35a_b5942f492b99), pid: 10u32, }; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SIDESHOW_COLOR_TYPE(pub i32); pub const SIDESHOW_COLOR_TYPE_COLOR: SIDESHOW_COLOR_TYPE = SIDESHOW_COLOR_TYPE(0i32); pub const SIDESHOW_COLOR_TYPE_GREYSCALE: SIDESHOW_COLOR_TYPE = SIDESHOW_COLOR_TYPE(1i32); pub const SIDESHOW_COLOR_TYPE_BLACK_AND_WHITE: SIDESHOW_COLOR_TYPE = SIDESHOW_COLOR_TYPE(2i32); impl ::core::convert::From<i32> for SIDESHOW_COLOR_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SIDESHOW_COLOR_TYPE { type Abi = Self; } pub const SIDESHOW_CONTENT_MISSING_EVENT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5007fba8_d313_439f_bea2_a50201d3e9a8); pub const SIDESHOW_ENDPOINT_ICAL: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4dff36b5_9dde_4f76_9a2a_96435047063d); pub const SIDESHOW_ENDPOINT_SIMPLE_CONTENT_FORMAT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa9a5353f_2d4b_47ce_93ee_759f3a7dda4f); pub const SIDESHOW_EVENTID_APPLICATION_ENTER: u32 = 4294901760u32; pub const SIDESHOW_EVENTID_APPLICATION_EXIT: u32 = 4294901761u32; pub const SIDESHOW_NEW_EVENT_DATA_AVAILABLE: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x57813854_2fc1_411c_a59f_f24927608804); #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct SIDESHOW_SCREEN_TYPE(pub i32); pub const SIDESHOW_SCREEN_TYPE_BITMAP: SIDESHOW_SCREEN_TYPE = SIDESHOW_SCREEN_TYPE(0i32); pub const SIDESHOW_SCREEN_TYPE_TEXT: SIDESHOW_SCREEN_TYPE = SIDESHOW_SCREEN_TYPE(1i32); impl ::core::convert::From<i32> for SIDESHOW_SCREEN_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for SIDESHOW_SCREEN_TYPE { type Abi = Self; } pub const SIDESHOW_USER_CHANGE_REQUEST_EVENT: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5009673c_3f7d_4c7e_9971_eaa2e91f1575); pub const SideShowKeyCollection: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdfbbdbf8_18de_49b8_83dc_ebc727c62d94); pub const SideShowNotification: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0ce3e86f_d5cd_4525_a766_1abab1a752f5); pub const SideShowPropVariantCollection: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe640f415_539e_4923_96cd_5f093bc250cd); pub const SideShowSession: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe20543b9_f785_4ea2_981e_c4ffa76bbc7c); pub const VERSION_1_WINDOWS_7: u32 = 0u32;
use cgmath::{Vector2, Zero}; use utilities::prelude::*; #[derive(Copy, Clone, Debug)] pub struct ControllerAxis { pub left_stick: Vector2<f32>, pub right_stick: Vector2<f32>, pub left_trigger: f32, pub right_trigger: f32, } impl Default for ControllerAxis { fn default() -> Self { ControllerAxis { left_stick: Vector2::zero(), right_stick: Vector2::zero(), left_trigger: 0.0, right_trigger: 0.0, } } }
#[doc = "Reader of register SR"] pub type R = crate::R<u32, super::SR>; #[doc = "Writer for register SR"] pub type W = crate::W<u32, super::SR>; #[doc = "Register SR `reset()`'s with value 0"] impl crate::ResetValue for super::SR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TXIS`"] pub type TXIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXIS`"] pub struct TXIS_W<'a> { w: &'a mut W, } impl<'a> TXIS_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `TXMSGDISC`"] pub type TXMSGDISC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXMSGDISC`"] pub struct TXMSGDISC_W<'a> { w: &'a mut W, } impl<'a> TXMSGDISC_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `TXMSGSENT`"] pub type TXMSGSENT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXMSGSENT`"] pub struct TXMSGSENT_W<'a> { w: &'a mut W, } impl<'a> TXMSGSENT_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 = "Reader of field `TXMSGABT`"] pub type TXMSGABT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXMSGABT`"] pub struct TXMSGABT_W<'a> { w: &'a mut W, } impl<'a> TXMSGABT_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 = "Reader of field `HRSTDISC`"] pub type HRSTDISC_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HRSTDISC`"] pub struct HRSTDISC_W<'a> { w: &'a mut W, } impl<'a> HRSTDISC_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 = "Reader of field `HRSTSENT`"] pub type HRSTSENT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `HRSTSENT`"] pub struct HRSTSENT_W<'a> { w: &'a mut W, } impl<'a> HRSTSENT_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 } } #[doc = "Reader of field `TXUND`"] pub type TXUND_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TXUND`"] pub struct TXUND_W<'a> { w: &'a mut W, } impl<'a> TXUND_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "Reader of field `RXNE`"] pub type RXNE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXNE`"] pub struct RXNE_W<'a> { w: &'a mut W, } impl<'a> RXNE_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 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "Reader of field `RXORDDET`"] pub type RXORDDET_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXORDDET`"] pub struct RXORDDET_W<'a> { w: &'a mut W, } impl<'a> RXORDDET_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 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `RXHRSTDET`"] pub type RXHRSTDET_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXHRSTDET`"] pub struct RXHRSTDET_W<'a> { w: &'a mut W, } impl<'a> RXHRSTDET_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 << 10)) | (((value as u32) & 0x01) << 10); self.w } } #[doc = "Reader of field `RXOVR`"] pub type RXOVR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXOVR`"] pub struct RXOVR_W<'a> { w: &'a mut W, } impl<'a> RXOVR_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 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `RXMSGEND`"] pub type RXMSGEND_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXMSGEND`"] pub struct RXMSGEND_W<'a> { w: &'a mut W, } impl<'a> RXMSGEND_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 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `RXERR`"] pub type RXERR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RXERR`"] pub struct RXERR_W<'a> { w: &'a mut W, } impl<'a> RXERR_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 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `TYPECEVT1`"] pub type TYPECEVT1_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TYPECEVT1`"] pub struct TYPECEVT1_W<'a> { w: &'a mut W, } impl<'a> TYPECEVT1_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 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `TYPECEVT2`"] pub type TYPECEVT2_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TYPECEVT2`"] pub struct TYPECEVT2_W<'a> { w: &'a mut W, } impl<'a> TYPECEVT2_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 } } #[doc = "Reader of field `TYPEC_VSTATE_CC1`"] pub type TYPEC_VSTATE_CC1_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TYPEC_VSTATE_CC1`"] pub struct TYPEC_VSTATE_CC1_W<'a> { w: &'a mut W, } impl<'a> TYPEC_VSTATE_CC1_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 & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `TYPEC_VSTATE_CC2`"] pub type TYPEC_VSTATE_CC2_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TYPEC_VSTATE_CC2`"] pub struct TYPEC_VSTATE_CC2_W<'a> { w: &'a mut W, } impl<'a> TYPEC_VSTATE_CC2_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 & !(0x03 << 18)) | (((value as u32) & 0x03) << 18); self.w } } #[doc = "Reader of field `FRSEVT`"] pub type FRSEVT_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FRSEVT`"] pub struct FRSEVT_W<'a> { w: &'a mut W, } impl<'a> FRSEVT_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 << 20)) | (((value as u32) & 0x01) << 20); self.w } } impl R { #[doc = "Bit 0 - TXIS"] #[inline(always)] pub fn txis(&self) -> TXIS_R { TXIS_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TXMSGDISC"] #[inline(always)] pub fn txmsgdisc(&self) -> TXMSGDISC_R { TXMSGDISC_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TXMSGSENT"] #[inline(always)] pub fn txmsgsent(&self) -> TXMSGSENT_R { TXMSGSENT_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - TXMSGABT"] #[inline(always)] pub fn txmsgabt(&self) -> TXMSGABT_R { TXMSGABT_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - HRSTDISC"] #[inline(always)] pub fn hrstdisc(&self) -> HRSTDISC_R { HRSTDISC_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - HRSTSENT"] #[inline(always)] pub fn hrstsent(&self) -> HRSTSENT_R { HRSTSENT_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - TXUND"] #[inline(always)] pub fn txund(&self) -> TXUND_R { TXUND_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 8 - RXNE"] #[inline(always)] pub fn rxne(&self) -> RXNE_R { RXNE_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - RXORDDET"] #[inline(always)] pub fn rxorddet(&self) -> RXORDDET_R { RXORDDET_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - RXHRSTDET"] #[inline(always)] pub fn rxhrstdet(&self) -> RXHRSTDET_R { RXHRSTDET_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - RXOVR"] #[inline(always)] pub fn rxovr(&self) -> RXOVR_R { RXOVR_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - RXMSGEND"] #[inline(always)] pub fn rxmsgend(&self) -> RXMSGEND_R { RXMSGEND_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 13 - RXERR"] #[inline(always)] pub fn rxerr(&self) -> RXERR_R { RXERR_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 14 - TYPECEVT1"] #[inline(always)] pub fn typecevt1(&self) -> TYPECEVT1_R { TYPECEVT1_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - TYPECEVT2"] #[inline(always)] pub fn typecevt2(&self) -> TYPECEVT2_R { TYPECEVT2_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 16:17 - TYPEC_VSTATE_CC1"] #[inline(always)] pub fn typec_vstate_cc1(&self) -> TYPEC_VSTATE_CC1_R { TYPEC_VSTATE_CC1_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bits 18:19 - TYPEC_VSTATE_CC2"] #[inline(always)] pub fn typec_vstate_cc2(&self) -> TYPEC_VSTATE_CC2_R { TYPEC_VSTATE_CC2_R::new(((self.bits >> 18) & 0x03) as u8) } #[doc = "Bit 20 - FRSEVT"] #[inline(always)] pub fn frsevt(&self) -> FRSEVT_R { FRSEVT_R::new(((self.bits >> 20) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TXIS"] #[inline(always)] pub fn txis(&mut self) -> TXIS_W { TXIS_W { w: self } } #[doc = "Bit 1 - TXMSGDISC"] #[inline(always)] pub fn txmsgdisc(&mut self) -> TXMSGDISC_W { TXMSGDISC_W { w: self } } #[doc = "Bit 2 - TXMSGSENT"] #[inline(always)] pub fn txmsgsent(&mut self) -> TXMSGSENT_W { TXMSGSENT_W { w: self } } #[doc = "Bit 3 - TXMSGABT"] #[inline(always)] pub fn txmsgabt(&mut self) -> TXMSGABT_W { TXMSGABT_W { w: self } } #[doc = "Bit 4 - HRSTDISC"] #[inline(always)] pub fn hrstdisc(&mut self) -> HRSTDISC_W { HRSTDISC_W { w: self } } #[doc = "Bit 5 - HRSTSENT"] #[inline(always)] pub fn hrstsent(&mut self) -> HRSTSENT_W { HRSTSENT_W { w: self } } #[doc = "Bit 6 - TXUND"] #[inline(always)] pub fn txund(&mut self) -> TXUND_W { TXUND_W { w: self } } #[doc = "Bit 8 - RXNE"] #[inline(always)] pub fn rxne(&mut self) -> RXNE_W { RXNE_W { w: self } } #[doc = "Bit 9 - RXORDDET"] #[inline(always)] pub fn rxorddet(&mut self) -> RXORDDET_W { RXORDDET_W { w: self } } #[doc = "Bit 10 - RXHRSTDET"] #[inline(always)] pub fn rxhrstdet(&mut self) -> RXHRSTDET_W { RXHRSTDET_W { w: self } } #[doc = "Bit 11 - RXOVR"] #[inline(always)] pub fn rxovr(&mut self) -> RXOVR_W { RXOVR_W { w: self } } #[doc = "Bit 12 - RXMSGEND"] #[inline(always)] pub fn rxmsgend(&mut self) -> RXMSGEND_W { RXMSGEND_W { w: self } } #[doc = "Bit 13 - RXERR"] #[inline(always)] pub fn rxerr(&mut self) -> RXERR_W { RXERR_W { w: self } } #[doc = "Bit 14 - TYPECEVT1"] #[inline(always)] pub fn typecevt1(&mut self) -> TYPECEVT1_W { TYPECEVT1_W { w: self } } #[doc = "Bit 15 - TYPECEVT2"] #[inline(always)] pub fn typecevt2(&mut self) -> TYPECEVT2_W { TYPECEVT2_W { w: self } } #[doc = "Bits 16:17 - TYPEC_VSTATE_CC1"] #[inline(always)] pub fn typec_vstate_cc1(&mut self) -> TYPEC_VSTATE_CC1_W { TYPEC_VSTATE_CC1_W { w: self } } #[doc = "Bits 18:19 - TYPEC_VSTATE_CC2"] #[inline(always)] pub fn typec_vstate_cc2(&mut self) -> TYPEC_VSTATE_CC2_W { TYPEC_VSTATE_CC2_W { w: self } } #[doc = "Bit 20 - FRSEVT"] #[inline(always)] pub fn frsevt(&mut self) -> FRSEVT_W { FRSEVT_W { w: self } } }
const ISA_TESTS: &[(&str, &str)] = &[ ("rv32ui", "add"), ("rv32ui", "addi"), ("rv32ui", "and"), ("rv32ui", "andi"), ("rv32ui", "auipc"), ("rv32ui", "beq"), ("rv32ui", "bge"), ("rv32ui", "bgeu"), ("rv32ui", "blt"), ("rv32ui", "bltu"), ("rv32ui", "bne"), ("rv32ui", "fence_i"), ("rv32ui", "jal"), ("rv32ui", "jalr"), ("rv32ui", "lb"), ("rv32ui", "lbu"), ("rv32ui", "lh"), ("rv32ui", "lhu"), ("rv32ui", "lui"), ("rv32ui", "lw"), ("rv32ui", "or"), ("rv32ui", "ori"), ("rv32ui", "sb"), ("rv32ui", "sh"), ("rv32ui", "simple"), ("rv32ui", "sll"), ("rv32ui", "slli"), ("rv32ui", "slt"), ("rv32ui", "slti"), ("rv32ui", "sltiu"), ("rv32ui", "sltu"), ("rv32ui", "sra"), ("rv32ui", "srai"), ("rv32ui", "srl"), ("rv32ui", "srli"), ("rv32ui", "sub"), ("rv32ui", "sw"), ("rv32ui", "xor"), ("rv32ui", "xori"), ("rv32um", "div"), ("rv32um", "divu"), ("rv32um", "mul"), ("rv32um", "mulh"), ("rv32um", "mulhsu"), ("rv32um", "mulhu"), ("rv32um", "rem"), ("rv32um", "remu"), ("rv32ua", "amoadd_w"), ("rv32ua", "amoand_w"), ("rv32ua", "amomax_w"), ("rv32ua", "amomaxu_w"), ("rv32ua", "amomin_w"), ("rv32ua", "amominu_w"), ("rv32ua", "amoor_w"), ("rv32ua", "amoswap_w"), ("rv32ua", "amoxor_w"), ("rv32ua", "lrsc"), ("rv32uf", "fadd"), ("rv32uf", "fclass"), ("rv32uf", "fcmp"), ("rv32uf", "fcvt"), ("rv32uf", "fcvt_w"), ("rv32uf", "fdiv"), ("rv32uf", "fmadd"), ("rv32uf", "fmin"), ("rv32uf", "ldst"), ("rv32uf", "move"), ("rv32uf", "recoding"), ("rv32ud", "fadd"), ("rv32ud", "fclass"), ("rv32ud", "fcmp"), ("rv32ud", "fcvt"), ("rv32ud", "fcvt_w"), ("rv32ud", "fdiv"), ("rv32ud", "fmadd"), ("rv32ud", "fmin"), ("rv32ud", "ldst"), // ("rv32ud", "move"), ("rv32ud", "recoding"), ];
use std::io::Write; use std::io; //convenience method for saving a few //lines of boilerplate when reading a response from //standard input fn read_result()->String{ let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); input } pub fn solution(){ println!("Compounding interest calculator\nPrincipal(in dollars): "); io::stdout().flush().unwrap(); let principal: f32 = read_result().trim().parse().unwrap(); println!("Are the compounded periods in years, months, or quarters? "); io::stdout().flush().unwrap(); let periods = match read_result().trim(){ "months" => { 12.0 }, "years" => { 1.0 }, "quarters" => { 4.0 }, _ => { println!("Invalid input"); return; } }; println!("Enter the number of years: "); let num_years: f32 = read_result().trim().parse().unwrap(); println!("Enter the % annual interest"); let rate: f32 = read_result().trim().parse().unwrap(); let mut balance:f32 = principal; let mut interest_earned:f32 = 0.0; for _ in 0..(periods * num_years) as i32{ interest_earned += balance * (rate / 100.0 / periods); balance += balance * (rate/ 100.0 / periods); } println!("Principal: ${}\nAnnual Rate: {}%\nYears compounded:{}\nInterest Earned: ${}\nEnding Balance: ${}", principal, rate, num_years,interest_earned,balance); }
use nalgebra::base::Vector3; use rand::{ distributions::uniform::{UniformFloat, UniformSampler}, random, thread_rng, }; use std::f64::consts::PI; use crate::{ hittable::{HitRecord, Hittable}, material::Material, }; pub type V3 = Vector3<f64>; pub type Point = V3; pub struct Ray { pub orig: Point, pub dir: V3, } pub struct Sphere { pub center: Point, pub radius: f64, pub material: Box<dyn Material>, } pub fn v3(x: f64, y: f64, z: f64) -> V3 { V3::new(x, y, z) } pub fn rand_vec() -> V3 { v3(random(), random(), random()) } pub fn unit(v: &V3) -> V3 { v.normalize() } pub fn near_zero(v: &V3) -> bool { let eps = 1e-8; v.norm() < eps } pub fn rand_in(min: f64, max: f64) -> f64 { random::<f64>() * (max - min) + min } pub fn rand_in_unit_disk() -> V3 { v3(rand_in(-1., 1.), rand_in(-1., 1.), 0.).normalize() * random::<f64>() } pub fn rand_vec_bounded(min: f64, max: f64) -> V3 { let mut rng = thread_rng(); let range: UniformFloat<f64> = UniformSampler::new(min, max); v3( range.sample(&mut rng), range.sample(&mut rng), range.sample(&mut rng), ) } pub fn deg_to_rad(deg: f64) -> f64 { (deg * PI / 2.) / 180. } pub fn random_in_unit_sphere() -> V3 { rand_vec_bounded(-1., 1.).normalize() * random::<f64>() } pub fn random_unit_vec() -> V3 { rand_vec().normalize() } pub fn reflect(v: &V3, n: &V3) -> V3 { v - 2.0 * v.dot(n) * n } pub fn refract(uv: &V3, n: &V3, etai_over_etat: f64) -> V3 { let cos_theta = -uv.dot(n).min(-1.); let r_out_perp = etai_over_etat * (uv + cos_theta * n); let r_out_par = -(1. - r_out_perp.dot(&r_out_perp)).abs().sqrt() * n; r_out_perp + r_out_par } impl Ray { pub fn at(&self, t: f64) -> V3 { self.orig + t * self.dir } pub fn direction(&self) -> V3 { self.dir } pub fn origin(&self) -> Point { self.orig } } impl Hittable for Sphere { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { let oc = ray.origin() - self.center; let a = ray.direction().norm_squared(); let half_b = oc.dot(&ray.direction()); let c = oc.norm_squared() - self.radius * self.radius; let discriminant = half_b.powf(2.) - a * c; if discriminant < 0.0 { return None; } let mut root = (-half_b - discriminant.sqrt()) / a; if root < t_min || t_max < root { root = (-half_b + discriminant.sqrt()) / a; if root < t_min || t_max < root { return None; } } let t = root; let point = ray.at(root); let outward_normal = (point - self.center) / self.radius; Some(HitRecord::new( &ray, &outward_normal, point, self.material.as_ref(), t, )) } } #[cfg(test)] mod tests { use super::*; use crate::{Color, Metal}; #[test] fn test_hit_sphere() { let mat = Metal { albedo: Color(v3(1., 1., 1.)), fuzz: 0.1, }; let sphere = Sphere { center: v3(0., 0., 0.), radius: 1., material: Arc::new(mat), }; let ray = Ray { orig: v3(-2., 0., 0.), dir: v3(1., 0., 0.), }; // Test hit let res = sphere.hit(&ray, 0., 100.); // A Hit should be detected match res { // recorded hit site should be -1, 0, 0 Some(rec) => assert_eq!((rec.point - v3(-1., 0., 0.)).norm() < 0.01, true), None => panic!("Expected a hit to be recorded"), } } #[test] fn test_hit_sphere_no_intersection() { let mat = Metal { albedo: Color(v3(1., 1., 1.)), fuzz: 0.1, }; let sphere = Sphere { center: v3(0., 0., 0.), radius: 1., material: Arc::new(mat), }; let ray = Ray { orig: v3(-2., 0., 0.), dir: v3(0., 1., 0.), }; // Test hit let res = sphere.hit(&ray, 0., 100.); // No hit should be detected match res { Some(_) => panic!("No hit should be detected"), None => (), } } #[test] fn test_hit_sphere_ray_starts_inside() { let mat = Metal { albedo: Color(v3(1., 1., 1.)), fuzz: 0.1, }; let sphere = Sphere { center: v3(0., 0., 0.), radius: 1., material: Arc::new(mat), }; let ray = Ray { orig: v3(0., 0., 0.), dir: v3(1., 0., 0.), }; // Test hit let res = sphere.hit(&ray, 0., 100.); // Hit should be detected match res { // Hit should occur at 1, 0, 0 Some(rec) => assert_eq!((rec.point - v3(1., 0., 0.)).norm() < 0.01, true), None => panic!("Expected a hit to be recorded"), }; } #[test] fn test_hit_sphere_glancing() { let mat = Metal { albedo: Color(v3(1., 1., 1.)), fuzz: 0.1, }; let sphere = Sphere { center: v3(0., 0., 0.), radius: 1., material: Arc::new(mat), }; let ray = Ray { orig: v3(-2., 1., 0.), dir: v3(1., 0., 0.), }; // Test hit let res = sphere.hit(&ray, 0., 100.); // Hit should be detected match res { // Hit should occur at 0, 1, 0 Some(rec) => assert_eq!((rec.point - v3(0., 1., 0.)).norm() < 0.01, true), None => panic!("Expected a hit to be recorded"), }; } }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use glib; use glib::object::Cast; use glib::object::IsA; use glib::signal::connect_raw; use glib::signal::SignalHandlerId; use glib::translate::*; use glib::GString; use glib_sys; use libc; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; use std::ptr; use webkit2_webextension_sys; use DOMElement; use DOMEventTarget; use DOMHTMLCollection; use DOMHTMLElement; use DOMNode; use DOMObject; glib_wrapper! { pub struct DOMHTMLTableSectionElement(Object<webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, webkit2_webextension_sys::WebKitDOMHTMLTableSectionElementClass, DOMHTMLTableSectionElementClass>) @extends DOMHTMLElement, DOMElement, DOMNode, DOMObject, @implements DOMEventTarget; match fn { get_type => || webkit2_webextension_sys::webkit_dom_html_table_section_element_get_type(), } } pub const NONE_DOMHTML_TABLE_SECTION_ELEMENT: Option<&DOMHTMLTableSectionElement> = None; pub trait DOMHTMLTableSectionElementExt: 'static { #[cfg_attr(feature = "v2_22", deprecated)] fn delete_row(&self, index: libc::c_long) -> Result<(), glib::Error>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_align(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_ch(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_ch_off(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_rows(&self) -> Option<DOMHTMLCollection>; #[cfg_attr(feature = "v2_22", deprecated)] fn get_v_align(&self) -> Option<GString>; #[cfg_attr(feature = "v2_22", deprecated)] fn insert_row(&self, index: libc::c_long) -> Result<DOMHTMLElement, glib::Error>; #[cfg_attr(feature = "v2_22", deprecated)] fn set_align(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_ch(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_ch_off(&self, value: &str); #[cfg_attr(feature = "v2_22", deprecated)] fn set_v_align(&self, value: &str); fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_ch_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_ch_off_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_rows_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_v_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<DOMHTMLTableSectionElement>> DOMHTMLTableSectionElementExt for O { fn delete_row(&self, index: libc::c_long) -> Result<(), glib::Error> { unsafe { let mut error = ptr::null_mut(); let _ = webkit2_webextension_sys::webkit_dom_html_table_section_element_delete_row( self.as_ref().to_glib_none().0, index, &mut error, ); if error.is_null() { Ok(()) } else { Err(from_glib_full(error)) } } } fn get_align(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_table_section_element_get_align( self.as_ref().to_glib_none().0, ), ) } } fn get_ch(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_table_section_element_get_ch( self.as_ref().to_glib_none().0, ), ) } } fn get_ch_off(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_table_section_element_get_ch_off( self.as_ref().to_glib_none().0, ), ) } } fn get_rows(&self) -> Option<DOMHTMLCollection> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_table_section_element_get_rows( self.as_ref().to_glib_none().0, ), ) } } fn get_v_align(&self) -> Option<GString> { unsafe { from_glib_full( webkit2_webextension_sys::webkit_dom_html_table_section_element_get_v_align( self.as_ref().to_glib_none().0, ), ) } } fn insert_row(&self, index: libc::c_long) -> Result<DOMHTMLElement, glib::Error> { unsafe { let mut error = ptr::null_mut(); let ret = webkit2_webextension_sys::webkit_dom_html_table_section_element_insert_row( self.as_ref().to_glib_none().0, index, &mut error, ); if error.is_null() { Ok(from_glib_none(ret)) } else { Err(from_glib_full(error)) } } } fn set_align(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_table_section_element_set_align( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_ch(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_table_section_element_set_ch( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_ch_off(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_table_section_element_set_ch_off( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn set_v_align(&self, value: &str) { unsafe { webkit2_webextension_sys::webkit_dom_html_table_section_element_set_v_align( self.as_ref().to_glib_none().0, value.to_glib_none().0, ); } } fn connect_property_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_align_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLTableSectionElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLTableSectionElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::align\0".as_ptr() as *const _, Some(transmute(notify_align_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_ch_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_ch_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLTableSectionElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLTableSectionElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::ch\0".as_ptr() as *const _, Some(transmute(notify_ch_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_ch_off_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_ch_off_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLTableSectionElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLTableSectionElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::ch-off\0".as_ptr() as *const _, Some(transmute(notify_ch_off_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_rows_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_rows_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLTableSectionElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLTableSectionElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::rows\0".as_ptr() as *const _, Some(transmute(notify_rows_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } fn connect_property_v_align_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe extern "C" fn notify_v_align_trampoline<P, F: Fn(&P) + 'static>( this: *mut webkit2_webextension_sys::WebKitDOMHTMLTableSectionElement, _param_spec: glib_sys::gpointer, f: glib_sys::gpointer, ) where P: IsA<DOMHTMLTableSectionElement>, { let f: &F = &*(f as *const F); f(&DOMHTMLTableSectionElement::from_glib_borrow(this).unsafe_cast()) } unsafe { let f: Box_<F> = Box_::new(f); connect_raw( self.as_ptr() as *mut _, b"notify::v-align\0".as_ptr() as *const _, Some(transmute(notify_v_align_trampoline::<Self, F> as usize)), Box_::into_raw(f), ) } } } impl fmt::Display for DOMHTMLTableSectionElement { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "DOMHTMLTableSectionElement") } }
use crate::ast; use crate::{Parse, ParseError, Parser, Peeker, Spanned, Storage, ToTokens}; use runestick::Span; /// A literal value #[derive(Debug, Clone, PartialEq, Eq, ToTokens, Spanned)] pub enum Lit { /// A boolean literal Bool(ast::LitBool), /// A byte literal Byte(ast::LitByte), /// A string literal Str(ast::LitStr), /// A byte string literal ByteStr(ast::LitByteStr), /// A character literal Char(ast::LitChar), /// A number literal Number(ast::LitNumber), } impl Lit { /// Construct a new literal. /// /// # Panics /// /// This will panic if it's called outside of a macro context. pub fn new<T>(lit: T) -> Self where T: crate::macros::IntoLit, { crate::macros::current_context(|ctx| Self::new_with(lit, ctx.macro_span(), ctx.storage())) } /// Construct a new literal with the specified span and storage. /// /// This does not panic outside of a macro context, but requires access to /// the specified arguments. /// /// # Examples /// /// ```rust /// use rune::{ast, Storage}; /// use runestick::Span; /// /// let storage = Storage::default(); /// let string = ast::Lit::new_with("hello world", Span::empty(), &storage); /// ``` pub fn new_with<T>(lit: T, span: Span, storage: &Storage) -> Self where T: crate::macros::IntoLit, { T::into_lit(lit, span, storage) } /// Test if this is an immediate literal in an expression. /// /// Here we only test for unambiguous literals which will not be caused by /// a later stage as an expression is being parsed. /// /// These include: /// * Object literals that start with a path (handled in [ast::Expr::parse_with_meta_path]). /// * Tuple literals that start with a path (handled in [ast::Expr::parse_open_paren]). pub(crate) fn peek_in_expr(p: &mut Peeker<'_>) -> bool { match p.nth(0) { K![true] | K![false] => true, K![byte] => true, K![number] => true, K![char] => true, K![str] => true, K![bytestr] => true, _ => false, } } } /// Parsing a Lit /// /// # Examples /// /// ```rust /// use rune::{testing, ast}; /// /// testing::roundtrip::<ast::Lit>("true"); /// testing::roundtrip::<ast::Lit>("false"); /// testing::roundtrip::<ast::Lit>("'🔥'"); /// testing::roundtrip::<ast::Lit>("b'4'"); /// testing::roundtrip::<ast::Lit>("b\"bytes\""); /// testing::roundtrip::<ast::Lit>("1.2"); /// testing::roundtrip::<ast::Lit>("42"); /// testing::roundtrip::<ast::Lit>("\"mary had a little lamb\""); /// ``` impl Parse for Lit { fn parse(p: &mut Parser<'_>) -> Result<Self, ParseError> { match p.nth(0)? { K![true] | K![false] => return Ok(Lit::Bool(p.parse()?)), K![byte(_)] => return Ok(Lit::Byte(p.parse()?)), K![number(_)] => return Ok(Lit::Number(p.parse()?)), K![char(_)] => return Ok(Lit::Char(p.parse()?)), K![str(_)] => return Ok(Lit::Str(p.parse()?)), K![bytestr(_)] => return Ok(Lit::ByteStr(p.parse()?)), _ => (), } Err(ParseError::expected( &p.next()?, r#"expected literal like `"Hello World"` or 42"#, )) } }
macro_rules! c_str { ($s:expr) => { concat!($s, "\0").as_ptr() as *const std::os::raw::c_char }; } /// Create a `SurfaceDescriptor` from a Winit `Window`. /// /// # Winit Note /// /// Winit is in the process of a major API refactor. If using winit `v0.19`, the `winit-eventloop-2` /// feature needs to be disabled. #[macro_export] macro_rules! winit_surface_descriptor { ($window:expr) => {{ #[cfg(target_os = "windows")] { #[cfg(feature = "winit-eventloop-2")] { use winit::platform::windows::WindowExtWindows; $crate::SurfaceDescriptorWin32 { hwnd: $window.hwnd() } } #[cfg(not(feature = "winit-eventloop-2"))] { use winit::os::windows::WindowExt; $crate::SurfaceDescriptorWin32 { hwnd: $window.get_hwnd(), } } } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] { #[cfg(feature = "winit-eventloop-2")] { use winit::platform::unix::WindowExtUnix; $crate::SurfaceDescriptorUnix { xlib_window: $window.xlib_window(), xlib_display: $window.xlib_display(), xcb_connection: $window.xcb_connection(), xcb_window: $window.xlib_window(), wayland_surface: $window.wayland_surface(), wayland_display: $window.wayland_display(), } } #[cfg(not(feature = "winit-eventloop-2"))] { use winit::os::unix::WindowExt; $crate::SurfaceDescriptorUnix { xlib_window: $window.get_xlib_window(), xlib_display: $window.get_xlib_display(), xcb_connection: $window.get_xcb_connection(), xcb_window: $window.get_xlib_window(), wayland_surface: $window.get_wayland_surface(), wayland_display: $window.get_wayland_display(), } } } #[cfg(all(unix, target_os = "macos"))] { #[cfg(feature = "winit-eventloop-2")] { use winit::platform::macos::WindowExtMacOS; $crate::SurfaceDescriptorMacOS { nsview: $window.ns_view(), } } #[cfg(not(feature = "winit-eventloop-2"))] { use winit::os::macos::WindowExt; $crate::SurfaceDescriptorMacOS { nsview: $window.get_nsview(), } } } }}; } /// Create a `SurfaceDescriptor` from a GLFW `Window`. /// /// # MacOS Note /// /// The `objc` crate must be added to `Cargo.toml` in addition to `glfw`. If compile errors /// arise on the `sel!` macro from the `objc` crate, try importing it with rust 2015 syntax: /// /// ``` /// #[cfg(target_os = "macos")] /// #[macro_use] /// extern crate objc; /// ``` #[macro_export] macro_rules! glfw_surface_descriptor ( ($window:expr) => {{ #[cfg(target_os = "windows")] { $crate::SurfaceDescriptorWin32 { hwnd: $window.get_win32_window() as _, } } #[cfg(all(unix, not(target_os = "android"), not(target_os = "macos")))] { let xlib_display = unsafe { glfw::ffi::glfwGetX11Display() }; $crate::SurfaceDescriptorUnix { xlib_window: Some($window.get_x11_window() as _), xlib_display: Some(xlib_display as _), xcb_connection: None, xcb_window: None, wayland_surface: None, wayland_display: None, } } #[cfg(all(unix, target_os = "macos"))] { // https://stackoverflow.com/questions/7566882/how-to-get-current-nsview-in-cocoa // TODO: Verify that this works! unsafe { let ns_window: *mut objc::runtime::Object = $window.get_cocoa_window() as *mut _; assert_ne!(ns_window, std::ptr::null_mut()); let ns_view: *mut objc::runtime::Object = objc::msg_send![ns_window, contentView]; assert_ne!(ns_view, std::ptr::null_mut()); $crate::SurfaceDescriptorMacOS { nsview: ns_view as *const _, } } } }}; );
use crate::module::ModuleManifest; use game_lib::{ anyhow::{anyhow, bail, Context}, bevy::utils::{HashMap, HashSet}, }; use std::{ fmt::{Debug, Formatter}, fs::File, io::BufReader, path::{Path, PathBuf}, }; use wasmer::{ import_namespace, ExportError, Instance, Memory, MemoryType, Module, Pages, Store, Val, }; use wasmer_wasi::WasiState; #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct ModuleInfo { pub manifest: ModuleManifest, pub entry_dir: PathBuf, pub entry_path: PathBuf, pub data_path: PathBuf, } #[derive(Clone)] struct ActiveModule { info: ModuleInfo, instance: Instance, } impl Debug for ActiveModule { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("ActiveModule") .field("info", &self.info) .finish() } } pub struct WasmRunner { shared_memory: Memory, active_modules: HashMap<String, ActiveModule>, } impl WasmRunner { pub fn new(bin_path: &Path) -> game_lib::anyhow::Result<Self> { let mod_path: PathBuf = [bin_path, Path::new("mods")].iter().collect(); let mod_data_path: PathBuf = [bin_path, Path::new("mod_data")].iter().collect(); // Find modules let mut modules = HashMap::default(); for dir in mod_path.read_dir()? { let dir = dir?; let dir_path = dir.path(); // Load manifest let manifest_path: PathBuf = { let mut path = dir_path.clone(); path.push("manifest.json"); path }; let manifest_file = File::open(manifest_path)?; let manifest: ModuleManifest = game_lib::serde_json::from_reader(BufReader::new(manifest_file))?; // Verify entry module is in the same directory let entry_path: PathBuf = [&dir_path, &manifest.entry].iter().collect(); let entry_path = entry_path.canonicalize()?; let data_path: PathBuf = match entry_path.strip_prefix(&dir_path) { Ok(remainder) => [&mod_data_path, remainder].iter().collect(), Err(_) => { bail!( "entry for {} must be contained in its directory ({})", manifest.id, dir_path.display() ) } }; modules.insert( manifest.id.clone(), ModuleInfo { manifest, entry_dir: dir_path, entry_path, data_path, }, ); } let mut load_order = Vec::new(); let mut sorted = HashSet::default(); let mut unsorted: HashSet<_> = modules.keys().map(|s| s.as_str()).collect(); while !unsorted.is_empty() { let next = unsorted .iter() .find_map(|&id| { modules.get(id).filter(|info| { info.manifest .dependencies .iter() .all(|dependency| sorted.contains(dependency.id.as_str())) }) }) .ok_or_else(|| anyhow!("could not resolve module load order"))?; unsorted.remove(next.manifest.id.as_str()); sorted.insert(next.manifest.id.as_str()); load_order.push(next); } // Load modules // TODO: make this multithreaded let store = Store::default(); let shared_memory = Memory::new(&store, MemoryType::new(Pages(1024), None, true)) .context("failure creating shared memory for modules")?; let active_modules = HashMap::default(); for module_info in load_order { let entry_bytes = std::fs::read(&module_info.entry_path)?; let module = Module::new(&store, &entry_bytes)?; let mut wasi_env = WasiState::new("mod_core") .preopen(|p| { p.directory(&module_info.entry_dir) .read(true) .write(false) .create(false) .alias("/mod") })? .preopen(|p| { p.directory(&module_info.data_path) .read(true) .write(true) .create(true) .alias("/data") })? .env("PWD", "/") .finalize()?; let mut imports = wasi_env.import_object(&module)?; let env_namespace = import_namespace! { { "memory" => shared_memory.clone(), } }; imports.register("env", env_namespace); let instance = Instance::new(&module, &imports)?; // Call _start function by convention if let Ok(function) = instance.exports.get_native_function::<(), ()>("_start") { function.call()?; } } Ok(WasmRunner { shared_memory, active_modules, }) } pub fn on_update(&mut self, params: &[Val]) -> game_lib::anyhow::Result<()> { self.call_all_if_exists("on_update", params) .into_iter() .map(|(_, result)| result.map(|_| ())) .collect() } pub fn call_all_if_exists( &mut self, function_name: &str, params: &[Val], ) -> HashMap<&ModuleInfo, game_lib::anyhow::Result<Option<Box<[Val]>>>> { self.active_modules .iter() .map(|(_id, active_module)| { let result = match active_module.instance.exports.get_function(function_name) { Ok(function) => function .call(params) .context("error during function execution") .map(|result| Some(result)), Err(ExportError::Missing(_)) => Ok(None), Err(error) => Err(error).context("error getting exported function"), }; (&active_module.info, result) }) .collect() } }
use crate::decode::Decode; use crate::encode::{Encode, IsNull}; use crate::io::{Buf, BufMut}; use crate::postgres::types::raw::sequence::PgSequenceDecoder; use crate::postgres::{PgData, PgRawBuffer, PgValue, Postgres}; use crate::types::Type; use byteorder::BE; use std::marker::PhantomData; // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/include/utils/array.h;h=7f7e744cb12bc872f628f90dad99dfdf074eb314;hb=master#l6 // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/adt/arrayfuncs.c;h=7a4a5aaa86dc1c8cffa2d899c89511dc317d485b;hb=master#l1547 pub(crate) struct PgArrayEncoder<'enc, T> { count: usize, len_start_index: usize, buf: &'enc mut PgRawBuffer, phantom: PhantomData<T>, } impl<'enc, T> PgArrayEncoder<'enc, T> where T: Encode<Postgres> + Type<Postgres>, { pub(crate) fn new(buf: &'enc mut PgRawBuffer) -> Self { let ty = <T as Type<Postgres>>::type_info(); // ndim buf.put_i32::<BE>(1); // dataoffset buf.put_i32::<BE>(0); // [elemtype] element type OID if let Some(oid) = ty.id { // write oid buf.extend(&oid.0.to_be_bytes()); } else { // write hole for this oid buf.push_type_hole(&ty.name); } let len_start_index = buf.len(); // dimensions buf.put_i32::<BE>(0); // lower_bnds buf.put_i32::<BE>(1); Self { count: 0, len_start_index, buf, phantom: PhantomData, } } pub(crate) fn encode(&mut self, item: T) { // Allocate space for the length of the encoded elemement up front let el_len_index = self.buf.len(); self.buf.put_i32::<BE>(0); // Allocate and encode the element it self let el_start = self.buf.len(); if let IsNull::Yes = Encode::<Postgres>::encode_nullable(&item, self.buf) { self.buf[el_len_index..el_start].copy_from_slice(&(-1_i32).to_be_bytes()); } else { let el_end = self.buf.len(); // Now we know the actual length of the encoded element let el_len = el_end - el_start; // And we can now go back and update the length self.buf[el_len_index..el_start].copy_from_slice(&(el_len as i32).to_be_bytes()); } self.count += 1; } pub(crate) fn finish(&mut self) { const I32_SIZE: usize = std::mem::size_of::<i32>(); let size_bytes = (self.count as i32).to_be_bytes(); self.buf[self.len_start_index..self.len_start_index + I32_SIZE] .copy_from_slice(&size_bytes); } } pub(crate) struct PgArrayDecoder<'de, T> { inner: PgSequenceDecoder<'de>, phantom: PhantomData<T>, } impl<'de, T> PgArrayDecoder<'de, T> where T: for<'arr> Decode<'arr, Postgres>, T: Type<Postgres>, { pub(crate) fn new(value: PgValue<'de>) -> crate::Result<Self> { let mut data = value.try_get()?; let element_oid = match data { PgData::Binary(ref mut buf) => { // number of dimensions of the array let ndim = buf.get_i32::<BE>()?; if ndim == 0 { // ndim of 0 is an empty array return Ok(Self { inner: PgSequenceDecoder::new(PgData::Binary(&[]), None), phantom: PhantomData, }); } if ndim != 1 { return Err(decode_err!( "encountered an array of {} dimensions; only one-dimensional arrays are supported", ndim )); } // offset to stored data // this doesn't matter as the data is always at the end of the header let _dataoffset = buf.get_i32::<BE>()?; // element type OID let element_oid = buf.get_u32::<BE>()?; // length of each array axis let _dimensions = buf.get_i32::<BE>()?; // lower boundary of each dimension let lower_bnds = buf.get_i32::<BE>()?; if lower_bnds != 1 { return Err(decode_err!( "encountered an array with a lower bound of {} in the first dimension; only arrays starting at one are supported", lower_bnds )); } Some(element_oid) } PgData::Text(_) => None, }; Ok(Self { inner: PgSequenceDecoder::new(data, element_oid), phantom: PhantomData, }) } fn decode(&mut self) -> crate::Result<Option<T>> { self.inner.decode() } } impl<'de, T> Iterator for PgArrayDecoder<'de, T> where T: for<'arr> Decode<'arr, Postgres>, T: Type<Postgres>, { type Item = crate::Result<T>; #[inline] fn next(&mut self) -> Option<crate::Result<T>> { self.decode().transpose() } } #[cfg(test)] mod tests { use super::PgArrayDecoder; use super::PgArrayEncoder; use crate::postgres::{PgRawBuffer, PgValue}; const BUF_BINARY_I32: &[u8] = b"\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x17\x00\x00\x00\x04\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x01\x00\x00\x00\x04\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00\x03\x00\x00\x00\x04\x00\x00\x00\x04"; #[test] fn it_encodes_i32() { let mut buf = PgRawBuffer::default(); let mut encoder = PgArrayEncoder::new(&mut buf); for val in &[1_i32, 2, 3, 4] { encoder.encode(*val); } encoder.finish(); assert_eq!(&**buf, BUF_BINARY_I32); } #[test] fn it_decodes_text_i32() -> crate::Result<()> { let s = "{1,152,-12412}"; let mut decoder = PgArrayDecoder::<i32>::new(PgValue::from_str(s))?; assert_eq!(decoder.decode()?, Some(1)); assert_eq!(decoder.decode()?, Some(152)); assert_eq!(decoder.decode()?, Some(-12412)); assert_eq!(decoder.decode()?, None); Ok(()) } #[test] fn it_decodes_text_str() -> crate::Result<()> { let s = "{\"\",\"\\\"\"}"; let mut decoder = PgArrayDecoder::<String>::new(PgValue::from_str(s))?; assert_eq!(decoder.decode()?, Some("".to_string())); assert_eq!(decoder.decode()?, Some("\"".to_string())); assert_eq!(decoder.decode()?, None); Ok(()) } #[test] fn it_decodes_binary_nulls() -> crate::Result<()> { let mut decoder = PgArrayDecoder::<Option<bool>>::new(PgValue::from_bytes( b"\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x10\x00\x00\x00\x04\x00\x00\x00\x01\xff\xff\xff\xff\x00\x00\x00\x01\x01\xff\xff\xff\xff\x00\x00\x00\x01\x00", ))?; assert_eq!(decoder.decode()?, Some(None)); assert_eq!(decoder.decode()?, Some(Some(true))); assert_eq!(decoder.decode()?, Some(None)); assert_eq!(decoder.decode()?, Some(Some(false))); Ok(()) } #[test] fn it_decodes_binary_i32() -> crate::Result<()> { let mut decoder = PgArrayDecoder::<i32>::new(PgValue::from_bytes(BUF_BINARY_I32))?; let val_1 = decoder.decode()?; let val_2 = decoder.decode()?; let val_3 = decoder.decode()?; let val_4 = decoder.decode()?; assert_eq!(val_1, Some(1)); assert_eq!(val_2, Some(2)); assert_eq!(val_3, Some(3)); assert_eq!(val_4, Some(4)); assert!(decoder.decode()?.is_none()); Ok(()) } }
use rust_gpu_tools::{cuda, opencl, program_closures, Device, GPUError, Program}; /// Returns a `Program` that runs on CUDA. fn cuda(device: &Device) -> Program { // The kernel was compiled with: // nvcc -fatbin -gencode=arch=compute_52,code=sm_52 -gencode=arch=compute_60,code=sm_60 -gencode=arch=compute_61,code=sm_61 -gencode=arch=compute_70,code=sm_70 -gencode=arch=compute_75,code=sm_75 -gencode=arch=compute_75,code=compute_75 --x cu add.cl let cuda_kernel = include_bytes!("./add.fatbin"); let cuda_device = device.cuda_device().unwrap(); let cuda_program = cuda::Program::from_bytes(cuda_device, cuda_kernel).unwrap(); Program::Cuda(cuda_program) } /// Returns a `Program` that runs on OpenCL. fn opencl(device: &Device) -> Program { let opencl_kernel = include_str!("./add.cl"); let opencl_device = device.opencl_device().unwrap(); let opencl_program = opencl::Program::from_opencl(opencl_device, opencl_kernel).unwrap(); Program::Opencl(opencl_program) } pub fn main() { // Define some data that should be operated on. let aa: Vec<u32> = vec![1, 2, 3, 4]; let bb: Vec<u32> = vec![5, 6, 7, 8]; // This is the core. Here we write the interaction with the GPU independent of whether it is // CUDA or OpenCL. let closures = program_closures!(|program, _args| -> Result<Vec<u32>, GPUError> { // Make sure the input data has the same length. assert_eq!(aa.len(), bb.len()); let length = aa.len(); // Copy the data to the GPU. let aa_buffer = program.create_buffer_from_slice(&aa)?; let bb_buffer = program.create_buffer_from_slice(&bb)?; // The result buffer has the same length as the input buffers. let result_buffer = unsafe { program.create_buffer::<u32>(length)? }; // Get the kernel. let kernel = program.create_kernel("add", 8, 4)?; // Execute the kernel. kernel .arg(&(length as u32)) .arg(&aa_buffer) .arg(&bb_buffer) .arg(&result_buffer) .run()?; // Get the resulting data. let mut result = vec![0u32; length]; program.read_into_buffer(&result_buffer, &mut result)?; Ok(result) }); // Get the first available device. let device = *Device::all().first().unwrap(); // First we run it on CUDA. let cuda_program = cuda(&device); let cuda_result = cuda_program.run(closures, ()).unwrap(); assert_eq!(cuda_result, [6, 8, 10, 12]); println!("CUDA result: {:?}", cuda_result); // Then we run it on OpenCL. let opencl_program = opencl(&device); let opencl_result = opencl_program.run(closures, ()).unwrap(); assert_eq!(cuda_result, [6, 8, 10, 12]); println!("OpenCL result: {:?}", opencl_result); }
use std::collections::BTreeMap; use std::sync::{Arc, RwLock}; use std::net::{SocketAddr,IpAddr,Ipv4Addr}; use std::error::Error; use std::thread; use mio::{EventLoop,EventLoopConfig, Sender, Handler}; use eventual::Async; use util; use def::*; use def::TopologyChangeType::*; use def::StatusChangeType::*; use def::CqlResponseBody::*; use def::CqlValue::*; use std::time::Duration; use node::Node; use connection_pool::ConnectionPool; use connection::CqlMsg; use std::convert::AsRef; use std::rc::Rc; use std::boxed::Box; use std::cell::RefCell; use load_balancing::*; use error::*; use error::RCErrorType::*; use std::sync::mpsc; type ArcMap = Arc<RwLock<BTreeMap<IpAddr,Node>>>; pub struct Cluster{ // Index of the current_node we are using current_node: Arc<RwLock<IpAddr>>, available_nodes: ArcMap, unavailable_nodes: ArcMap, channel_cpool: Sender<CqlMsg>, // https://doc.rust-lang.org/error-index.html#E0038 balancer: Arc<RwLock<LoadBalancing+Send+Sync>>, balancer_sender: mpsc::Sender<()> } impl Cluster { pub fn new() -> Cluster{ let availables = Arc::new(RwLock::new(BTreeMap::new())); let unavailables = Arc::new(RwLock::new(BTreeMap::new())); //Start EventLoop<ConnectionPool> let mut config = EventLoopConfig::new(); config.notify_capacity(65_536) .messages_per_tick(1_024) //.timer_tick(Duration::from_millis(100)) .timer_wheel_size(1_024) .timer_capacity(65_536); let mut event_loop_conn_pool : EventLoop<ConnectionPool> = EventLoop::configured(config.clone()).ok().expect("Couldn't create event loop"); let mut channel_cpool= event_loop_conn_pool.channel(); let balancer = Arc::new(RwLock::new(RoundRobin{index:0})); let current_node = Arc::new(RwLock::new(IpAddr::V4(Ipv4Addr::new(0,0,0,0)))); //Start EventLoop<EventHandler> let mut event_loop : EventLoop<EventHandler> = EventLoop::configured(config).ok().expect("Couldn't create event loop"); let event_handler_channel = event_loop.channel(); let mut event_handler = EventHandler::new( availables.clone(), unavailables.clone(), channel_cpool.clone(), current_node.clone()); // Only keep the event loop channel thread::Builder::new().name("event_handler".to_string()).spawn(move || { event_loop.run(&mut event_handler).ok().expect("Failed to start event loop"); }); // We will need the event loop to register a new socket // but on creating the thread we borrow the even_loop. // So we 'give away' the connection pool and keep the channel. let mut connection_pool = ConnectionPool::new(event_handler_channel); //println!("Starting event loop..."); // Only keep the event loop channel thread::Builder::new().name("connection_pool".to_string()).spawn(move || { event_loop_conn_pool.run(&mut connection_pool).ok().expect("Failed to start event loop"); }); Cluster{ available_nodes: availables.clone(), unavailable_nodes: unavailables.clone(), channel_cpool: channel_cpool, current_node: Arc::new(RwLock::new(IpAddr::V4(Ipv4Addr::new(0,0,0,0)))), balancer: balancer, balancer_sender: mpsc::channel().0 } } fn start_load_balancing(&mut self,duration:Duration){ let availables = self.available_nodes.clone(); let current_node = self.current_node.clone(); let balancer = self.balancer.clone(); let tx = util::set_interval(duration,move || { //println!("set_interval"); let mut node = current_node.write().unwrap(); *node = balancer.write().unwrap().select_node(&availables.read().unwrap()); }); self.balancer_sender = tx; } pub fn set_load_balancing(&mut self,balancer: BalancerType,duration: Duration){ //Stop load balancer thread sending a '()' message self.balancer_sender.send(()); match balancer{ BalancerType::RoundRobin => self.balancer = Arc::new(RwLock::new(RoundRobin{index:0})), BalancerType::LatencyAware => self.balancer = Arc::new(RwLock::new(LatencyAware)), } self.start_load_balancing(duration); } pub fn are_available_nodes(&self) -> bool{ self.available_nodes.read() .unwrap() .len() == 0 } fn add_node(&self,ip: IpAddr) -> RCResult<CqlResponse>{ let address = SocketAddr::new(ip,CQL_DEFAULT_PORT); let mut node = Node::new(address,self.channel_cpool.clone()); node.set_channel_cpool(self.channel_cpool.clone()); let response = { try_unwrap!(node.connect().await()) }; match response { Ok(_) => { try_unwrap!(self.available_nodes.write()) .insert(address.ip(),node); } Err(_) =>{ try_unwrap!(self.unavailable_nodes.write()) .insert(address.ip(),node); } } response } // This operation blocks pub fn connect_cluster(&mut self,address: SocketAddr) -> RCResult<CqlResponse>{ // No avaiables nodes make sure that 'tick' thread is not writing if self.are_available_nodes(){ { let mut node = self.current_node.write().unwrap(); *node = address.ip(); } { self.start_load_balancing(Duration::from_secs(1)); } return self.create_and_register(); } else{ return Err(RCError::new("Already connected to cluster", ClusterError)) } } fn create_and_register(&mut self) -> RCResult<CqlResponse>{ let connect_response = self.add_node(self.current_node.read().unwrap().clone()); match connect_response{ Ok(_) => { //Register the connection to get Events from Cassandra try_unwrap!(try_unwrap!(self.register().await())); //Get the currrent nodes from a system query let peers = try_unwrap!(try_unwrap!(self.get_peers().await())); let ip_nodes = try_unwrap!(parse_nodes(peers)); self.create_nodes(ip_nodes); }, Err(_) =>{ () } } connect_response } fn create_nodes(&mut self,ips: Vec<IpAddr>){ for ip in ips { self.add_node(ip); } } pub fn get_peers(&mut self) -> CassFuture{ let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.get_peers() } pub fn exec_query(&mut self, query_str: &str, con: Consistency) -> CassFuture { let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.exec_query(query_str,con) } //This operation blocks pub fn prepared_statement(&mut self, query_str: &str) -> RCResult<CqlPreparedStat> { let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.prepared_statement(query_str) } pub fn exec_prepared(&mut self, preps: &Vec<u8>, params: &Vec<CqlValue>, con: Consistency) -> CassFuture{ let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.exec_prepared(preps,params,con) } pub fn exec_batch(&mut self, q_type: BatchType, q_vec: Vec<Query>, con: Consistency) -> CassFuture { let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.exec_batch(q_type,q_vec,con) } fn register(&mut self) -> CassFuture{ let map = self.available_nodes .read() .unwrap(); let node = map.get(&self.current_node.read().unwrap()) .unwrap(); node.send_register() } // This temporal until I return some type pub fn show_cluster_information(&self){ let map_availables = self.available_nodes .read() .unwrap(); let map_unavailables = self.unavailable_nodes .read() .unwrap(); println!("--------------Available nodes-----------"); println!("Address"); for node in map_availables.iter() { println!("{:?}\t",node.0); } println!("----------------------------------------"); println!("--------------Unavailable nodes---------"); println!("Address"); for node in map_unavailables.iter() { println!("{:?}\t",node.0); } println!("----------------------------------------"); println!("Current node: {:?}\n",self.current_node); println!("----------------------------------------\n"); //println!("Current balaning strategy: {}\n",self.balancer); //println!("----------------------------------------\n"); } } pub fn parse_nodes(response: CqlResponse) -> RCResult<Vec<IpAddr>>{ let mut nodes = Vec::new(); match response.body { ResultRows(cql_rows) => { if cql_rows.rows.len() > 0 { let rows = cql_rows.rows.clone(); for row in rows { //println!("Col: {:?}",row); match *row.cols.get(0).unwrap() { CqlInet(Some(ip)) => { nodes.push(ip); }, _ => return Err(RCError::new("Error CqlResponse contains no rows", ReadError)), } } Ok(nodes) } else{ Err(RCError::new("Error CqlResponse contains no rows", ReadError)) } }, _ => Err(RCError::new("Error CqlResponse type must be ResultRows", ClusterError)), } } struct EventHandler{ available_nodes: ArcMap, unavailable_nodes: ArcMap, channel_cpool: Sender<CqlMsg>, current_node: Arc<RwLock<IpAddr>> } impl EventHandler{ fn new(availables: ArcMap,unavailables: ArcMap,channel_cpool : Sender<CqlMsg>, current_node: Arc<RwLock<IpAddr>>) -> EventHandler{ EventHandler{ available_nodes: availables, unavailable_nodes: unavailables, channel_cpool: channel_cpool, current_node: current_node } } pub fn show_cluster_information(&self){ let map_availables = self.available_nodes .read() .unwrap(); let map_unavailables = self.unavailable_nodes .read() .unwrap(); println!("EventHandler::show_cluster_information"); println!("--------------Available nodes-----------"); println!("Address"); for node in map_availables.iter() { println!("{:?}\t",node.0); } println!("----------------------------------------"); println!("--------------Unavailable nodes---------"); println!("Address"); for node in map_unavailables.iter() { println!("{:?}\t",node.0); } println!("----------------------------------------"); } } impl Handler for EventHandler { type Timeout = (); type Message = CqlEvent; fn notify(&mut self, event_loop: &mut EventLoop<EventHandler>, msg: CqlEvent) { println!("EventHandler::notify"); match msg { CqlEvent::TopologyChange(change_type,socket_addr) =>{ let mut map = self.available_nodes .write() .ok().expect("Can't write in available_nodes"); match change_type{ NewNode =>{ map.insert(socket_addr.ip(), Node::new(socket_addr,self.channel_cpool.clone())); }, RemovedNode =>{ map.remove(&socket_addr.ip()); }, MovedNode =>{ //Not sure about this. map.insert(socket_addr.ip(), Node::new(socket_addr,self.channel_cpool.clone())); }, Unknown => () } }, CqlEvent::StatusChange(change_type,socket_addr) =>{ //Need for a unavailable_nodes list (down) let mut map_unavailable = self.unavailable_nodes .write() .ok().expect("Can't write in unavailable_nodes"); let mut map_available = self.available_nodes .write() .ok().expect("Can't write in unavailable_nodes"); match change_type{ Up =>{ //To-do: treat error if node doesn't exist let result_node = map_unavailable.remove(&socket_addr.ip()); match result_node { Some(node) => { map_available.insert(node.get_sock_addr().ip(),node); }, None => println!("Node with ip {:?} wasn't found in unavailable_nodes",&socket_addr.ip()), } }, Down =>{ //To-do: treat error if node doesn't exist let result_node = map_available.remove(&socket_addr.ip()); match result_node { Some(node) => { map_unavailable.insert(node.get_sock_addr().ip(),node); }, None => println!("Node with ip {:?} wasn't found in available_nodes",&socket_addr.ip()), } }, UnknownStatus => () } }, CqlEvent::SchemaChange(change_type,socket_addr) =>{ println!("Schema changes are not supported yet"); }, CqlEvent::UnknownEvent=> { println!("We've got an UnkownEvent"); } } } }
#[macro_export] macro_rules! impl_error_group { //( $name:ident { $( $x:ident : $y:path ),* } ) | ( enum $name:ident { $( $kind:ident ( $kind_type:path $( , $desc:expr )* ) ),* $(,)* } ) => { #[derive(Debug)] enum $name { $( $kind($kind_type), )* } impl ::std::error::Error for $name { fn description(&self) -> &str { match self { $( &$name::$kind(ref e) => ::std::error::Error::description(e), )* } } fn cause(&self) -> Option<&::std::error::Error> { match self { $( &$name::$kind(ref e) => return Some(e), )* } } } impl ::std::fmt::Display for $name { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { match self { $( &$name::$kind(ref err) => write!(f, concat!($( $desc, ": ", )* "{}"), err), )* } } } $( impl From<$kind_type> for $name { fn from(error: $kind_type) -> Self { $name::$kind(error) } } )* } }
use std::fmt::{Debug, Display}; use crate::arguments::Arguments; use crate::connection::Connect; use crate::cursor::HasCursor; use crate::error::DatabaseError; use crate::row::HasRow; use crate::types::TypeInfo; use crate::value::HasRawValue; /// A database driver. /// /// This trait encapsulates a complete driver implementation to a specific /// database (e.g., **MySQL**, **Postgres**). pub trait Database where Self: Debug + Sized + Send + 'static, Self: for<'c> HasRow<'c, Database = Self>, Self: for<'c> HasRawValue<'c, Database = Self>, Self: for<'c, 'q> HasCursor<'c, 'q, Database = Self>, { /// The concrete `Connection` implementation for this database. type Connection: Connect<Database = Self>; /// The concrete `Arguments` implementation for this database. type Arguments: Arguments<Database = Self>; /// The concrete `TypeInfo` implementation for this database. type TypeInfo: TypeInfo; /// The Rust type of table identifiers for this database. type TableId: Display + Clone; /// The Rust type used as the buffer when encoding arguments. /// /// For example, **Postgres** and **MySQL** use `Vec<u8>`; /// however, **SQLite** uses `Vec<SqliteArgumentValue>`. type RawBuffer: Default; /// The concrete `DatabaseError` type used to report errors from the database. type Error: DatabaseError + Send + Sync; }
use crate::api::v1::ceo::auth::model::{Login, New, QueryUser, SlimUser, User}; use crate::errors::ServiceError; use crate::models::msg::Msg; use crate::models::shop::Shop; use crate::models::DbExecutor; use actix::Handler; use diesel; use diesel::prelude::*; use diesel::sql_query; use serde_json::json; // register/signup user // handle msg from api::auth.signup impl Handler<New> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: New, _: &mut Self::Context) -> Self::Result { use crate::schema::user::dsl::*; let conn = &self.0.get()?; let check_user = user .filter(&account_id.eq(&msg.account_id)) .load::<User>(conn)? .pop(); match check_user { Some(_) => Err(ServiceError::BadRequest("중복".into())), None => { let s = r#"INSERT INTO "user" ( account_id,account_password, email, name, role) VALUES "#; let s2 = s.to_string() + "(" + "'" + &msg.account_id + "'" + "," + "crypt(" + "'" + &msg.account_password + "'" + ", gen_salt('bf'))" + "," + "'" + &msg.email + "'" + "," + "'" + &msg.name + "'" + "," + "'" + &msg.role + "'" + ")"; let res = sql_query(s2).execute(conn)?; let payload = json!({ "res": res, }); Ok(Msg { status: 200, data: payload, }) } } } } impl Handler<Login> for DbExecutor { type Result = Result<SlimUser, ServiceError>; fn handle(&mut self, msg: Login, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let s = r#"SELECT * FROM "user" WHERE account_password = "#; let s2 = s.to_string() + "crypt(" + "'" + &msg.password + "'" + ", account_password)"; let s2 = s2.to_string() + " AND account_id = " + "'" + &msg.id + "'"; let res: Option<User> = sql_query(s2).load::<User>(conn)?.pop(); match res { Some(u) => Ok(u.into()), None => Err(ServiceError::BadRequest("누구냐".into())), } } } impl Handler<QueryUser> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, uid: QueryUser, _: &mut Self::Context) -> Self::Result { use crate::schema::shop::dsl::{ceo_id, shop as s_tb}; use crate::schema::user::dsl::*; let conn = &self.0.get()?; let query_user = user.filter(&id.eq(&uid.id)).get_result::<User>(conn)?; let query_shop = s_tb.filter(&ceo_id.eq(&uid.id)).get_result::<Shop>(conn); let shop_info: Option<Shop> = match query_shop { Ok(s) => Some(s), Err(_e) => None, }; let payload = json!({ "user": query_user, "shop": shop_info, }); Ok(Msg { status: 200, data: payload, }) } }
use rust_blog::establish_connection; use rust_blog::models::User; use rust_blog::schema::users; use diesel::RunQueryDsl; fn main() { let connection = establish_connection(); let results: Vec<User> = users::table.get_results(&connection).unwrap(); results.into_iter().for_each(|user| println!("{:?}", user)); }
// #![deny(unsafe_code)] // #![deny(warnings)] #![no_main] #![no_std] extern crate cortex_m as cm; extern crate cortex_m_rt as rt; extern crate panic_itm; extern crate stm32f1xx_hal as hal; // #[macro_use(block)] extern crate nb; use nb::block; use cm::iprintln; use hal::prelude::*; use hal::{ delay::Delay, serial::{self, Serial}, stm32, }; use rt::entry; #[entry] fn main() -> ! { // Get control of the PC13 pin let device_peripherals = stm32::Peripherals::take().unwrap(); let cortex_peripherals = cortex_m::Peripherals::take().unwrap(); let mut rcc = device_peripherals.RCC.constrain(); let mut flash = device_peripherals.FLASH.constrain(); let clocks = rcc.cfgr.freeze(&mut flash.acr); let mut gpioa = device_peripherals.GPIOA.split(&mut rcc.apb2); let mut gpioc = device_peripherals.GPIOC.split(&mut rcc.apb2); // // Won't work without a USB adapter, see: // // https://blog.japaric.io/itm/ // let mut itm = cortex_peripherals.ITM; // Prepare the alternate function I/O registers let mut afio = device_peripherals.AFIO.constrain(&mut rcc.apb2); // USART1 let tx = gpioa.pa9.into_alternate_push_pull(&mut gpioa.crh); let rx = gpioa.pa10; //let serial = Serial::usart1( //device_peripherals.USART1, //(tx, rx), //&mut afio.mapr, //serial::Config::default() //.baudrate(9600.bps()) //.stopbits(serial::StopBits::STOP2) //.parity_odd(), //clocks, //&mut rcc.apb2, //); let serial = Serial::usart1( device_peripherals.USART1, (tx, rx), &mut afio.mapr, 9600.bps(), clocks, &mut rcc.apb2, ); // Split the serial struct into a receiving and a transmitting part let (mut tx, _rx) = serial.split(); let mut led = gpioc.pc13.into_push_pull_output(&mut gpioc.crh); let half_period = 100_u16; let mut delay = Delay::new(cortex_peripherals.SYST, clocks); // We can only send byte per byte with the serial let sent = b'U'; loop { led.set_high(); delay.delay_ms(half_period); led.set_low(); delay.delay_ms(half_period); // block!(tx.write(sent)).ok(); tx.write(sent).ok(); } }
#[macro_use] extern crate honggfuzz; extern crate orion; extern crate ring; pub mod utils; use orion::hazardous::constants::SHA512_OUTSIZE; use orion::hazardous::kdf::{hkdf, pbkdf2}; use utils::{make_seeded_rng, ChaChaRng, RngCore}; fn fuzz_hkdf(fuzzer_input: &[u8], seeded_rng: &mut ChaChaRng) { let mut ikm = vec![0u8; fuzzer_input.len() / 2]; seeded_rng.fill_bytes(&mut ikm); let mut salt = vec![0u8; fuzzer_input.len() / 4]; seeded_rng.fill_bytes(&mut salt); let mut orion_okm: Vec<u8> = if (fuzzer_input.len() / 2) > (255 * SHA512_OUTSIZE) || (fuzzer_input.len() / 2) < 1 { vec![0u8; 256] } else { vec![0u8; fuzzer_input.len() / 2] }; let mut other_okm = orion_okm.clone(); // Empty info will be the same as None. let info: Vec<u8> = if fuzzer_input.is_empty() { vec![0u8; 0] } else { vec![0u8; fuzzer_input[0] as usize] }; // orion let orion_prk = hkdf::extract(&salt, &ikm).unwrap(); hkdf::expand(&orion_prk, Some(&info), &mut orion_okm).unwrap(); // ring let other_salt = ring::hmac::SigningKey::new(&ring::digest::SHA512, &salt); let other_prk = ring::hkdf::extract(&other_salt, &ikm); ring::hkdf::expand(&other_prk, &info, &mut other_okm[..]); // We cannot compare PRKs because ring's SigningKey does not offer // access to internal bytes. assert_eq!(orion_okm, other_okm); // Test extract-then-expand combination hkdf::derive_key(&salt, &ikm, Some(&info), &mut orion_okm).unwrap(); ring::hkdf::extract_and_expand(&other_salt, &ikm, &info, &mut other_okm); assert_eq!(orion_okm, other_okm); } fn fuzz_pbkdf2(fuzzer_input: &[u8], seeded_rng: &mut ChaChaRng) { let mut password = vec![0u8; fuzzer_input.len() / 2]; seeded_rng.fill_bytes(&mut password); let mut salt = vec![0u8; fuzzer_input.len() / 4]; seeded_rng.fill_bytes(&mut salt); // Cast to u16 so we don't have too many blocks to process. let dk_length = seeded_rng.next_u32() as u16; let mut orion_dk: Vec<u8> = if dk_length == 0 { vec![0u8; 64] } else { vec![0u8; dk_length as usize] }; let mut other_dk = orion_dk.clone(); // Cast to u16 so we don't have too many iterations. let mut iterations = seeded_rng.next_u32() as u16; if iterations == 0 { iterations = 1; } // orion let orion_password = pbkdf2::Password::from_slice(&password).unwrap(); pbkdf2::derive_key(&orion_password, &salt, iterations as usize, &mut orion_dk).unwrap(); // ring ring::pbkdf2::derive( &ring::digest::SHA512, std::num::NonZeroU32::new(u32::from(iterations)).unwrap(), &salt, &password, &mut other_dk, ); assert_eq!(orion_dk, other_dk); } fn main() { loop { fuzz!(|data: &[u8]| { // Seed the RNG let mut seeded_rng = make_seeded_rng(data); // Test `orion::hazardous::kdf::hkdf` fuzz_hkdf(data, &mut seeded_rng); // Test `orion::hazardous::kdf::pbkdf2` fuzz_pbkdf2(data, &mut seeded_rng); }); } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type CoreFrameworkInputView = *mut ::core::ffi::c_void; pub type CoreFrameworkInputViewAnimationStartingEventArgs = *mut ::core::ffi::c_void; pub type CoreFrameworkInputViewOcclusionsChangedEventArgs = *mut ::core::ffi::c_void; pub type CoreInputView = *mut ::core::ffi::c_void; pub type CoreInputViewAnimationStartingEventArgs = *mut ::core::ffi::c_void; pub type CoreInputViewHidingEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CoreInputViewKind(pub i32); impl CoreInputViewKind { pub const Default: Self = Self(0i32); pub const Keyboard: Self = Self(1i32); pub const Handwriting: Self = Self(2i32); pub const Emoji: Self = Self(3i32); pub const Symbols: Self = Self(4i32); pub const Clipboard: Self = Self(5i32); pub const Dictation: Self = Self(6i32); } impl ::core::marker::Copy for CoreInputViewKind {} impl ::core::clone::Clone for CoreInputViewKind { fn clone(&self) -> Self { *self } } pub type CoreInputViewOcclusion = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CoreInputViewOcclusionKind(pub i32); impl CoreInputViewOcclusionKind { pub const Docked: Self = Self(0i32); pub const Floating: Self = Self(1i32); pub const Overlay: Self = Self(2i32); } impl ::core::marker::Copy for CoreInputViewOcclusionKind {} impl ::core::clone::Clone for CoreInputViewOcclusionKind { fn clone(&self) -> Self { *self } } pub type CoreInputViewOcclusionsChangedEventArgs = *mut ::core::ffi::c_void; pub type CoreInputViewShowingEventArgs = *mut ::core::ffi::c_void; pub type CoreInputViewTransferringXYFocusEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct CoreInputViewXYFocusTransferDirection(pub i32); impl CoreInputViewXYFocusTransferDirection { pub const Up: Self = Self(0i32); pub const Right: Self = Self(1i32); pub const Down: Self = Self(2i32); pub const Left: Self = Self(3i32); } impl ::core::marker::Copy for CoreInputViewXYFocusTransferDirection {} impl ::core::clone::Clone for CoreInputViewXYFocusTransferDirection { fn clone(&self) -> Self { *self } } pub type UISettingsController = *mut ::core::ffi::c_void;
#![allow(non_snake_case)] //! https://github.com/lumen/otp/tree/lumen/lib/xmerl/src use super::*; test_compiles_lumen_otp!(xmerl); test_compiles_lumen_otp!(xmerl_b64Bin_scan); test_compiles_lumen_otp!(xmerl_eventp); test_compiles_lumen_otp!(xmerl_html); test_compiles_lumen_otp!(xmerl_lib); test_compiles_lumen_otp!(xmerl_otpsgml imports "lib/xmerl/src/xmerl_lib"); test_compiles_lumen_otp!(xmerl_regexp); test_compiles_lumen_otp!(xmerl_sax_old_dom); test_compiles_lumen_otp!(xmerl_sax_parser); test_compiles_lumen_otp!(xmerl_sax_simple_dom); test_compiles_lumen_otp!(xmerl_scan); test_compiles_lumen_otp!(xmerl_sgml imports "lib/xmerl/src/xmerl_lib"); test_compiles_lumen_otp!(xmerl_simple); test_compiles_lumen_otp!(xmerl_text); test_compiles_lumen_otp!(xmerl_ucs); test_compiles_lumen_otp!(xmerl_uri); test_compiles_lumen_otp!(xmerl_validate); test_compiles_lumen_otp!(xmerl_xlate); test_compiles_lumen_otp!(xmerl_xml); test_compiles_lumen_otp!(xmerl_xpath); test_compiles_lumen_otp!(xmerl_xpath_lib); test_compiles_lumen_otp!(xmerl_xpath_pred); test_compiles_lumen_otp!(xmerl_xpath_scan); test_compiles_lumen_otp!(xmerl_xs); test_compiles_lumen_otp!(xmerl_xsd); test_compiles_lumen_otp!(xmerl_xsd_type); fn includes() -> Vec<&'static str> { let mut includes = super::includes(); includes.extend(vec!["lib/xmerl/include", "lib/xmerl/src"]); includes } fn relative_directory_path() -> PathBuf { super::relative_directory_path().join("xmerl/src") }
#[rustversion::stable] #[test] fn test_compile_errors() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/invalid_macro_args.rs"); t.compile_fail("tests/ui/invalid_property_args.rs"); t.compile_fail("tests/ui/invalid_pyclass_args.rs"); t.compile_fail("tests/ui/invalid_pymethod_names.rs"); t.compile_fail("tests/ui/invalid_pymethod_receiver.rs"); t.compile_fail("tests/ui/missing_clone.rs"); t.compile_fail("tests/ui/reject_generics.rs"); t.compile_fail("tests/ui/wrong_aspyref_lifetimes.rs"); skip_min_stable(&t); #[rustversion::since(1.43)] fn skip_min_stable(t: &trybuild::TestCases) { t.compile_fail("tests/ui/static_ref.rs"); } #[rustversion::before(1.43)] fn skip_min_stable(_t: &trybuild::TestCases) {} }
#![feature(transpose_result)] extern crate actix_web; extern crate cookie; extern crate downcast; extern crate env_logger; extern crate failure; #[macro_use] extern crate failure_derive; extern crate fst; extern crate handlebars; extern crate itertools; #[macro_use] extern crate log; extern crate pretty_bytes; extern crate serde; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate tantivy; extern crate url; mod debug; mod fields; mod reconstruct; mod space_usage; mod top_terms; use actix_web::App; use failure::Error; use tantivy::Index; use std::env; use std::sync::Arc; use tantivy::DocId; use actix_web::HttpRequest; use actix_web::server; use handlebars::Handlebars; use std::fs; use serde::Serialize; use actix_web::HttpResponse; use actix_web::Query; use actix_web::http; use pretty_bytes::converter::convert; use handlebars::Helper; use handlebars::RenderContext; use handlebars::RenderError; use tantivy::query::QueryParser; use tantivy::SegmentId; use tantivy::collector::Collector; use tantivy::SegmentReader; use std::collections::HashSet; use itertools::Itertools; use std::collections::HashMap; use tantivy::schema::Schema; use tantivy::query::BooleanQuery; use tantivy::query::Occur; use tantivy::query::TermQuery; use tantivy::Term; use tantivy::schema::Type; use tantivy::query::PhraseQuery; use tantivy::query::RangeQuery; use url::form_urlencoded; use fields::get_fields; use space_usage::space_usage; use top_terms::top_terms; use top_terms::TantivyValue; use reconstruct::reconstruct; use tantivy::query::AllQuery; use std::collections::Bound; use tantivy::Searcher; use tantivy::SegmentLocalId; use tantivy::query::Scorer; use tantivy::fastfield::DeleteBitSet; use reconstruct::handle_reconstruct; use debug::handle_debug; #[derive(Fail, Debug)] enum TantivyViewerError { #[fail(display="An error occurred in tantivy")] TantivyError(tantivy::Error), #[fail(display="Query parsing error occurred")] QueryParserError(tantivy::query::QueryParserError), #[fail(display="Error encountered while rendering page")] RenderingError(handlebars::RenderError), #[fail(display="Error encountered serializing json")] JsonSerializationError, #[fail(display="Could not find a segment with the given prefix")] SegmentNotFoundError, #[fail(display="Could not break down unknown query type")] UnknownQueryTypeError, } impl actix_web::error::ResponseError for TantivyViewerError { fn error_response(&self) -> HttpResponse { use TantivyViewerError::*; let status = match *self { TantivyError(_) | RenderingError(_) | JsonSerializationError | UnknownQueryTypeError => http::StatusCode::INTERNAL_SERVER_ERROR, QueryParserError(_) | SegmentNotFoundError => http::StatusCode::BAD_REQUEST, }; HttpResponse::Ok() .status(status) .body(format!("{}", self)) } } impl From<tantivy::Error> for TantivyViewerError { fn from(e: tantivy::Error) -> Self { TantivyViewerError::TantivyError(e) } } impl From<UnknownQueryTypeError> for TantivyViewerError { fn from(_: UnknownQueryTypeError) -> Self { TantivyViewerError::UnknownQueryTypeError } } #[derive(Serialize)] struct FieldData { name: String, } #[derive(Serialize)] struct IndexData { fields: Vec<FieldData>, segments: Vec<String>, num_fields: usize, total_usage: usize, } fn handle_index(req: HttpRequest<State>) -> Result<HttpResponse, TantivyViewerError> { let state = req.state(); let index = &state.index; let searcher = index.searcher(); let space_usage = searcher.space_usage(); let segments = index.searchable_segment_ids().map_err(TantivyViewerError::TantivyError)?; let fields: Vec<_> = index.schema().fields().iter().map(|x| FieldData { name: x.name().to_string() }).collect(); let num_fields = fields.len(); let data = IndexData { fields, segments: segments.into_iter().map(|x| x.short_uuid_string()).collect(), num_fields, total_usage: space_usage.total(), }; state.render_template("index", &data) } #[derive(Debug, Serialize)] struct FieldDetail { name: String, value_type: String, extra_options: String, } fn handle_field_details(req: HttpRequest<State>) -> Result<HttpResponse, TantivyViewerError> { let state = req.state(); let fields = get_fields(&state.index) .map_err(TantivyViewerError::TantivyError)?; let mut field_details = fields .fields .into_iter() .map(|(_k, v)| Ok(FieldDetail { name: v.name, value_type: format!("{:?}", v.value_type), extra_options: serde_json::to_string(&v.extra_options)? })) .collect::<Result<Vec<_>, std::io::Error>>() .map_err(|_e| TantivyViewerError::JsonSerializationError)?; field_details.sort_unstable_by_key(|x| x.name.clone()); state.render_template("field_details", &field_details) } fn handle_space_usage(req: HttpRequest<State>) -> Result<HttpResponse, TantivyViewerError> { let state = req.state(); let space_usage = space_usage(&state.index); state.render_template("space_usage", &space_usage) } fn get_identifying_fields<S>(req: &HttpRequest<S>) -> Vec<String> { let mut cookie_fields = Vec::new(); if let Ok(cookies) = req.cookies() { for cookie in cookies { if cookie.name() == "selected" { for value in cookie.value().split(",") { cookie_fields.push(value.to_string()); } } } } cookie_fields } #[derive(Serialize)] struct ConfigurationField { field: String, selected: bool, } fn handle_configure(req: HttpRequest<State>) -> Result<HttpResponse, TantivyViewerError> { let state = req.state(); let fields = get_fields(&state.index) .map_err(TantivyViewerError::TantivyError)?; let cookie_fields = get_identifying_fields(&req).into_iter().collect::<HashSet<String>>(); let fields = fields.fields .into_iter() .map(|(field,_v)| { let selected = cookie_fields.contains(&field); ConfigurationField { field, selected, } }) .sorted_by(|x, y| { x.selected.cmp(&y.selected).reverse().then_with(|| x.field.cmp(&y.field)) }); state.render_template("configure", &fields) } #[derive(Deserialize)] struct TopTermsQuery { field: String, k: Option<usize>, } #[derive(Serialize)] struct TermCountData { term: String, count: i64, } #[derive(Serialize)] struct TopTermsData { field: String, terms: Vec<TermCountData>, } fn handle_top_terms(req: (HttpRequest<State>, Query<TopTermsQuery>)) -> Result<HttpResponse, TantivyViewerError> { let (req, params) = req; let state = req.state(); let field = params.field.clone(); let k = params.k.unwrap_or(100); let top_terms = top_terms(&state.index, &field, k).unwrap(); let data = TopTermsData { field, terms: top_terms.terms.into_iter().map(|x| TermCountData { term: format!("{}", x.term), count: x.count }).collect() }; state.render_template("top_terms", &data) } fn stringify_values(values: Vec<Option<TantivyValue>>) -> String { values.into_iter() .map(|opt| opt.map(|x| format!("{} ", x)).unwrap_or_default()) .collect() } #[derive(Deserialize)] struct SearchQuery { query: Option<String>, } struct DocCollector { current_segment: Option<SegmentId>, current_segment_docs: Vec<DocId>, docs: Vec<(SegmentId, Vec<DocId>)>, } impl DocCollector { fn new() -> DocCollector { DocCollector { current_segment: None, current_segment_docs: Vec::new(), docs: Vec::new(), } } fn finish_segment(&mut self) { if let Some(segment_id) = self.current_segment { let mut docs = Vec::new(); std::mem::swap(&mut self.current_segment_docs, &mut docs); self.docs.push((segment_id, docs)); } } fn into_docs(mut self) -> Vec<(SegmentId, Vec<DocId>)> { self.finish_segment(); self.docs } } impl Collector for DocCollector { fn set_segment(&mut self, _segment_local_id: u32, segment: &SegmentReader) -> Result<(), tantivy::Error> { self.finish_segment(); self.current_segment = Some(segment.segment_id()); Ok(()) } fn collect(&mut self, doc: u32, _score: f32) { self.current_segment_docs.push(doc); } fn requires_scoring(&self) -> bool { false } } #[derive(Serialize)] struct SearchData { query: String, reconstructed_fields: Vec<String>, docs: Vec<(String, Vec<(DocId, Vec<String>)>)>, truncated: bool, } impl SearchData { fn empty() -> SearchData { SearchData { query: String::new(), reconstructed_fields: Vec::new(), docs: Vec::new(), truncated: false, } } } trait QueryExt { fn collect_first_k(&self, searcher: &Searcher, collector: &mut Collector, k: usize) -> tantivy::Result<()>; } impl<Q: tantivy::query::Query> QueryExt for Q { fn collect_first_k(&self, searcher: &Searcher, collector: &mut Collector, k: usize) -> tantivy::Result<()> { let scoring_enabled = collector.requires_scoring(); let weight = self.weight(searcher, scoring_enabled)?; let mut remaining = k; for (segment_ord, segment_reader) in searcher.segment_readers().iter().enumerate() { collector.set_segment(segment_ord as SegmentLocalId, segment_reader)?; let mut scorer = weight.scorer(segment_reader)?; remaining -= segment_collect_first_k(&mut scorer, collector, segment_reader.delete_bitset(), remaining); } Ok(()) } } trait CollectorExt : Collector + Sized { fn collect_first_k(&mut self, searcher: &Searcher, query: &tantivy::query::Query, k: usize) -> tantivy::Result<()> { let scoring_enabled = self.requires_scoring(); let weight = query.weight(searcher, scoring_enabled)?; let mut remaining = k; for (segment_ord, segment_reader) in searcher.segment_readers().iter().enumerate() { self.set_segment(segment_ord as SegmentLocalId, segment_reader)?; let mut scorer = weight.scorer(segment_reader)?; remaining -= segment_collect_first_k(&mut scorer, &mut *self, segment_reader.delete_bitset(), remaining); } Ok(()) } } impl<C: Collector + Sized> CollectorExt for C { } fn segment_collect_first_k<S: Scorer>(scorer: &mut S, collector: &mut Collector, delete_bitset_opt: Option<&DeleteBitSet>, k: usize) -> usize { let mut remaining = k; if let Some(delete_bitset) = delete_bitset_opt { while remaining > 0 && scorer.advance() { let doc = scorer.doc(); if !delete_bitset.is_deleted(doc) { remaining -= 1; collector.collect(doc, scorer.score()); } } } else { while remaining > 0 && scorer.advance() { remaining -= 1; collector.collect(scorer.doc(), scorer.score()); } } remaining } fn handle_search(req: (HttpRequest<State>, Query<SearchQuery>)) -> Result<HttpResponse, Error> { let (req, params) = req; let state = req.state(); let raw_query = match params.query { None => return Ok(state.render_template("search", &SearchData::empty())?), Some(ref query) => query.clone(), }; let limit = 1000; let query_parser = QueryParser::for_index(&state.index, vec![]); let query = query_parser.parse_query(&raw_query).map_err(TantivyViewerError::QueryParserError)?; let searcher = state.index.searcher(); let mut collector = DocCollector::new(); collector.collect_first_k(&*searcher, &*query, limit + 1).map_err(TantivyViewerError::TantivyError)?; let docs = collector.into_docs(); let identifying_fields = get_identifying_fields(&req); let mut remaining = limit; let mut docs_to_reconstruct = HashMap::new(); let mut truncated = false; for (segment, docs) in docs.into_iter() { let num_docs = docs.len(); if remaining == 0 { break; } let take = remaining.min(docs.len()); if take > 0 { docs_to_reconstruct.insert(segment, docs.into_iter().take(take).collect()); } if take < num_docs { truncated = true; } remaining -= take; } let mut reconstructed_fields = Vec::new(); for field in identifying_fields.iter() { let reconstructed = reconstruct(&state.index, &*field, &docs_to_reconstruct)?; let reconstructed = reconstructed .into_iter() .map(|(segment, docs)| { (segment, docs.into_iter().map(|(doc, values)| (doc, stringify_values(values))).collect::<Vec<_>>()) }) .collect::<HashMap<_, _>>(); reconstructed_fields.push(reconstructed); } let mut result = Vec::new(); for (segment, docs) in docs_to_reconstruct.into_iter() { let mut segment_docs = Vec::new(); for (idx, doc) in docs.into_iter().enumerate() { let mut doc_reconstructed_fields = Vec::new(); for field in reconstructed_fields.iter_mut() { let mut str_swap = String::new(); std::mem::swap(&mut str_swap, &mut field.get_mut(&segment).unwrap().get_mut(idx).unwrap().1); doc_reconstructed_fields.push(str_swap); } segment_docs.push((doc, doc_reconstructed_fields)); } result.push((segment.short_uuid_string(), segment_docs)); } let data = SearchData { query: raw_query, reconstructed_fields: identifying_fields, docs: result, truncated, }; Ok(state.render_template("search", &data)?) } struct State { index: Arc<Index>, handlebars: Arc<Handlebars>, } impl Clone for State { fn clone(&self) -> Self { State { index: self.index.clone(), handlebars: self.handlebars.clone(), } } } impl State { fn render_template<T: Serialize>(&self, name: &str, data: &T) -> Result<HttpResponse, TantivyViewerError> { Ok( HttpResponse::Ok() .content_type("text/html") .body(self.handlebars.render(name, &data).map_err(TantivyViewerError::RenderingError)?) ) } } fn pretty_bytes(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> { if let Some(param) = h.param(0) { if let Some(param) = param.value().as_f64() { rc.writer.write(convert(param).as_bytes())?; return Ok(()); } } rc.writer.write("<invalid argument>".as_bytes())?; Ok(()) } fn url_encode(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> { if let Some(param) = h.param(0) { if let Some(param) = param.value().as_str() { let encoded: String = form_urlencoded::byte_serialize(param.as_bytes()).collect(); rc.writer.write(encoded.as_bytes())?; return Ok(()); } } Err(RenderError::new("Invalid argument to url_encode. Expected string.")) } struct UnknownQueryTypeError; fn child_queries(query: &tantivy::query::Query) -> Result<Vec<Box<tantivy::query::Query>>, UnknownQueryTypeError> { let mut result = Vec::new(); if let Ok(ref query) = query.downcast_ref::<BooleanQuery>() { for (_occur, clause) in query.clauses() { result.push(clause.box_clone()); } } else if let Ok(_query) = query.downcast_ref::<TermQuery>() { } else if let Ok(_query) = query.downcast_ref::<PhraseQuery>() { } else if let Ok(_query) = query.downcast_ref::<RangeQuery>() { } else if let Ok(_query) = query.downcast_ref::<AllQuery>() { } else { return Err(UnknownQueryTypeError); } Ok(result) } fn push_term_str(term: &Term, value_type: &Type, allow_quoting: bool, output: &mut String) { match *value_type { Type::Str => { let term_text = term.text(); if allow_quoting && term_text.contains(' ') { output.push('"'); output.push_str(term_text); output.push('"'); } else { output.push_str(term_text) } }, Type::U64 => output.push_str(&format!("{}", term.get_u64())), Type::I64 => output.push_str(&format!("{}", term.get_i64())), Type::HierarchicalFacet => output.push_str("<cannot write HierarchicalFacet>"), Type::Bytes => output.push_str("<cannot search for bytes>"), } } fn query_to_string(query: &tantivy::query::Query, schema: &Schema) -> String { let mut output = String::new(); push_query_to_string(query, schema, &mut output); output } fn push_query_to_string(query: &tantivy::query::Query, schema: &Schema, output: &mut String) { if let Ok(ref query) = query.downcast_ref::<BooleanQuery>() { let was_empty = output.is_empty(); if !was_empty { output.push('('); } for (idx, (occur, clause)) in query.clauses().iter().enumerate() { if idx != 0 { output.push(' '); } let prefix = match occur { Occur::Should => "", Occur::Must => "+", Occur::MustNot => "-", }; output.push_str(prefix); push_query_to_string(clause.as_ref(), schema, output); } if !was_empty { output.push(')'); } } else if let Ok(ref query) = query.downcast_ref::<TermQuery>() { let term = query.term(); let field_obj = query.term().field(); let field = schema.get_field_name(field_obj); let value_type = schema.get_field_entry(field_obj).field_type().value_type(); output.push_str(field); output.push(':'); push_term_str(term, &value_type, true, output); } else if let Ok(ref query) = query.downcast_ref::<PhraseQuery>() { let field = schema.get_field_name(query.field()); let value_type = schema.get_field_entry(query.field()).field_type().value_type(); let terms = query.phrase_terms(); output.push_str(field); output.push_str(":\""); for (idx, term) in terms.iter().enumerate() { if idx != 0 { output.push(' '); } push_term_str(term, &value_type, false, output); } output.push('"'); } else if let Ok(query) = query.downcast_ref::<RangeQuery>() { let field = schema.get_field_name(query.field()); let value_type = schema.get_field_entry(query.field()).field_type().value_type(); output.push_str(field); output.push(':'); match query.left_bound() { Bound::Included(term) => { output.push('['); push_term_str(&term, &value_type, false, output); }, Bound::Excluded(term) => { output.push('{'); push_term_str(&term, &value_type, false, output); }, Bound::Unbounded => output.push('['), } output.push_str(" TO "); match query.right_bound() { Bound::Included(term) => { push_term_str(&term, &value_type, false, output); output.push(']'); }, Bound::Excluded(term) => { push_term_str(&term, &value_type, false, output); output.push('}'); }, Bound::Unbounded => output.push(']'), } } else if let Ok(_query) = query.downcast_ref::<AllQuery>() { output.push_str("*"); } else { output.push_str(&format!("<unknown query type {:?}>", query)); } } fn main() -> Result<(), Error> { env_logger::init(); let args = env::args().collect::<Vec<_>>(); let index = Arc::new(Index::open_in_dir(&args[1]).unwrap()); let mut handlebars = Handlebars::new(); handlebars.register_helper("pretty_bytes", Box::new(pretty_bytes)); handlebars.register_helper("url_encode", Box::new(url_encode)); for entry in fs::read_dir("./templates")? { let entry = entry?; let filename = entry.file_name(); let filename_string = filename.to_string_lossy(); if filename_string.ends_with(".hbs") { let template_name = &filename_string[..filename_string.len() - ".hbs".len()]; debug!("Registering template {}", template_name); handlebars.register_template_file(template_name, entry.path())?; } } let state = State { index: index.clone(), handlebars: Arc::new(handlebars), }; server::new(move || App::with_state(state.clone()) .resource("/", |r| r.f(handle_index)) .resource("/field_details", |r| r.f(handle_field_details)) .resource("/space_usage", |r| r.f(handle_space_usage)) .resource("/configure", |r| r.f(handle_configure)) .resource("/top_terms", |r| r.method(http::Method::GET).with(handle_top_terms)) .resource("/reconstruct", |r| r.method(http::Method::GET).with(handle_reconstruct)) .resource("/search", |r| r.method(http::Method::GET).with(handle_search)) .resource("/debug", |r| r.method(http::Method::GET).with(handle_debug)) ).bind("0.0.0.0:3000").unwrap().run(); Ok(()) }
// Copyright 2018 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 crate::ast::ServiceSet; use failure::Error; use std::env; use std::fs; #[cfg(test)] use crate::tests; mod ast; mod codegen; #[cfg(test)] mod tests; fn usage() { println!("usage: qmigen -i <qmi json defs> -o <protocol.rs>"); println!(""); println!("Generates type-safe rust bindings for QMI off of a set of"); println!("custom protocol definitions in JSON"); ::std::process::exit(1); } fn main() -> Result<(), Error> { let mut args: Vec<String> = env::args().collect(); if args.len() < 3 { usage(); } if !args.contains(&String::from("-i")) && !args.contains(&String::from("-o")) { usage(); } // extract subsets of the args let i_offset = args.clone().into_iter().position(|s| s == "-i").unwrap(); let o_offset = args.clone().into_iter().position(|s| s == "-o").unwrap(); let mut inputs = args.split_off(i_offset + 1); let outputs = inputs.split_off(o_offset - i_offset); if outputs.len() != 1 { eprintln!("Only one output is expected"); ::std::process::exit(1); } // for each input, add to the Service Set code generator let mut svc_set = ServiceSet::new(); let mut file = fs::File::create(&outputs[0])?; let mut c = codegen::Codegen::new(&mut file); for file in inputs.into_iter().take_while(|s| s != "-o") { let svc_file = fs::File::open(&file)?; svc_set.parse_service_file(svc_file)?; } c.codegen(svc_set) }
use crate::analysis::{reaching_definitions, LocationSet}; use crate::il; use crate::Error; use std::collections::HashMap; #[allow(dead_code)] /// Compute use definition chains for the given function. pub fn use_def( function: &il::Function, ) -> Result<HashMap<il::ProgramLocation, LocationSet>, Error> { let rd = reaching_definitions::reaching_definitions(function)?; let mut ud = HashMap::new(); for location in rd.keys() { let defs = match location.function_location().apply(function).unwrap() { il::RefFunctionLocation::Instruction(_, instruction) => instruction .operation() .scalars_read() .into_iter() .fold(LocationSet::new(), |mut defs, scalar_read| { rd[location].locations().iter().for_each(|rd| { rd.function_location() .apply(function) .unwrap() .instruction() .unwrap() .operation() .scalars_written() .into_iter() .for_each(|scalar_written| { if scalar_written == scalar_read { defs.insert(rd.clone()); } }) }); defs }), il::RefFunctionLocation::Edge(edge) => edge .condition() .map(|condition| { condition.scalars().into_iter().fold( LocationSet::new(), |mut defs, scalar_read| { rd[location].locations().iter().for_each(|rd| { if let Some(scalars_written) = rd .function_location() .apply(function) .unwrap() .instruction() .unwrap() .operation() .scalars_written() { scalars_written.into_iter().for_each(|scalar_written| { if scalar_written == scalar_read { defs.insert(rd.clone()); } }) } }); defs }, ) }) .unwrap_or_else(LocationSet::new), il::RefFunctionLocation::EmptyBlock(_) => LocationSet::new(), }; ud.insert(location.clone(), defs); } Ok(ud) } #[test] fn use_def_test() { /* a = in b = 4 if a < 10 { c = a [0xdeadbeef] = c } else { c = b } b = c c = [0xdeadbeef] */ let mut control_flow_graph = il::ControlFlowGraph::new(); let head_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("a", 32), il::expr_scalar("in", 32)); block.assign(il::scalar("b", 32), il::expr_const(4, 32)); block.index() }; let gt_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("c", 32), il::expr_scalar("b", 32)); block.index() }; let lt_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("c", 32), il::expr_scalar("a", 32)); block.store(il::expr_const(0xdeadbeef, 32), il::expr_scalar("c", 32)); block.index() }; let tail_index = { let block = control_flow_graph.new_block().unwrap(); block.assign(il::scalar("b", 32), il::expr_scalar("c", 32)); block.load(il::scalar("c", 32), il::expr_const(0xdeadbeef, 32)); block.index() }; let condition = il::Expression::cmpltu(il::expr_scalar("a", 32), il::expr_const(10, 32)).unwrap(); control_flow_graph .conditional_edge(head_index, lt_index, condition.clone()) .unwrap(); control_flow_graph .conditional_edge( head_index, gt_index, il::Expression::cmpeq(condition, il::expr_const(0, 1)).unwrap(), ) .unwrap(); control_flow_graph .unconditional_edge(lt_index, tail_index) .unwrap(); control_flow_graph .unconditional_edge(gt_index, tail_index) .unwrap(); control_flow_graph.set_entry(head_index).unwrap(); let function = il::Function::new(0, control_flow_graph); let ud = use_def(&function).unwrap(); // for u in ud.iter() { // println!("{}", u.0); // for d in u.1 { // println!(" {}", d); // } // } let block = function.control_flow_graph().block(0).unwrap(); assert!(ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into()] .is_empty()); let block = function.control_flow_graph().block(0).unwrap(); assert!(ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(1).unwrap()) ) .into()] .is_empty()); let block = function.control_flow_graph().block(1).unwrap(); assert!( ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into()] .len() == 1 ); let block = function.control_flow_graph().block(3).unwrap(); assert!(ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into()] .contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction( function.control_flow_graph().block(1).unwrap(), function .control_flow_graph() .block(1) .unwrap() .instruction(0) .unwrap() ) ) .into() )); let block = function.control_flow_graph().block(3).unwrap(); assert!(ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into()] .contains( &il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction( function.control_flow_graph().block(2).unwrap(), function .control_flow_graph() .block(2) .unwrap() .instruction(0) .unwrap() ) ) .into() )); let block = function.control_flow_graph().block(3).unwrap(); assert!( ud[&il::RefProgramLocation::new( &function, il::RefFunctionLocation::Instruction(block, block.instruction(0).unwrap()) ) .into()] .len() == 2 ); }
// 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 { failure::{Error, ResultExt}, fidl_fuchsia_test_hub as fhub, fuchsia_async as fasync, fuchsia_component::client::connect_to_service, }; macro_rules! get_names_from_listing { ($dir_listing:ident) => { &mut $dir_listing.iter().map(|entry| &entry.name as &str) }; } async fn report_directory_contents( hub_report: &fhub::HubReportProxy, dir_path: &str, ) -> Result<(), Error> { let dir_proxy = io_util::open_directory_in_namespace(dir_path, io_util::OPEN_RIGHT_READABLE) .expect("Unable to open directory in namespace"); let dir_listing = files_async::readdir(&dir_proxy).await.expect("readdir failed"); hub_report .list_directory(dir_path, get_names_from_listing!(dir_listing)) .await .context("list directory failed")?; Ok(()) } async fn report_file_content(hub_report: &fhub::HubReportProxy, path: &str) -> Result<(), Error> { let resolved_url_proxy = io_util::open_file_in_namespace(path, io_util::OPEN_RIGHT_READABLE) .expect("Unable to open the sibling Hub."); let resolved_url_file_content = io_util::read_file(&resolved_url_proxy).await?; hub_report .report_file_content(path, &resolved_url_file_content) .await .context("report file content failed")?; Ok(()) } #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { let hub_report = connect_to_service::<fhub::HubReportMarker>().context("error connecting to HubReport")?; // Read the listing of entires of the hub rooted at this component and // pass the results to the integration test via HubReport. report_directory_contents(&hub_report, "/hub").await?; // Read the listing of the children of the parent from its hub, and pass the // results to the integration test via HubReport. report_directory_contents(&hub_report, "/parent_hub/children").await?; // Read the content of the resolved_url file in the sibling hub, and pass the // results to the integration test via HubReport. report_file_content(&hub_report, "/sibling_hub/exec/resolved_url").await?; Ok(()) }
use test_implement::*; use windows::core::*; use Windows::Foundation::IClosable; // TODO: this just tests the syntax until #81 is further along. #[test] fn test_implement() -> Result<()> { let app: IClosable = AppWithOverrides {}.into(); app.Close()?; let app: IClosable = AppNoOverrides {}.into(); app.Close()?; let app: IClosable = NoExtend {}.into(); app.Close()?; Ok(()) } #[implement( extend Windows::UI::Xaml::Application, override OnLaunched OnBackgroundActivated, Windows::Foundation::IStringable, Windows::Foundation::IClosable, )] struct AppWithOverrides {} #[allow(non_snake_case)] impl AppWithOverrides { fn ToString(&self) -> Result<HSTRING> { Ok("Stringable".into()) } fn Close(&self) -> Result<()> { Ok(()) } fn OnLaunched(&self, _: &Option<Windows::ApplicationModel::Activation::LaunchActivatedEventArgs>) -> Result<()> { Ok(()) } fn OnBackgroundActivated(&self, _: &Option<Windows::ApplicationModel::Activation::BackgroundActivatedEventArgs>) -> Result<()> { Ok(()) } } #[implement( extend Windows::UI::Xaml::Application, Windows::Foundation::{IStringable, IClosable}, )] struct AppNoOverrides {} #[allow(non_snake_case)] impl AppNoOverrides { fn ToString(&self) -> Result<HSTRING> { Ok("Stringable".into()) } fn Close(&self) -> Result<()> { Ok(()) } } #[implement( Windows::Foundation::{IStringable, IClosable}, )] struct NoExtend {} #[allow(non_snake_case)] impl NoExtend { fn ToString(&self) -> Result<HSTRING> { Ok("Stringable".into()) } fn Close(&self) -> Result<()> { Ok(()) } } #[implement( extend Windows::UI::Xaml::Controls::Button, override OnContentChanged, // ContentControl override OnPointerEntered, // Control override OnApplyTemplate, // FrameworkElement )] struct Button {} #[allow(non_snake_case)] impl Button { fn OnContentChanged(&self, _: &Option<IInspectable>, _: &Option<IInspectable>) -> Result<()> { Ok(()) } // TODO: need option to omit Option and/or reference. fn OnPointerEntered(&self, _: &Option<Windows::UI::Xaml::Input::PointerRoutedEventArgs>) -> Result<()> { Ok(()) } fn OnApplyTemplate(&self) -> Result<()> { Ok(()) } }
use std::borrow::Borrow; use std::cell::RefCell; use std::fmt::{Display, Formatter}; use std::fmt; use std::rc::Rc; use rand_distr::{Distribution, Normal}; use crate::structs::offset4::Offset4; use crate::structs::shape4::Shape4; use crate::structs::view4::View4; use crate::traits::view::View; #[derive(Debug)] pub struct Tensor { buffer: Vec<f32>, view: View4, } impl Tensor { pub fn normal(shape: Shape4, mean: f32, std_dev: f32) -> Tensor { Self::from_distrib(shape, Normal::new(mean, std_dev).unwrap()) } pub fn from_distrib<D: Distribution<f32>>(shape: Shape4, dist: D) -> Self { let mut rng = rand::thread_rng(); let mut buffer = vec![0_f32; shape.len()]; for i in 0..buffer.len() { buffer[i] = dist.sample(&mut rng); } Self::from_buffer(buffer, View4::new(shape)) } pub fn new(shape: Shape4, value: f32) -> Self { Self::from_buffer( vec![value; shape.len()], View4::new(shape)) } pub fn from_buffer(buffer: Vec<f32>, view: View4) -> Self { assert_eq!(buffer.len(), view.shape().len()); Tensor { buffer, view, } } pub fn view(&self, offset: Offset4, shape: Shape4) -> Tensor { Tensor { buffer: self.buffer.clone(), view: View4 { offset, shape, }, } } pub fn get_at(&self, offset: Offset4) -> f32 { log::trace!("Offset4.index_from"); self.get(self.shape().index(&offset)) } pub fn insert_at(&mut self, offset: Offset4, value: f32) { self.insert(self.shape().index(&offset), value) } pub fn get(&self, offset: usize) -> f32 { self.buffer[offset] } pub fn insert(&mut self, offset: usize, value: f32) { self.buffer[offset] = value; } pub fn copy_from(&mut self, other: &Tensor) { self.buffer.as_mut_slice().copy_from_slice( other.buffer.as_slice() ) } pub fn deep_clone(&self) -> Tensor { Tensor::from_buffer( self.buffer.clone(), self.view.clone(), ) } } impl View for Tensor { fn offset(&self) -> &Offset4 { self.view.offset() } fn shape(&self) -> &Shape4 { &self.view.shape } } impl Display for Tensor { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.buffer) } } impl Clone for Tensor { fn clone(&self) -> Self { self.deep_clone() } } #[cfg(test)] mod tests { use std::time::Duration; use rust_tools::bench::Bench; use crate::structs::shape4::Shape4; use crate::tensor::Tensor; #[test] fn test_tensor() { let shape = Shape4::vec4(32, 32, 128, 1); let mut x = Tensor::normal(shape.clone(), 0.0, 1.0); let y = Tensor::normal(shape, 0.0, 1.0); let mut bench = Bench::new("Tensor Mut"); while bench.for_duration(Duration::from_secs(5)) { x *= y.clone(); } // println!("{:?}", x); println!("{}", bench); } }
{{#if NumericSet}}{{NumericSet}}{{else}}&(){{/if}}
#[macro_use] extern crate guitk; use guitk::logger; fn setup_logger() { logger::set_default_log_tag("pkdx"); logger::set_default_log_priority(logger::LogPriority::DEBUG); } fn setup_test_layer(w: f32, h: f32) -> guitk::view::Layer { use guitk::view::*; use guitk::entity::core::*; use guitk::entity::animation::*; use guitk::common::color::*; use guitk::layout::*; use guitk::entity::EntityID; // Header bar let header_bar_aabb = ComponentAABB { entity_id: EntityID(0), x: 0.0, y: 0.0, w: 0.0, h: 0.0, }; let header_bar_debug_draw = ComponentDebugDraw { entity_id: EntityID(0), color: RGBf32::new(0.0, 1.0, 0.0), }; // Body container ( nested layer ) let body_aabb = ComponentAABB { entity_id: EntityID(1), x:0.0, y: 0.0, w: 0.0, h: 0.0, }; let mut body_layer = Layer::new(); body_layer.entity_id = Some(EntityID(1)); // Body L div let body_l_aabb = ComponentAABB { entity_id: EntityID(3), x: 0.0, y: 0.0, w: 0.0, h: 0.0, }; let body_l_debug_draw = ComponentDebugDraw { entity_id: EntityID(3), color: RGBf32::new(1.0, 1.0, 0.0), }; // Body R div let body_r_aabb = ComponentAABB { entity_id: EntityID(4), x: 0.0, y: 0.0, w: 0.0, h: 0.0, }; let body_r_debug_draw = ComponentDebugDraw { entity_id: EntityID(4), color: RGBf32::new(0.0, 1.0, 1.0), }; const SIDEBAR_SIZE: f32 = 300.0; // Body vsplit let inner_body_aabb = ComponentAABB { entity_id: EntityID(5), x: -SIDEBAR_SIZE, y: 0.0, w: w+SIDEBAR_SIZE, h: h, }; let inner_body_container = ComponentContainer { entity_id: EntityID(5), layout: Layout::VSplit { entity_l: EntityID(3), entity_r: EntityID(4), split_pos: SIDEBAR_SIZE, }, }; let inner_body_trigger = ComponentTrigger { entity_id: EntityID(5), trigger_id: 0, x: SIDEBAR_SIZE - 50.0, y: 0.0, w: 100.0, h: h - 100.0, relative: true,}; let inner_body_scroll = ComponentTouchScroll { entity_id: EntityID(5), trigger_id: 0, behaviour_flags: scroll_behaviour::LOCKED_Y, min_x: - SIDEBAR_SIZE, max_x: w + SIDEBAR_SIZE, min_y: 0.0, max_y: h, }; let inner_body_scroll_snap = ComponentScrollSnap { entity_id: EntityID(5), snap_positions: vec![(-SIDEBAR_SIZE, 0.0), (0.0, 0.0)], tween_func: TweenFunction::EaseOut, tween_len: 250, }; // Main container let view_container_aabb = ComponentAABB { entity_id: EntityID(2), x: 0.0, y: 0.0, w: w, h: h}; let view_container_container = ComponentContainer { entity_id: EntityID(2), layout: Layout::HeaderBar { entity_header: EntityID(0), entity_body: EntityID(1), header_height: 100.0, } }; let mut layer = guitk::view::Layer::new(); layer.component_aabb.add_component(header_bar_aabb); layer.component_aabb.add_component(body_aabb); layer.component_aabb.add_component(view_container_aabb); layer.component_debug_draw.add_component(header_bar_debug_draw); layer.component_container.add_component(view_container_container); body_layer.component_aabb.add_component(body_l_aabb); body_layer.component_aabb.add_component(body_r_aabb); body_layer.component_aabb.add_component(inner_body_aabb); body_layer.component_debug_draw.add_component(body_l_debug_draw); body_layer.component_debug_draw.add_component(body_r_debug_draw); body_layer.component_container.add_component(inner_body_container); body_layer.component_trigger.add_component(inner_body_trigger); body_layer.component_touch_scroll.add_component(inner_body_scroll); body_layer.component_scroll_snap.add_component(inner_body_scroll_snap); layer.component_layer.add_component(body_layer); return layer; } fn setup_test_view<'a>(w: f32, h: f32) -> guitk::view::View<'a> { let mut view = guitk::view::View::new(); view.layers.push(setup_test_layer(w, h)); return view; } fn main() { // Initialise guitk let mut guitk_state = guitk::init().unwrap(); setup_logger(); // Push a new view onto the view stack let (w, h) = guitk_state.get_view_size(); guitk_state.view_stack.push(setup_test_view(w as f32, h as f32)); // Layout test view guitk_state.view_stack.last_mut().unwrap().layout(); loop { // Render the view guitk_state.update(); } }
use crate::schema; use arrow::datatypes::{ DataType as ArrowDataType, Field as ArrowField, Schema as ArrowSchema, TimeUnit, }; use lazy_static::lazy_static; use regex::Regex; impl From<&schema::Schema> for ArrowSchema { fn from(s: &schema::Schema) -> Self { let fields = s .get_fields() .iter() .map(|field| <ArrowField as From<&schema::SchemaField>>::from(field)) .collect(); ArrowSchema::new(fields) } } impl From<&schema::SchemaField> for ArrowField { fn from(f: &schema::SchemaField) -> Self { ArrowField::new( f.get_name(), ArrowDataType::from(f.get_type()), f.is_nullable(), ) } } impl From<&schema::SchemaTypeArray> for ArrowField { fn from(a: &schema::SchemaTypeArray) -> Self { ArrowField::new( "", ArrowDataType::from(a.get_element_type()), a.contains_null(), ) } } impl From<&schema::SchemaDataType> for ArrowDataType { fn from(t: &schema::SchemaDataType) -> Self { match t { schema::SchemaDataType::primitive(p) => { lazy_static! { static ref DECIMAL_REGEX: Regex = Regex::new(r"\((\d{1,2}),(\d{1,2})\)").unwrap(); } match p.as_str() { "string" => ArrowDataType::Utf8, "long" => ArrowDataType::Int64, // undocumented type "integer" => ArrowDataType::Int32, "short" => ArrowDataType::Int16, "byte" => ArrowDataType::Int8, "float" => ArrowDataType::Float32, "double" => ArrowDataType::Float64, "boolean" => ArrowDataType::Boolean, "binary" => ArrowDataType::Binary, decimal if DECIMAL_REGEX.is_match(decimal) => { let extract = DECIMAL_REGEX.captures(decimal).unwrap(); let precision = extract.get(1).unwrap().as_str().parse::<usize>().unwrap(); let scale = extract.get(2).unwrap().as_str().parse::<usize>().unwrap(); ArrowDataType::Decimal(precision, scale) } "date" => { // A calendar date, represented as a year-month-day triple without a // timezone. panic!("date is not supported in arrow"); } "timestamp" => { // Microsecond precision timestamp without a timezone. ArrowDataType::Time64(TimeUnit::Microsecond) } s => { panic!("unexpected delta schema type: {}", s); } } } schema::SchemaDataType::r#struct(s) => ArrowDataType::Struct( s.get_fields() .iter() .map(|f| <ArrowField as From<&schema::SchemaField>>::from(f)) .collect(), ), schema::SchemaDataType::array(a) => ArrowDataType::List(Box::new( <ArrowField as From<&schema::SchemaTypeArray>>::from(a), )), schema::SchemaDataType::map(m) => ArrowDataType::Dictionary( Box::new(<ArrowDataType as From<&schema::SchemaDataType>>::from( m.get_key_type(), )), Box::new(<ArrowDataType as From<&schema::SchemaDataType>>::from( m.get_value_type(), )), ), } } }
//https://leetcode.com/problems/count-the-number-of-consistent-strings/submissions/ impl Solution { pub fn count_consistent_strings(allowed: String, words: Vec<String>) -> i32 { let mut good: Vec<bool> = vec![false; 26]; for c in allowed.chars() { let c_value = c as i32 - 'a' as i32; good[c_value as usize] = true; } let mut good_words = 0; for i in 0..words.len() { good_words += 1; for c in words[i].chars() { let c_value = c as i32 - 'a' as i32; if !good[c_value as usize] { good_words -= 1; break; } } } good_words } }
use super::*; /// The output of a [`TagAttributeIterator`]. /// /// Attributes within an XML tag are key-value pairs. Only `Start` and `Empty` /// tags have attributes. /// /// Each key is expected to only appear once in a given tag. The order of the /// keys is not usually significant. #[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] #[allow(missing_docs)] pub struct TagAttribute<'s> { pub key: &'s str, pub value: &'s str, } /// Iterator to walk through a `Start` or `Empty` tag's attribute string. /// /// Supports both `'` and `"` quoting around the attribute values. /// /// The parsing is a little simplistic, and if the iterator gets confused by bad /// input it will just end the iteration. #[derive(Debug, Clone, Default)] pub struct TagAttributeIterator<'s> { attrs: &'s str, } impl<'s> TagAttributeIterator<'s> { /// Makes a new iterator over the attribute string. #[inline] #[must_use] pub fn new(attrs: &'s str) -> Self { Self { attrs: attrs.trim() } } /// Gets the `value` of the `key` given, if the key is present. /// /// ```rust /// # use magnesium::TagAttributeIterator; /// let attrs = r#"namespace="Graphics" group="Polygon""#; /// let iter = TagAttributeIterator::new(attrs); /// assert_eq!(iter.find_by_key("namespace"), Some("Graphics")); /// assert_eq!(iter.find_by_key("ferris"), None); /// assert_eq!(iter.find_by_key("group"), Some("Polygon")); /// ``` #[inline] #[must_use] pub fn find_by_key(&self, key: &str) -> Option<&'s str> { self.clone().find(|ta| ta.key == key).map(|ta| ta.value) } } impl<'s> Iterator for TagAttributeIterator<'s> { type Item = TagAttribute<'s>; #[inline] #[must_use] fn next(&mut self) -> Option<Self::Item> { debug_assert_eq!(self.attrs, self.attrs.trim()); if self.attrs.is_empty() { return None; } #[allow(clippy::never_loop)] 'clear_and_return_none: loop { // break on `=` let (key, rest) = match break_on_first_char(self.attrs, '=') { Some((key, rest)) => (key, rest), None => break 'clear_and_return_none, }; self.attrs = rest; // support both `"` and `'` since it's easy to do let quote_marker = match self.attrs.chars().next() { Some(q) if q == '\'' || q == '\"' => { self.attrs = &self.attrs[1..]; q } _ => break 'clear_and_return_none, }; // break on the end of the quote let (value, rest) = match break_on_first_char(self.attrs, quote_marker) { Some((key, rest)) => (key, rest), None => break 'clear_and_return_none, }; self.attrs = rest.trim_start(); return Some(TagAttribute { key, value }); } self.attrs = ""; None } } impl<'s> core::iter::FusedIterator for TagAttributeIterator<'s> {}
use P80::digraph_converters::labeled; use P81::*; pub fn main() { let g = labeled::from_string("[p>q/9, m>q/7, k, p>m/5]"); println!("Paths from p to q: {:?}", g.find_paths('p', 'q')); println!("Paths from p to k: {:?}", g.find_paths('p', 'k')); }
extern crate time; extern crate openrpg; use time::{PreciseTime}; const MS_PER_UPDATE: i64 = 16; #[allow(dead_code)] fn gameloop() { let mut previous = PreciseTime::now(); // Get Current time let mut lag: i64 = 0; loop { let current = PreciseTime::now(); let elapsed = previous.to(current).num_milliseconds(); previous = current; lag += elapsed; while lag >= MS_PER_UPDATE { lag -= MS_PER_UPDATE; } } } fn main() { use openrpg::framework::cvar_system::{CVarSystem, CVarSystemLocal}; // let cmdSystem = let mut cvar_system: CVarSystemLocal = CVarSystemLocal::new(); cvar_system.init(); }
use super::connect_params::ServerCerts; use super::connect_params_builder::ConnectParamsBuilder; use super::cp_url::UrlOpt; use crate::{HdbError, HdbResult}; use url::Url; /// A trait implemented by types that can be converted into a `ConnectParamsBuilder`. /// /// # Example /// ```rust /// use hdbconnect::IntoConnectParamsBuilder; /// /// let cp_builder = "hdbsql://MEIER:schLau@abcd123:2222" /// .into_connect_params_builder() /// .unwrap(); /// /// assert_eq!("abcd123", cp_builder.get_hostname().unwrap()); /// ``` pub trait IntoConnectParamsBuilder { /// Converts the value of `self` into a `ConnectParamsBuilder`. /// /// # Errors /// `HdbError::Usage` if wrong information was provided fn into_connect_params_builder(self) -> HdbResult<ConnectParamsBuilder>; } impl IntoConnectParamsBuilder for ConnectParamsBuilder { fn into_connect_params_builder(self) -> HdbResult<ConnectParamsBuilder> { Ok(self) } } impl<'a> IntoConnectParamsBuilder for &'a str { fn into_connect_params_builder(self) -> HdbResult<ConnectParamsBuilder> { Url::parse(self) .map_err(|e| HdbError::conn_params(Box::new(e)))? .into_connect_params_builder() } } impl IntoConnectParamsBuilder for String { fn into_connect_params_builder(self) -> HdbResult<ConnectParamsBuilder> { self.as_str().into_connect_params_builder() } } impl IntoConnectParamsBuilder for Url { fn into_connect_params_builder(self) -> HdbResult<ConnectParamsBuilder> { let mut builder = ConnectParamsBuilder::new(); self.host_str().as_ref().map(|host| builder.hostname(host)); self.port().as_ref().map(|port| builder.port(*port)); let dbuser = self.username(); if !dbuser.is_empty() { builder.dbuser(dbuser); } self.password().as_ref().map(|pw| builder.password(pw)); // authoritative switch between protocols: let use_tls = match self.scheme() { "hdbsql" => false, "hdbsqls" => true, _ => { return Err(HdbError::Usage( "Unknown protocol, only 'hdbsql' and 'hdbsqls' are supported", )); } }; let mut insecure_option = false; let mut server_certs = Vec::<ServerCerts>::new(); for (name, value) in self.query_pairs() { match UrlOpt::from(name.as_ref()) { Some(UrlOpt::ClientLocale) => { builder.clientlocale(&value); } Some(UrlOpt::ClientLocaleFromEnv) => { std::env::var(value.to_string()) .ok() .map(|s| builder.clientlocale(s)); } Some(UrlOpt::TlsCertificateDir) => { server_certs.push(ServerCerts::Directory(value.to_string())); } Some(UrlOpt::TlsCertificateEnv) => { server_certs.push(ServerCerts::Environment(value.to_string())); } Some(UrlOpt::TlsCertificateMozilla) => { server_certs.push(ServerCerts::RootCertificates); } Some(UrlOpt::InsecureOmitServerCheck) => { insecure_option = true; } #[cfg(feature = "alpha_nonblocking")] Some(UrlOpt::NonBlocking) => { builder.use_nonblocking(); return Err(HdbError::UsageDetailed(format!( "url option {} requires feature alpha_nonblocking", UrlOpt::NonBlocking.name() ))); } Some(UrlOpt::Database) => { builder.dbname(&value); } Some(UrlOpt::NetworkGroup) => { builder.network_group(&value); } None => { return Err(HdbError::UsageDetailed(format!( "option '{name}' not supported", ))); } } } if use_tls { if insecure_option { if !server_certs.is_empty() { return Err(HdbError::Usage( "Use the url-options 'tls_certificate_dir', 'tls_certificate_env', \ 'tls_certificate_direct' and 'use_mozillas_root_certificates' \ to specify the access to the server certificate,\ or use 'insecure_omit_server_certificate_check' to not verify the server's \ identity, which is not recommended in most situations", )); } builder.tls_without_server_verification(); } else { if server_certs.is_empty() { return Err(HdbError::Usage( "Using 'hdbsqls' requires at least one of the url-options \ 'tls_certificate_dir', 'tls_certificate_env', 'tls_certificate_direct', \ 'use_mozillas_root_certificates', or 'insecure_omit_server_certificate_check'", )); } for cert in server_certs { builder.tls_with(cert); } } } else if insecure_option || !server_certs.is_empty() { return Err(HdbError::Usage( "Using 'hdbsql' is not possible with any of the url-options \ 'tls_certificate_dir', 'tls_certificate_env', 'tls_certificate_direct', \ 'use_mozillas_root_certificates', or 'insecure_omit_server_certificate_check'; \ consider using 'hdbsqls' instead", )); } Ok(builder) } }
use ndarray::{Array, Array1, Array3, ArrayView3}; use std::convert::From; use std::ops::{Add, Mul}; use std::vec::IntoIter; use crate::voxel::Voxel; use crate::iso_field_generator::ScalarField; type Indexes = (usize, usize, usize); type Mask = (usize, usize, usize); const MASKS: [Mask; 8] = [ (0, 0, 0), (1, 0, 0), (1, 0, 1), (0, 0, 1), (0, 1, 0), (1, 1, 0), (1, 1, 1), (0, 1, 1), ]; #[derive(Debug)] struct Vertex { x: f32, y: f32, z: f32, } impl From<(Indexes, Mask)> for Vertex { fn from(i: (Indexes, Mask)) -> Self { Vertex { x: i.0.0.mul(2).add(i.1.0) as f32, y: i.0.1.mul(2).add(i.1.1) as f32, z: i.0.2.mul(2).add(i.1.2) as f32, } } } #[derive(Debug)] pub struct Corner { vertex: Vertex, iso_value: Voxel, } pub type Cube = [Corner; 8]; fn collect_iso_volume(iso_field: &ScalarField) -> Array3<Array3<Voxel>> { let grid_size = iso_field.dim().0; iso_field .exact_chunks((2, 2, 2)) .into_iter() .map(|c| c.into_owned()) .collect::<Array<Array3<Voxel>, _>>() .into_shape((grid_size / 2, grid_size / 2, grid_size / 2)) .unwrap() } pub fn cubes_iter(iso_field: &ScalarField) -> IntoIter<Cube> { let chunked_iso_field = collect_iso_volume(&iso_field); let indexed_iter = chunked_iso_field.indexed_iter(); indexed_iter .map(|(index, data)| { MASKS.map(|m| { Corner { vertex: Vertex::from((index, m)), iso_value: data[[m.0, m.1, m.2]], } }) }) .collect::<Vec<Cube>>() .into_iter() } pub fn cubes_iter2(iso_field: &ScalarField) -> Array1<Cube> { let grid_size = iso_field.dim().0; let x = iso_field .exact_chunks((2, 2, 2)) .into_iter() .collect::<Array<ArrayView3<Voxel>, _>>() .into_shape((grid_size / 2, grid_size / 2, grid_size / 2)).unwrap() .indexed_iter() .map(|(index, data)| { MASKS.map(|m| { Corner { vertex: Vertex::from((index, m)), iso_value: data[[m.0, m.1, m.2]], } }) }) .collect::<Array1<Cube>>(); //.into_iter(); x } #[cfg(test)] mod tests { use super::*; use crate::iso_field_generator::{generate_iso_field, ScalarField}; use float_cmp::approx_eq; use pretty_assertions::assert_eq; const BALL_POS: [(f32, f32, f32); 2] = [(8.5, 8.5, 8.5), (8.5, 17.0, 8.5)]; const GRID_SIZE: usize = 32; fn assert_cube(voxel: &Cube, iso_cube: &ScalarField) { voxel.iter().for_each(|v| { let vertex_value = v.iso_value; let cube_value = iso_cube[[ v.vertex.x as usize, v.vertex.y as usize, v.vertex.z as usize, ]]; assert!(approx_eq!(Voxel, vertex_value, cube_value, ulps = 2)); }); } #[test] fn test_convert_iso_to_voxels() { let iso_cube = generate_iso_field(GRID_SIZE, &BALL_POS); let c_iter = cubes_iter(&iso_cube); c_iter.for_each(|v| assert_cube(&v, &iso_cube)); } #[test] fn test_view_based_chunking() { let iso_cube = generate_iso_field(GRID_SIZE, &BALL_POS); let c_iter = cubes_iter2(&iso_cube); c_iter.for_each(|v| assert_cube(&v, &iso_cube)); } }
use std::ops::{Deref, DerefMut}; use super::*; pub struct WriteBufferMap <'a, T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { pub(crate) buff: &'a mut Buffer<T, Kind, Acces>, pub(crate) buffer: &'a mut [T] } impl<T, Kind, Acces> Deref for WriteBufferMap<'_, T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { type Target = [T]; fn deref(&self) -> &[T] { self.buffer } } impl<T, Kind, Acces> DerefMut for WriteBufferMap<'_, T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { fn deref_mut(&mut self) -> &mut [T] { self.buffer } } impl<T, Kind, Acces> Drop for WriteBufferMap<'_, T, Kind, Acces> where T: Sized + BufferData, Kind: BufferType, Acces: BufferAcces { fn drop(&mut self) { unsafe { self.buff.bind(); self.buff.len = self.buffer.len(); gl::UnmapBuffer(Kind::value()); } } }
mod app; mod callback; mod hooks; use crate::app::AppStartup; use wasm_bindgen::prelude::*; use yew::prelude::*; #[wasm_bindgen(start)] pub fn run_app() { App::<AppStartup>::new().mount_to_body(); }
#![feature(str_split_once)] use std::path::Path; use std::fs::File; use std::io::{BufRead, BufReader}; use std::io::Write; use std::any::type_name; mod convert; mod info; mod utility; #[derive(Debug)] struct Parser { symbol_stack: Vec<String>, content_stack: Vec<String>, } fn parse_markdown_file(_filename: &str){ println!("[ INFO ] Trying to parse {}...", _filename); let input_filename = Path::new(_filename); let mut output_filename = String::from(_filename.split('.').nth(0).unwrap()); output_filename.push_str(".html"); let mut outfile = File::create(output_filename) .expect("[ ERROR ] Could not create output file1"); let file = File::open(&input_filename) .expect("[ ERROR ] Failed to open file!"); let mut tokens: Vec<String> = Vec::new(); let reader = BufReader::new(file); let keywords: Vec<&str> = vec!["#","##","###"]; let mut see_order_list = false; let mut next_number: usize = 1; // let order_list_ended = false; let mut encounter = false; for line in reader.lines().map(|l| l.unwrap()){ if line != ""{ let mut p = Parser{ symbol_stack: Vec::new(), content_stack: Vec::new(), }; for word in line.split_whitespace() { p.symbol_stack.push(word.to_string()); } while let Some(top) = p.symbol_stack.pop() { let top_len = top.len(); if see_order_list && top.parse::<usize>().is_err(){ p.content_stack.insert(0, "</ol>".to_string()); see_order_list = false; } if let Some(converted_bold) = convert::bold(&top) { p.content_stack.push(converted_bold); } else if let Some((start, end)) = convert::block_quote(&top){ p.content_stack.push(start); p.content_stack.insert(0,end); } else if keywords.contains(&top.as_str()){ p.content_stack.insert(0, format!("</h{}>", top_len)); p.content_stack.push(format!("<h{}>", top_len )); } else{ p.content_stack.push(top.to_string()) } } p.content_stack.reverse(); let first_item = p.content_stack[0].as_str(); if let Some(first_char) = first_item.get(0..1) { if first_char != "<" { if let Ok(x) = first_char.parse::<usize>() { encounter = true; match x { 1 => { p.content_stack[0] = "<ol>\n<li>".to_string(); p.content_stack.push("</li>".to_string()); }, _ => { p.content_stack[0] = "<li>".to_string(); p.content_stack.push("</li>".to_string()); } } println!("numeric!!! {}", x); }else{ // encounter = false; // if first_char.is_numeric() // println!("first character = {}", first_char); p.content_stack.push(format!("</p>")); p.content_stack.insert(0, "<p>".to_string()); } } } if encounter && p.content_stack[0] != "<li>".to_string() && p.content_stack[0] != "<ol>\n<li>".to_string() { tokens.push("</ol>\n".to_string()); encounter = false; } tokens.push(format!("{}\n",p.content_stack.join(" ")) ); for line in &tokens{ println!("{}", line); } } } println!("[ INFO ] Parsing complete!"); } fn main() { let args: Vec<String> = std::env::args().collect(); match args.len(){ 1 => info::usage(), 2 => parse_markdown_file(&args[1]), _ => { println!("[ERROR] Invalid invocation (you done goofed!)"); } } }