text
stringlengths
8
4.13M
#![warn(clippy::all)] #![warn(clippy::pedantic)] fn main() { run(); } fn run() { let start = std::time::Instant::now(); // code goes here let res = recurse(0, 0); let span = start .elapsed() .as_nanos(); println!("{} {}", res, span); } const COINS: &[u64] = &[1, 2, 5, 10, 20, 50, 100, 200]; const GOAL: u64 = 200; fn recurse(sum: u64, idx: usize) -> u64 { if sum > GOAL || idx >= COINS.len() { 0 } else if sum == GOAL { 1 } else { recurse(sum + COINS[idx], idx) + recurse(sum, idx + 1) } }
use std::error::Error; /// HTTPS capable synchronous client. pub trait HttpsClient { fn get(&self, url: &str) -> Result<String, Box<dyn Error>>; } #[test] fn assert_https_client_object_safety() { struct NoneHttpsClient; impl HttpsClient for NoneHttpsClient { fn get(&self, _url: &str) -> Result<String, Box<dyn Error>> { Ok(String::new()) } } let _: Box<dyn HttpsClient> = Box::new(NoneHttpsClient); } pub mod impls { use super::*; #[cfg(feature = "attohttpc_client")] pub mod attohttpc_impl { use super::*; #[cfg(test)] lazy_static::lazy_static! { static ref THROTTLE_MUTEX: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); } /// `HttpsClient` implementation for `attohttpc` crate. pub struct AttoHttpcImpl {} impl HttpsClient for AttoHttpcImpl { #[cfg(not(test))] fn get(&self, url: &str) -> Result<String, Box<dyn Error>> { Ok(attohttpc::get(url).send()?.error_for_status()?.text()?) } #[cfg(test)] fn get(&self, url: &str) -> Result<String, Box<dyn Error>> { let sleep_duration = std::time::Duration::from_millis(rand::random::<u64>() % 100 + 100); let guard = THROTTLE_MUTEX.lock(); let res = attohttpc::get(url).send()?.error_for_status()?.text()?; std::thread::sleep(sleep_duration); drop(guard); Ok(res) } } #[test] fn get() { assert!(AttoHttpcImpl {}.get("http://example.com").is_ok()) } #[test] fn get_ssl() { assert!(AttoHttpcImpl {}.get("https://example.com").is_ok()) } #[test] fn get_err() { assert!(AttoHttpcImpl {}.get("http://example.com/unknown").is_err()) } #[test] fn get_ssl_err() { assert!(AttoHttpcImpl {}.get("https://example.com/unknown").is_err()) } } }
use crate::api::v1::ceo::option::model::{Delete, Get, GetList, New, Update}; use crate::errors::ServiceError; use crate::models::option::{Opt as Object, OptRes}; use crate::models::DbExecutor; use crate::schema::option::dsl::{deleted_at, html_type, id, name, option as tb, price, shop_id}; use actix::Handler; use diesel; use diesel::prelude::*; impl Handler<New> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: New, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let check = tb .filter(&shop_id.eq(&msg.shop_id)) .filter(&name.eq(&msg.name)) .load::<Object>(conn)? .pop(); match check { Some(_) => Err(ServiceError::BadRequest("중복".into())), None => { let insert: Object = diesel::insert_into(tb) .values(&msg) .get_result::<Object>(conn)?; let payload = serde_json::json!({ "item": insert, }); Ok(Msg { status: 201, data: payload, }) } } } } use crate::models::msg::Msg; impl Handler<Update> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: Update, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let old_item = tb .filter(&id.eq(&msg.id)) .filter(&shop_id.eq(&msg.shop_id)) .get_result::<Object>(conn)?; let item_update = diesel::update(&old_item) .set(&msg) .get_result::<Object>(conn)?; let payload = serde_json::json!({ "item_update": item_update, }); Ok(Msg { status: 201, data: payload, }) } } impl Handler<Get> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: Get, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let item = tb.filter(&id.eq(&msg.id)).get_result::<Object>(conn)?; let payload = serde_json::json!({ "item": item, }); Ok(Msg { status: 201, data: payload, }) } } impl Handler<GetList> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, _msg: GetList, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let item = tb .select((id, name, price, html_type)) .filter(&shop_id.eq(&_msg.shop_id)) .filter(&deleted_at.is_null()) .load::<OptRes>(conn)?; let payload = serde_json::json!({ "items": item, }); Ok(Msg { status: 201, data: payload, }) } } impl Handler<Delete> for DbExecutor { type Result = Result<Msg, ServiceError>; fn handle(&mut self, msg: Delete, _: &mut Self::Context) -> Self::Result { let conn = &self.0.get()?; let old_item = tb .filter(&id.eq(&msg.id)) .filter(&shop_id.eq(&msg.shop_id)) .get_result::<Object>(conn)?; let item_delete = diesel::update(&old_item) .set(deleted_at.eq(diesel::dsl::now)) .get_result::<Object>(conn)?; //deleted_at let payload = serde_json::json!({ "item_delete": item_delete, }); Ok(Msg { status: 201, data: payload, }) } }
use regex::Regex; pub fn new_re(s: &str) -> Regex { Regex::new(s).unwrap() } pub fn re_captures<'a>(re: &Regex, s: &'a str) -> impl Iterator<Item = &'a str> { re.captures(s) .unwrap() .iter() .skip(1) .map(|om| om.map_or("", |m| m.as_str())) .collect::<Vec<_>>() // Not sure how to avoid this (lifetimes) .into_iter() } pub fn parse_re<'a, T: Extract<'a>>(re: &Regex, s: &'a str) -> T { T::extract(&mut re_captures(re, s)) } pub fn parse_iter<'a, T: Extract<'a>, I: Iterator<Item = &'a str>>(iter: &mut I) -> T { T::extract(iter) } pub fn re_parser<'a, T: Extract<'a>>(re_str: &str) -> impl (Fn(&'a str) -> T) { let re = new_re(re_str); move |s| parse_re(&re, s) } pub trait Extract<'a> { fn extract<I: Iterator<Item = &'a str>>(iter: &mut I) -> Self; } impl<'a> Extract<'a> for &'a str { fn extract<I: Iterator<Item = &'a str>>(iter: &mut I) -> Self { iter.next().unwrap() } } impl<'a> Extract<'a> for String { fn extract<I: Iterator<Item = &'a str>>(iter: &mut I) -> Self { iter.next().unwrap().into() } } impl<'a, T: Extract<'a>> Extract<'a> for Vec<T> { fn extract<I: Iterator<Item = &'a str>>(iter: &mut I) -> Self { let mut res = vec![]; let mut iter = iter.peekable(); while iter.peek() != None { res.push(T::extract(&mut iter)); } res } } macro_rules! extract_impl { ($($t:ty)+) => { $( impl<'a> Extract<'a> for $t { fn extract<I: Iterator<Item = &'a str>>(iter: &mut I) -> Self { let s = iter.next().unwrap(); if let Ok(res) = s.parse() { res } else { panic!("Cannot convert string '{}'", s) } } } )+ } } extract_impl!(i8 i16 i32 i64 isize u8 u16 u32 u64 usize char bool); macro_rules! extract_tuple_impl { ($($types:ident),+) => { impl<'a, $($types: Extract<'a>),+> Extract<'a> for ($($types),+){ fn extract<I: Iterator<Item=&'a str>>(iter: &mut I) -> Self { ($($types::extract(iter)),+) } } } } extract_tuple_impl!(A, B); extract_tuple_impl!(A, B, C); extract_tuple_impl!(A, B, C, D); extract_tuple_impl!(A, B, C, D, E); extract_tuple_impl!(A, B, C, D, E, F); extract_tuple_impl!(A, B, C, D, E, F, G); pub trait Gather<'a, T> { fn gather(&mut self) -> T; } impl<'a, T: Extract<'a>, I> Gather<'a, T> for I where I: Iterator<Item = &'a str>, { fn gather(&mut self) -> T { T::extract(self) } }
mod drawing_window; mod grid_panel; mod widget; mod scroll_panel; mod h_scroll; use drawing_window::DrawingWindow; use grid_panel::GridPanel; use widget::Widget; use scroll_panel::ScrollPanel; fn main() { let mut red_scroll = Box::new(ScrollPanel::new()); let mut green_scroll = Box::new(ScrollPanel::new()); let mut red_panel = Box::new(GridPanel::new([1.0, 0.0, 0.0, 1.0])); let mut green_panel = Box::new(GridPanel::new([0.0, 1.0, 0.0, 1.0])); let blue_panel = Box::new(GridPanel::new([0.0, 0.0, 1.0, 1.0])); green_scroll.add_child(blue_panel); green_panel.add_child(green_scroll); red_scroll.add_child(green_panel); red_panel.add_child(red_scroll); let mut app = DrawingWindow::new(red_panel); app.run(); }
#[derive(Debug, Serialize, Deserialize)] pub struct Command { pub command: CommandType, pub data: String, } #[derive(Debug, Serialize, Deserialize, ToString, PartialEq)] pub enum CommandType { NodeElementList, DiscoveryEnable, DiscoveryDisable, AddToUnregisteredList, // From BlackBox to WebInterface RemoveFromUnregisteredList, // From BlackBox to WebInterface AnnounceOnline, AnnounceOffline, NodeRegistration, UnregisterNode, RestartNode, NodeStatus, UpdateNodeInfo, SetElementState, UpdateElementState, SystemShutdown, SystemReboot, } // Used for parsing request from WebInterface #[derive(Debug, Serialize, Deserialize)] pub struct NodeInfoEdit { pub identifier: String, pub name: String, pub elements: Vec<ElementInfoEdit>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ElementInfoEdit { pub address: String, pub name: String, pub zone: String, } // Used for NodeElementList response structuring #[derive(Debug, Serialize, Deserialize)] pub struct NodeFiltered { pub identifier: String, pub name: String, pub state: bool, pub elements: Vec<ElementsFiltered>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ElementsFiltered { pub node_identifier: String, pub address: String, pub name: String, pub element_type: String, pub zone: String, pub data: String } // Used for NodeElementList response structuring #[derive(Debug, Serialize, Deserialize)] pub struct UnregisteredNode { pub identifier: String, pub elements: String, }
#![feature(decl_macro)] use rocket::{self, get,post,routes}; use serde::{Serialize, Deserialize}; use rocket_contrib::json::Json; extern crate serde_json; use serde_json::Value; use std::string::String; //use std::fmt; //use std::fmt::Display; #[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)] struct NewTodo { titulo: String } #[get("/hello")] fn hola()->&'static str { "¡mensaje enviado desde get!" } //JSON - String #[post("/", data="<new_todo>")] fn create(new_todo:Json<NewTodo>)->String{ String::from(format!("mensaje {}",new_todo.titulo)) } #[post("/conver", data="<new_todo>")] fn enteros(new_todo:Json<NewTodo>)->String{ let aux=&new_todo.titulo; let sub_strings_decimal: Vec<&str> = aux.split(',').collect(); //println!(" valor split {:?}",sub_strings_decimal.len()); let sub_strings_enteros: Vec<&str> = sub_strings_decimal[0].split('.').collect(); let mut mensaje = String::new(); let mut mensaje_final =String::new(); //decimales let decimales = sub_strings_decimal[1]; let mut a:usize =decimales.len()-1; //tamaño println!(" sub_string [1]= {:?}",sub_strings_decimal[1].len()); let mut numero_decimal = String::new(); let mut aux_decimal=String::new(); let mut cont=1; let mut p=0; let mut vector:Vec<String>= Vec::new(); /*Decimales*/ if sub_strings_decimal[1].len()>24 ||sub_strings_decimal[1].len()==0 { numero_decimal="decimales hasta 10^-24".to_string(); }else{ while a>=0{ aux_decimal =decimales.chars().nth(a).unwrap().to_string() +&aux_decimal; if cont==3{ cont=0; vector.push(aux_decimal.to_string()); aux_decimal = String::new(); } cont+=1; if a==0 { if cont!=1{ vector.push(aux_decimal.to_string()); } break; } a=a-1; } let long =vector.len(); a=0; while a<long{ if a%2==0 && a!=decimales.len()-1&& a!=0{ println!("valor a {:?}",a); numero_decimal=" ".to_string() +&get_millones(p)+ " "+ &numero_decimal; p+=1; }else if a%2!=0{ numero_decimal = " mil ".to_string()+&numero_decimal; } numero_decimal =get_convert(vector[a].parse::<usize>().unwrap())+&numero_decimal; a=a+1; } numero_decimal=numero_decimal+" "+&get_indice(decimales.len()); } /*Enteros*/ if sub_strings_enteros.len()>40{ mensaje ="Números enteros hasta 10^120".to_string(); }else{ let mut num: usize; let mut k:usize =sub_strings_enteros.len()-1; let mut j=0; while k>=0{ if k%2==0 && k!=sub_strings_enteros.len()-1{ //millones mensaje=" ".to_string() +&get_millones(j)+ " "+ &mensaje; j+=1; }else if k%2!=0{ //miles mensaje = " mil ".to_string()+&mensaje; } mensaje =get_convert(sub_strings_enteros[k].parse::<usize>().unwrap())+&mensaje; if k==0{ break; } k=k-1; } } String::from(format!("{}",mensaje + " , "+&numero_decimal)) } /*Función convierte números aletras*/ fn get_convert (num:usize)->String{ /*cinvierte números a letras*/ let mut numero_letras = String::new(); if num>0 && num<10{ String::from(format!("{}",get_unidades(num))) }else if num<20{ String::from(format!("{}",get_especiales(num))) }else if num<100{ let unid = num%10; let dec = num/10; String::from(format!("{} y {}",get_decenas(dec-1),get_unidades(unid))) }else if num<1000{ let un = num%10; let de = (num/10)%10; let ce = num/100; let aux=num%100; if num==100{ String::from("cien") }else if aux>=10 && aux<20{ //----cambios // numero_letras=get_cientos(ce-1)+ " "+&get_decenas(de-1)+ " y "+ &get_unidades(un); // println!("ingresa {:?}",aux); numero_letras=get_cientos(ce-1)+ " "+&get_especiales(aux); String::from(numero_letras) }else{ numero_letras=get_cientos(ce-1)+ " "+&get_decenas(de-1)+ " y "+ &get_unidades(un); String::from(numero_letras) } }else { String::from("numeros mayores") } } fn get_unidades(num:usize)->String{ let unidades = vec!["","uno","dos", "tres","cuatro","cinco","seis", "siete","ocho","nueve"]; // println!("entra unidades {:?}",num); String::from(format!("{}",unidades[num])) } fn get_especiales(num:usize)->String{ let especiales = vec!["diez","once","doce","trece","catorce","quince","deciseis","diecisiete","dieciocho","diecinueve"]; // println!("entra decenas {:?}",num); String::from(format!("{}",especiales[(num-10)])) } fn get_decenas(num:usize)->String{ let decenas = vec!["diez","veinte","treinta","cuarenta","cincuenta","sesenta","setenta","ochenta","novena"]; String::from(format!("{}",decenas[num])) } fn get_millones(num:usize)->String{ let millones = vec!["millónes","billónes","trillónes","cuatrillónes","quintillónes","sextillónes","septillónes","octillónes","nonillónes","decillónes"]; String::from(format!("{}",millones[num])) } fn get_cientos(num:usize)->String{ let centenas = vec!["ciento","doscientos","trecientos","cuatrocientos","quinientos","seiscientos ","setecientos ", "ochocientos ", "novecientos "]; // println!("entra centen {:?}",num); // String::from(format!("{}",centenas[num-10])) String::from(format!("{}",centenas[num])) } fn get_decimales(num:usize)->String{ let decimales = vec!["décimas","centésimas","milésimas","millonésimas","milmillonésimas ","billonésimas ", "milbillonésimas ", "trillonésimas","miltrillonésimas","cuatrillonésimas"]; // println!("entra centen {:?}",num); // String::from(format!("{}",centenas[num-10])) String::from(format!("{}",decimales[num])) } fn get_indice(num:usize)->String{ if num==1{ String::from("décimas") }else if num==2{ String::from("centésimo") }else if num==3 { String::from("milésimo") }else if num>=4 && num<=6{ String::from("millonésimo") }else if num>=7 && num<=9{ String::from("milmillonésimo") }else if num>=10 && num<=12{ String::from("billonésimo") }else if num>=13 && num<=15{ String::from("milbillonésimo") } else if num>=16 && num<=18{ String::from("trillonésimo") }else if num>=19 && num<=21{ String::from("milmillonésimo") }else if num>=22&&num<=24{ String::from("cuatrillonésimo") }else{ String::from("numero no válido") } } fn main() { rocket::ignite().mount("/", routes![hola,create,enteros]).launch(); }
use std::collections::HashSet; use std::fs::{read_dir, File}; use std::io::prelude::*; use std::io::{self, BufReader, BufWriter}; use regex::Regex; use serde::{Deserialize, Serialize}; #[derive(Deserialize)] pub struct InputRecipe { title: String, external_id: String, external_source: String, external_url: String, external_img_url: String, quantity: String, ingredients: Vec<String>, } #[derive(Serialize)] pub struct Ingredient { amount: Option<f64>, unit: Option<String>, name: String, } #[derive(Serialize)] pub struct OutputRecipe { title: String, external_id: String, external_source: String, external_url: String, external_img_url: String, quantity: String, ingredients: Vec<Ingredient>, } pub fn read_input_recipes(file_path: &str) -> io::Result<Vec<InputRecipe>> { let file = File::open(file_path)?; let buffered_reader = BufReader::new(file); let input_recipes: Vec<InputRecipe> = serde_json::from_reader(buffered_reader)?; Ok(input_recipes) } pub fn write_output_recipes(file_path: &str, output_recipes: &Vec<OutputRecipe>) -> io::Result<()> { let file = File::create(file_path)?; let buffered_writer = BufWriter::new(file); serde_json::to_writer(buffered_writer, output_recipes)?; Ok(()) } pub fn generate_ingredient( re1: &Regex, re2: &Regex, re3: &Regex, ingredient: &str, ) -> Option<Ingredient> { let ingredient = ingredient.trim(); if re1.is_match(ingredient) { let caps = re1.captures(ingredient).unwrap(); let amount: f64 = caps .name("amount") .map_or(0f64, |c| c.as_str().parse().unwrap_or(0f64)); // TODO default 0? let unit: String = String::from(caps.name("unit").map_or("", |c| c.as_str())); let name: String = String::from(caps.name("ingredient").map_or("", |c| c.as_str())); Some(Ingredient { amount: Some(amount), unit: Some(unit), name, }) } else if re2.is_match(ingredient) { let caps = re2.captures(ingredient).unwrap(); let amount: f64 = caps .name("amount") .map_or(0f64, |c| c.as_str().parse().unwrap_or(0f64)); // TODO default 0? let name: String = String::from(caps.name("ingredient").map_or("", |c| c.as_str())); Some(Ingredient { amount: Some(amount), unit: None, name, }) } else if re3.is_match(ingredient) { let caps = re3.captures(ingredient).unwrap(); let name: String = String::from(caps.name("ingredient").map_or("", |c| c.as_str())); Some(Ingredient { amount: None, unit: None, name, }) } else { None } } pub fn beautify_jsons(path: &str, re_units: String) -> io::Result<()> { let re1 = Regex::new(&format!( "^(?P<amount>[0-9]+(?:\\.[0-9]+)?) *(?P<unit>{}) *(?P<ingredient>.+)$", re_units )) .unwrap(); let re2 = Regex::new(r"^(?P<amount>[0-9]+(?:\.[0-9]+)?) *(?P<ingredient>.+)$").unwrap(); let re3 = Regex::new(r"^(?P<ingredient>.+)$").unwrap(); let mut output_recipes: Vec<OutputRecipe> = Vec::new(); let mut output_recipes_names: HashSet<String> = HashSet::new(); let mut recipes_files: Vec<String> = Vec::new(); for entry in read_dir(path)? { let entry = entry?; let path = entry.path(); if path.is_file() && path.extension().is_some() && path.extension().unwrap() == "json" { recipes_files.push(String::from(path.as_path().to_str().unwrap())); } } for recipes_file in recipes_files { println!("Using recipes file {}", recipes_file); let input_recipes = read_input_recipes(&recipes_file)?; for recipe in input_recipes { if output_recipes_names.insert(String::from(&recipe.title)) { let mut output_ingredients: Vec<Ingredient> = Vec::new(); for ingredient in recipe.ingredients { output_ingredients .push(generate_ingredient(&re1, &re2, &re3, &ingredient).unwrap()); } output_recipes.push(OutputRecipe { title: recipe.title, external_id: recipe.external_id, external_source: recipe.external_source, external_url: recipe.external_url, external_img_url: recipe.external_img_url, quantity: recipe.quantity, ingredients: output_ingredients, }); } } } write_output_recipes(&format!("{}/recipes.json.new", path), &output_recipes)?; Ok(()) }
pub const VRAM_START: u32 = 0x00000000; pub const VRAM_LENGTH: u32 = 0x00040000; pub const VRAM_END: u32 = VRAM_START + VRAM_LENGTH - 1; pub const CHR_RAM_PATTERN_TABLE_0_START: u32 = 0x00006000; pub const CHR_RAM_PATTERN_TABLE_0_LENGTH: u32 = 0x00002000; pub const CHR_RAM_PATTERN_TABLE_1_START: u32 = 0x0000e000; pub const CHR_RAM_PATTERN_TABLE_1_LENGTH: u32 = 0x00002000; pub const CHR_RAM_PATTERN_TABLE_2_START: u32 = 0x00016000; pub const CHR_RAM_PATTERN_TABLE_2_LENGTH: u32 = 0x00002000; pub const CHR_RAM_PATTERN_TABLE_3_START: u32 = 0x0001e000; pub const CHR_RAM_PATTERN_TABLE_3_LENGTH: u32 = 0x00002000; pub const WINDOW_ATTRIBS_START: u32 = 0x0003d800; pub const WINDOW_ATTRIBS_LENGTH: u32 = 0x00000400; pub const WINDOW_ATTRIBS_END: u32 = WINDOW_ATTRIBS_START + WINDOW_ATTRIBS_LENGTH - 1; pub const INTERRUPT_PENDING_REG: u32 = 0x0005f800; pub const INTERRUPT_ENABLE_REG: u32 = 0x0005f802; pub const INTERRUPT_CLEAR_REG: u32 = 0x0005f804; pub const DISPLAY_CONTROL_READ_REG: u32 = 0x0005f820; pub const DISPLAY_CONTROL_WRITE_REG: u32 = 0x0005f822; pub const LED_BRIGHTNESS_1_REG: u32 = 0x0005f824; pub const LED_BRIGHTNESS_2_REG: u32 = 0x0005f826; pub const LED_BRIGHTNESS_3_REG: u32 = 0x0005f828; pub const LED_BRIGHTNESS_IDLE_REG: u32 = 0x0005f82a; pub const GAME_FRAME_CONTROL_REG: u32 = 0x0005f82e; pub const DRAWING_CONTROL_READ_REG: u32 = 0x0005f840; pub const DRAWING_CONTROL_WRITE_REG: u32 = 0x0005f842; pub const OBJ_GROUP_0_POINTER_REG: u32 = 0x0005f848; pub const OBJ_GROUP_1_POINTER_REG: u32 = 0x0005f84a; pub const OBJ_GROUP_2_POINTER_REG: u32 = 0x0005f84c; pub const OBJ_GROUP_3_POINTER_REG: u32 = 0x0005f84e; pub const BG_PALETTE_0_REG: u32 = 0x0005f860; pub const BG_PALETTE_1_REG: u32 = 0x0005f862; pub const BG_PALETTE_2_REG: u32 = 0x0005f864; pub const BG_PALETTE_3_REG: u32 = 0x0005f866; pub const OBJ_PALETTE_0_REG: u32 = 0x0005f868; pub const OBJ_PALETTE_1_REG: u32 = 0x0005f86a; pub const OBJ_PALETTE_2_REG: u32 = 0x0005f86c; pub const OBJ_PALETTE_3_REG: u32 = 0x0005f86e; pub const CLEAR_COLOR_REG: u32 = 0x0005f870; pub const CHR_RAM_PATTERN_TABLE_0_MIRROR_START: u32 = 0x00078000; pub const CHR_RAM_PATTERN_TABLE_0_MIRROR_LENGTH: u32 = CHR_RAM_PATTERN_TABLE_0_LENGTH; pub const CHR_RAM_PATTERN_TABLE_0_MIRROR_END: u32 = CHR_RAM_PATTERN_TABLE_0_MIRROR_START + CHR_RAM_PATTERN_TABLE_0_MIRROR_LENGTH - 1; pub const CHR_RAM_PATTERN_TABLE_1_MIRROR_START: u32 = 0x0007a000; pub const CHR_RAM_PATTERN_TABLE_1_MIRROR_LENGTH: u32 = CHR_RAM_PATTERN_TABLE_1_LENGTH; pub const CHR_RAM_PATTERN_TABLE_1_MIRROR_END: u32 = CHR_RAM_PATTERN_TABLE_1_MIRROR_START + CHR_RAM_PATTERN_TABLE_1_MIRROR_LENGTH - 1; pub const CHR_RAM_PATTERN_TABLE_2_MIRROR_START: u32 = 0x0007c000; pub const CHR_RAM_PATTERN_TABLE_2_MIRROR_LENGTH: u32 = CHR_RAM_PATTERN_TABLE_2_LENGTH; pub const CHR_RAM_PATTERN_TABLE_2_MIRROR_END: u32 = CHR_RAM_PATTERN_TABLE_2_MIRROR_START + CHR_RAM_PATTERN_TABLE_2_MIRROR_LENGTH - 1; pub const CHR_RAM_PATTERN_TABLE_3_MIRROR_START: u32 = 0x0007e000; pub const CHR_RAM_PATTERN_TABLE_3_MIRROR_LENGTH: u32 = CHR_RAM_PATTERN_TABLE_3_LENGTH; pub const CHR_RAM_PATTERN_TABLE_3_MIRROR_END: u32 = CHR_RAM_PATTERN_TABLE_3_MIRROR_START + CHR_RAM_PATTERN_TABLE_3_MIRROR_LENGTH - 1;
use procon_reader::ProconReader; fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let x: u32 = rd.get(); if x < 40 { println!("{}", 40 - x); } else if x < 70 { println!("{}", 70 - x); } else if x < 90 { println!("{}", 90 - x); } else { println!("expert"); } }
use std::{env, marker::PhantomData, path}; use super::Module; use crate::{terminal::Color, Segment, R}; pub struct Cwd<S: CwdScheme> { max_length: usize, wanted_seg_num: usize, resolve_symlinks: bool, scheme: PhantomData<S>, } pub trait CwdScheme { const CWD_FG: Color; const PATH_FG: Color; const PATH_BG: Color; const HOME_FG: Color; const HOME_BG: Color; const SEPARATOR_FG: Color; const CWD_HOME_SYMBOL: &'static str = "~"; } impl<S: CwdScheme> Cwd<S> { pub fn new(max_length: usize, wanted_seg_num: usize, resolve_symlinks: bool) -> Cwd<S> { Cwd { max_length, wanted_seg_num, resolve_symlinks, scheme: PhantomData, } } } macro_rules! append_cwd_segments { ($segments: ident, $iter: expr) => { for val in $iter { $segments.push(Segment::special(format!("{}", val), S::PATH_FG, S::PATH_BG, '/', S::SEPARATOR_FG)); } }; } impl<S: CwdScheme> Module for Cwd<S> { fn append_segments(&mut self, segments: &mut Vec<Segment>) -> R<()> { let current_dir = if self.resolve_symlinks { env::current_dir()? } else { path::PathBuf::from(env::var("PWD")?) }; let mut cwd = current_dir.to_str().unwrap(); if let Some(home_path) = dirs::home_dir() { let home_str = home_path.to_str().unwrap(); if cwd.starts_with(home_str) { segments.push(Segment::simple(format!("{}", S::CWD_HOME_SYMBOL), S::HOME_FG, S::HOME_BG)); cwd = &cwd[home_str.len()..] } } let depth = cwd.matches('/').count(); if (cwd.len() > self.max_length as usize) && (depth > self.wanted_seg_num) { let left = self.wanted_seg_num / 2; let right = self.wanted_seg_num - left; let start = cwd.split('/').skip(1).take(left); let end = cwd.split('/').skip(depth - right + 1); append_cwd_segments!(segments, start); segments.push(Segment::special("\u{2026}", S::PATH_FG, S::PATH_BG, '/', S::SEPARATOR_FG)); append_cwd_segments!(segments, end); } else { append_cwd_segments!(segments, cwd.split('/').skip(1)); }; // todo get rid of me if let Some(last) = segments.last_mut() { if &last.val == " " { last.val = " / ".to_string() } last.fg = S::CWD_FG.into_fg(); last.sep = '/'; last.sep_col = last.bg.transpose(); } Ok(()) } }
#[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::IC { #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPIDCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPIDCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPDZCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPDZCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPIOCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPIOCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 2); self.w.bits |= ((value as u32) & 1) << 2; self.w } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPUFCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPUFCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 3); self.w.bits |= ((value as u32) & 1) << 3; self.w } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPOFCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPOFCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Proxy"] pub struct _SYSEXC_IC_FPIXCICW<'a> { w: &'a mut W, } impl<'a> _SYSEXC_IC_FPIXCICW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 5); self.w.bits |= ((value as u32) & 1) << 5; self.w } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Floating-Point Input Denormal Exception Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpidcic(&mut self) -> _SYSEXC_IC_FPIDCICW { _SYSEXC_IC_FPIDCICW { w: self } } #[doc = "Bit 1 - Floating-Point Divide By 0 Exception Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpdzcic(&mut self) -> _SYSEXC_IC_FPDZCICW { _SYSEXC_IC_FPDZCICW { w: self } } #[doc = "Bit 2 - Floating-Point Invalid Operation Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpiocic(&mut self) -> _SYSEXC_IC_FPIOCICW { _SYSEXC_IC_FPIOCICW { w: self } } #[doc = "Bit 3 - Floating-Point Underflow Exception Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpufcic(&mut self) -> _SYSEXC_IC_FPUFCICW { _SYSEXC_IC_FPUFCICW { w: self } } #[doc = "Bit 4 - Floating-Point Overflow Exception Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpofcic(&mut self) -> _SYSEXC_IC_FPOFCICW { _SYSEXC_IC_FPOFCICW { w: self } } #[doc = "Bit 5 - Floating-Point Inexact Exception Interrupt Clear"] #[inline(always)] pub fn sysexc_ic_fpixcic(&mut self) -> _SYSEXC_IC_FPIXCICW { _SYSEXC_IC_FPIXCICW { w: self } } }
//! Event types for runtimes. use oasis_core_runtime::transaction::tags::Tag; /// An event emitted by the runtime. /// /// This trait can be derived: /// ``` /// # #[cfg(feature = "oasis-runtime-sdk-macros")] /// # mod example { /// # use oasis_runtime_sdk_macros::Event; /// const MODULE_NAME: &str = "my-module"; /// #[derive(Clone, Debug, cbor::Encode, Event)] /// #[cbor(untagged)] /// #[sdk_event(autonumber)] // `module_name` meta is required if `MODULE_NAME` isn't in scope /// enum MyEvent { /// Greeting(String), // autonumbered to 0 /// #[sdk_event(code = 2)] // manually numbered to 2 (`code` is required if not autonumbering) /// DontPanic, /// Salutation { // autonumbered to 1 /// plural: bool, /// } /// } /// # } /// ``` pub trait Event: Sized + cbor::Encode { /// Name of the module that emitted the event. fn module_name() -> &'static str; /// Code uniquely identifying the event. fn code(&self) -> u32; /// Converts an emitted event into a tag that can be emitted by the runtime. /// /// # Key /// /// ```text /// <module (variable size bytes)> <code (big-endian u32)> /// ``` /// /// # Value /// /// CBOR-serialized event value. /// fn into_tag(self) -> Tag { tag_for_event(Self::module_name(), self.code(), cbor::to_vec(self)) } } impl Event for () { fn module_name() -> &'static str { "(none)" } fn code(&self) -> u32 { Default::default() } } /// Generate an Oasis Core tag corresponding to the passed event triple. pub fn tag_for_event(module_name: &str, code: u32, value: Vec<u8>) -> Tag { Tag::new( [module_name.as_bytes(), &code.to_be_bytes()] .concat() .to_vec(), value, ) }
//! Sum all the bytes of a data structure or an array. //! //! A commonly used method to ensure the validity of data is to calculate //! the sum of all the bytes, and compare it to a known value. //! //! **Note**: if you need a way to ensure data integrity, use some better algorithm like CRC-32. //! This crate is only intended to be used with legacy APIs. #![no_std] #![deny(missing_docs)] #![cfg_attr(feature = "cargo-clippy", deny(clippy))] use core::{mem, slice}; /// Sums all the bytes of a data structure. pub fn sum<T>(data: &T) -> u8 { let ptr = data as *const _ as *const u8; let len = mem::size_of::<T>(); let data = unsafe { slice::from_raw_parts(ptr, len) }; sum_slice(data) } /// Sums all the bytes in an array. pub fn sum_slice(data: &[u8]) -> u8 { data.iter().fold(0, |a, &b| a.wrapping_add(b)) } #[cfg(test)] mod tests { use super::*; #[test] fn simple_sum() { struct Simple(u32, u32); let simple = Simple(0xAA_00_BB_00, 0xAA_00_00_00); assert_eq!(sum(&simple), 15); } #[test] fn array_sum() { let data: &[u8] = &[1, 0, 8, 24, 45, 192, 25, 253, 0]; assert_eq!(sum_slice(&data), 36); } #[test] fn zero_size_type() { struct Zero; assert_eq!(sum(&Zero), 0); } }
pub const NODE_PUBLIC : usize = 28; pub const NODE_PRIVATE : usize = 32; pub const ACCOUNT_ID : usize = 0; pub const FAMILY_SEED : usize = 33; pub const ED25519_SEED : [u8; 3] = [0x01, 0xe1, 0x4b]; pub const SIGN_TYPE : [&'static str; 2] = ["ed25519", "secp256k1"]; pub trait BaseDataI { fn get_version(&self) -> Option<String>; fn get_versions(&self) -> Option<Vec<String>>; fn get_version_type(&self) -> Option<String>; fn get_checked(&self) -> Option<bool>; fn get_expected_length(&self) -> Option<usize>; } #[derive(Debug)] pub struct EdSeed { pub expected_length: usize, pub version: [u8; 3], } impl Default for EdSeed { fn default() -> Self { EdSeed { expected_length: 16, version: ED25519_SEED, } } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // Seed // #[derive(Debug)] pub struct Seed { pub version_types: [&'static str; 2], pub version: usize, pub expected_length: usize, } impl Default for Seed { fn default() -> Self { Seed { version_types: SIGN_TYPE, version: FAMILY_SEED, expected_length: 16, } } } impl BaseDataI for Seed { fn get_version(&self) -> Option<String> { Some(self.version.to_string()) } fn get_versions(&self) -> Option<Vec<String>> { None } fn get_version_type(&self) -> Option<String> { None } fn get_checked(&self) -> Option<bool> { None } fn get_expected_length(&self) -> Option<usize> { Some(self.expected_length) } } #[derive(Debug)] pub struct AccountID { pub version: usize, pub expected_length: usize, } impl Default for AccountID { fn default() -> Self { AccountID { version: ACCOUNT_ID, expected_length: 20, } } } //////////////////////////////////////////////////////////////////////////////////////////////////// // // Address // #[derive(Debug)] pub struct Address { pub version: usize, pub expected_length: usize, } impl Default for Address { fn default() -> Self { Address { version: ACCOUNT_ID, expected_length: 20, } } } impl BaseDataI for Address { fn get_version(&self) -> Option<String> { None } fn get_versions(&self) -> Option<Vec<String>> { None } fn get_version_type(&self) -> Option<String> { None } fn get_checked(&self) -> Option<bool> { None } fn get_expected_length(&self) -> Option<usize> { Some(self.expected_length) } } #[derive(Debug)] pub struct NodePublic { pub version: usize, pub expected_length: usize } impl Default for NodePublic { fn default() -> Self { NodePublic { version: NODE_PUBLIC, expected_length: 33, } } } #[derive(Debug)] pub struct NodePrivate { pub version: usize, pub expected_length: usize, } impl Default for NodePrivate { fn default() -> Self { NodePrivate { version: NODE_PRIVATE, expected_length: 32, } } } #[derive(Debug)] pub struct K256Seed { pub version: usize, pub expected_length: usize, } impl Default for K256Seed { fn default() -> Self { K256Seed { version: FAMILY_SEED, expected_length: 16, } } } #[derive(Debug)] pub enum BASEStates { EdSeed(EdSeed), Seed(Seed), AccountID(AccountID), Address(Address), NodePublic(NodePublic), NodePrivate(NodePrivate), K256Seed(K256Seed), }
use std::fmt::Debug; #[derive(Debug)] struct Vehicle { handbrake_enabled: bool } fn manifest_presence<T>(v: T) -> T where T: Debug { println!("Me be: {:?}", v); v } type CPS = Box<Fn(Vehicle) -> Vehicle>; fn vehicle_run(cps: CPS) -> CPS { Box::new(move |v: Vehicle| { let v: Vehicle = cps(v); println!("Running: ({:?})", &v); v } ) } fn vehicle_lights_on(cps: CPS) -> CPS { Box::new(move |v: Vehicle| { let v: Vehicle = cps(v); println!("Lights on: ({:?})", &v); v } ) } pub fn run() { println!("-------------------- {} --------------------", file!()); let v = Vehicle { handbrake_enabled: true }; println!("%## RAW ###"); let v = manifest_presence(v); println!("%## DECORATED ###"); let vrl: Box<Fn(Vehicle) -> Vehicle> = vehicle_lights_on(vehicle_run(Box::new(manifest_presence))); vrl(v); }
use super::default_process_fn; use super::Printer; use crossterm::style::Color; use std::io::Write; type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; #[test] fn write_from_terminal_start_cursor_pos_correct() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let origin_pos = p.cursor.pos; p.write_from_terminal_start("hello", Color::Red)?; assert_eq!(p.cursor.pos.current_pos.0, 5); assert_eq!(p.cursor.pos.current_pos.1, origin_pos.current_pos.1); Ok(()) } #[test] fn writenew_line_no_scroll() { let mut p = Printer::new(std::io::sink(), "".to_owned()); let b = "Hello world".into(); p.cursor.pos.starting_pos.0 = 0; p.cursor.pos.starting_pos.1 = 0; p.cursor.goto_start(); assert_eq!(p.cursor.pos.current_pos, p.cursor.pos.starting_pos); let origin_pos = p.cursor.pos; p.write_newline(&b); assert_eq!(origin_pos.starting_pos.1 + 1, p.cursor.pos.starting_pos.1); assert_eq!(origin_pos.current_pos.1 + 1, p.cursor.pos.current_pos.1); } #[test] fn writenew_line_with_scroll() { let mut p = Printer::new(std::io::sink(), "".to_owned()); let b = "Hello world".into(); p.cursor.pos.starting_pos.0 = 0; p.cursor.pos.starting_pos.1 = p.cursor.bound.height - 1; p.cursor.goto_start(); assert_eq!(p.cursor.pos.current_pos, p.cursor.pos.starting_pos); let origin_pos = p.cursor.pos; p.write_newline(&b); assert_eq!(origin_pos.starting_pos.1, p.cursor.pos.starting_pos.1); assert_eq!(origin_pos.current_pos.1, p.cursor.pos.current_pos.1); } #[test] fn scroll_up() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let origin_pos = p.cursor.pos; p.scroll_up(3); assert_eq!( origin_pos.starting_pos.1.saturating_sub(3), p.cursor.pos.starting_pos.1 ); assert_eq!( origin_pos.current_pos.1.saturating_sub(3), p.cursor.pos.current_pos.1 ); Ok(()) } #[test] fn scroll_because_input_needs_scroll() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let b = "\n\n\n".into(); p.cursor.pos.starting_pos.0 = 0; p.cursor.pos.starting_pos.1 = p.cursor.bound.height - 1; p.cursor.goto_start(); let original_pos = p.cursor.pos; p.scroll_if_needed_for_input(&b); assert_eq!(original_pos.starting_pos.1 - 3, p.cursor.pos.starting_pos.1); Ok(()) } #[test] fn dont_scroll_because_input_doesent_need_scroll() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let b = "\n\n\n".into(); p.cursor.pos.starting_pos.0 = 0; p.cursor.pos.starting_pos.1 = 0; p.cursor.goto_start(); let original_pos = p.cursor.pos; p.scroll_if_needed_for_input(&b); assert_eq!(original_pos.starting_pos.1, p.cursor.pos.starting_pos.1); Ok(()) } #[test] fn calculate_bounds_correctly() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let width = p.cursor.bound.width; let height = p.cursor.bound.height; let queue = default_process_fn(&"alloc\nprint".into()); // 1 move_to_and_modify_start(&mut p, 0, 0); p.recalculate_bounds(queue)?; let expected_bound = { let mut v = vec![width - 1; height]; v[0] = 9; v[1] = 9; v }; assert_eq!(expected_bound, p.cursor.bound.bound); Ok(()) } #[test] pub fn calculate_bounds_correctly2() -> Result<()> { let mut p = Printer::new(std::io::sink(), "".to_owned()); let width = p.cursor.bound.width; let height = p.cursor.bound.height; let queue = default_process_fn(&"A\tz\nBC\n".into()); // 2 move_to_and_modify_start(&mut p, 0, height - 5); p.recalculate_bounds(queue)?; let expected_bound = { let mut v = vec![width - 1; height]; v[height - 5] = 7; v[height - 4] = 6; v[height - 3] = 4; v }; assert_eq!(expected_bound, p.cursor.bound.bound); Ok(()) } // helper fn move_to_and_modify_start(printer: &mut Printer<impl Write>, x: usize, y: usize) { printer.cursor.pos.starting_pos.0 = x; printer.cursor.pos.starting_pos.1 = y; printer.cursor.goto_start(); }
use std::cmp::Ordering; use std::sync::Arc; use askama::Template; use crate::db::Db; use crate::error::Error; use crate::fetcher::Currency; #[derive(Template)] #[template(path = "index.html")] struct CurrenciesTemplate<'a> { date: &'a str, currencies: &'a [Currency], } // order currencies so that EUR comes first then gomes USD and then GBP fn sort_currencies(currencies: &mut [Currency]) { currencies.sort_by( |curr1, curr2| match (curr1.name.as_ref(), curr2.name.as_ref()) { ("EUR", _) => Ordering::Less, (_, "EUR") => Ordering::Greater, ("USD", "GBP") | ("GBP", "USD") => Ordering::Equal, ("USD", _) => Ordering::Less, (_, "USD") => Ordering::Greater, ("GBP", _) => Ordering::Less, (_, "GBP") => Ordering::Greater, _ => Ordering::Equal, }, ); } pub async fn index(db: Arc<Db>) -> Result<impl warp::Reply, warp::Rejection> { let mut date = db.get_current_rates().await?; sort_currencies(&mut date.currencies); let rendered = CurrenciesTemplate { date: &date.value, currencies: date.currencies.as_slice(), } .render() .map_err(Error::Template)?; Ok(warp::reply::html(rendered)) } #[cfg(test)] mod tests { use super::Currency; #[test] fn sort_currencies() { let mut currencies = Vec::new(); currencies.push(Currency { name: "JPY".to_string(), rate: 0.0, }); currencies.push(Currency { name: "RON".to_string(), rate: 0.0, }); currencies.push(Currency { name: "USD".to_string(), rate: 0.0, }); currencies.push(Currency { name: "CZK".to_string(), rate: 0.0, }); currencies.push(Currency { name: "GBP".to_string(), rate: 0.0, }); currencies.push(Currency { name: "CHF".to_string(), rate: 0.0, }); currencies.push(Currency { name: "EUR".to_string(), rate: 0.0, }); currencies.push(Currency { name: "RUB".to_string(), rate: 0.0, }); super::sort_currencies(&mut currencies); assert_eq!(&currencies[0].name, "EUR"); assert_eq!(&currencies[1].name, "USD"); assert_eq!(&currencies[2].name, "GBP"); } }
//! This file exposes a single function, monitor, that is launched in a special //! thread and pulls the evaluations results, store them and then updates the //! Store accordingly. use crate::device::Context; use crate::explorer::candidate::Candidate; use crate::explorer::config::Config; use crate::explorer::logger::LogMessage; use crate::explorer::store::Store; use futures::prelude::*; use futures::{executor, future, task, Async}; use log::warn; use serde::{Deserialize, Serialize}; use std::io::Write; use std::sync::{ self, atomic::{AtomicBool, Ordering}, Arc, }; use std::time::{Duration, Instant}; use std::{self, thread}; use utils::unwrap; pub type MonitorMessage<T> = (Candidate, f64, <T as Store>::PayLoad); /// Indicates why the exploration was terminated. #[derive(Serialize, Deserialize)] pub enum TerminationReason { /// The maximal number of evaluation was reached. MaxEvaluations, /// The timeout was reached. Timeout, } impl std::fmt::Display for TerminationReason { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self { TerminationReason::MaxEvaluations => { write!(f, "the maximum number of evaluations was reached") } TerminationReason::Timeout => { write!(f, "the maximum exploration time was reached") } } } } struct Status { best_candidate: Option<(Candidate, f64)>, num_evaluations: usize, } impl Default for Status { fn default() -> Self { Status { best_candidate: None, num_evaluations: 0, } } } /// This function is an interface supposed to make a connection between the /// Store and the evaluator. Retrieve evaluations, retains the results and /// update the store accordingly. pub fn monitor<T, E>( config: &Config, context: &dyn Context, candidate_store: &T, recv: futures::sync::mpsc::Receiver<MonitorMessage<T>>, log_sender: sync::mpsc::SyncSender<LogMessage<E>>, ) -> Option<Candidate> where T: Store, { warn!("Monitor waiting for evaluation results"); let t0 = Instant::now(); let mut status = Status::default(); let res = { let log_sender_ref = &log_sender; let status_mut = &mut status; let mut future: Box<dyn Future<Item = _, Error = _>> = Box::new(recv.map_err(|()| unreachable!()).for_each(move |message| { handle_message( config, context, message, t0, candidate_store, log_sender_ref, status_mut, ) })); if let Some(timeout_mins) = config.timeout { future = Box::new( future .select(timeout(Duration::from_secs(timeout_mins * 60))) .map(|((), _)| ()) .map_err(|(err, _)| err), ); } executor::spawn(future).wait_future() }; let duration = t0.elapsed(); let duration_secs = duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-9; warn!( "Exploration finished in {}s with {} candidates evaluated (avg {} candidate/s).", duration_secs, status.num_evaluations, status.num_evaluations as f64 / duration_secs ); match res { Ok(_) => warn!("No candidates to try anymore"), Err(reason) => { warn!("exploration stopped because {}", reason); candidate_store.stop_exploration(); unwrap!(log_sender.send(LogMessage::Finished { reason, timestamp: duration, num_evaluations: status.num_evaluations })); } } status.best_candidate.map(|x| x.0) } /// Depending on the value of the evaluation we just did, computes the new cut /// value for the store Can be 0 if we decide to stop the search fn get_new_cut(config: &Config, eval: f64) -> f64 { if let Some(bound) = config.stop_bound { if eval < bound { return 0.; } } if let Some(ratio) = config.distance_to_best { (1. - ratio / 100.) * eval } else { eval } } /// All work that has to be done on reception of a message, meaning updating /// the best cand if needed, logging, committing back to candidate_store fn handle_message<T, E>( config: &Config, context: &dyn Context, message: MonitorMessage<T>, start_time: Instant, candidate_store: &T, log_sender: &sync::mpsc::SyncSender<LogMessage<E>>, status: &mut Status, ) -> Result<(), TerminationReason> where T: Store, { let (cand, eval, payload) = message; let wall = start_time.elapsed(); warn!("Got a new evaluation after {}, bound: {:.4e} score: {:.4e}, current best: {:.4e}", status.num_evaluations, cand.bound.value(), eval, status.best_candidate.as_ref().map_or(std::f64::INFINITY, |best: &(Candidate, f64)| best.1 )); candidate_store.commit_evaluation(&cand.actions, payload, eval); let change = status .best_candidate .as_ref() .map(|&(_, time)| time > eval) .unwrap_or(true); if change { warn!("Got a new best candidate, score: {:.3e}, {}", eval, cand); candidate_store.update_cut(get_new_cut(config, eval)); let log_message = LogMessage::NewBest { score: eval, cpt: status.num_evaluations, timestamp: wall, }; unwrap!(log_sender.send(log_message)); config .output_path(format!("best_{}", status.num_evaluations)) .and_then(|output_path| { std::fs::create_dir_all(&output_path)?; write!( std::fs::File::create(output_path.join("actions.json"))?, "{}", serde_json::to_string(&cand.actions).unwrap() )?; cand.space.dump_code(context, output_path.join("code")) }) .unwrap_or_else(|err| warn!("Error while dumping candidate: {}", err)); status.best_candidate = Some((cand, eval)); } // Note that it is possible that we actually didn't make an // evaluation here, because the evaluator may return an infinite // runtime for some of the candidates in its queue when a new best // candidate was found. In this case, `eval` is be infinite, and // we don't count the corresponding evaluation towards the number // of evaluations performed (a sequential, non-parallel // implementation of the search algorithm would not have selected // this candidate since it would get cut). if !eval.is_infinite() { status.num_evaluations += 1; if let Some(max_evaluations) = config.max_evaluations { if status.num_evaluations >= max_evaluations { return Err(TerminationReason::MaxEvaluations); } } } Ok(()) } struct TimeoutWorker { running: Arc<AtomicBool>, thread: thread::Thread, } impl Drop for TimeoutWorker { fn drop(&mut self) { self.running.store(false, Ordering::Relaxed); self.thread.unpark(); } } /// Creates a new future which will return with a `TerminationReason::Timeout` error after the /// `duration` has elapsed. /// /// This creates a background thread which sleeps for the requested amount of time, then notifies /// the future to be polled and return with an error. fn timeout(duration: Duration) -> impl Future<Item = (), Error = TerminationReason> { let start_time = std::time::Instant::now(); let mut worker = None; future::poll_fn(move || { if start_time.elapsed() > duration { Err(TerminationReason::Timeout) } else { // If we were polled before the timeout exceeded, we need to setup a worker thread // which will notify the task when the timeout expires. If we don't, the futures // runtime may never poll on our future again (un-notified polls after the first one // are allowed, but not guaranteed), in which case we would never actually time out. if worker.is_none() { let running = Arc::new(AtomicBool::new(true)); let task = task::current(); let thread_running = Arc::clone(&running); let thread = thread::Builder::new() .name("Telamon - Timeout".to_string()) .spawn(move || loop { if !thread_running.load(Ordering::Relaxed) { break; } let elapsed = start_time.elapsed(); if elapsed < duration { // Use park_timeout instead of sleep here so that we can be woken up and // exit when the `TimeoutWorker` goes out of scope. thread::park_timeout(duration - elapsed); } else { task.notify(); } }) .unwrap() .thread() .clone(); worker = Some(TimeoutWorker { running, thread }); } Ok(Async::NotReady) } }) }
//! TODO docs use crate::action::Action; use crate::bytes::{NumBytes, Read, Write}; use crate::time::TimePointSec; use crate::varint::UnsignedInt; use alloc::vec::Vec; /// TODO docs #[derive( Read, Write, NumBytes, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Hash, Default, )] #[eosio(crate_path = "crate::bytes")] pub struct TransactionExtension(u16, Vec<char>); /// TODO docs #[derive( Read, Write, NumBytes, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Hash, Default, )] #[eosio(crate_path = "crate::bytes")] pub struct TransactionHeader { /// TODO docs pub expiration: TimePointSec, /// TODO docs pub ref_block_num: u16, /// TODO docs pub ref_block_prefix: u32, /// number of 8 byte words this transaction can serialize into after compressions pub max_net_usage_words: UnsignedInt, /// number of CPU usage units to bill transaction for pub max_cpu_usage_ms: u8, /// number of seconds to delay transaction, default: 0 pub delay_sec: UnsignedInt, } /// TODO docs #[derive(Clone, Debug, Read, Write, NumBytes, Default)] #[eosio(crate_path = "crate::bytes")] pub struct Transaction<T: Default + Clone = Vec<u8>> { /// TODO docs pub header: TransactionHeader, /// TODO docs pub context_free_actions: Vec<Action<T>>, /// TODO docs pub actions: Vec<Action<T>>, /// TODO docs pub transaction_extensions: Vec<TransactionExtension>, } /// TODO docs /// TODO represet this as a String for RPC #[derive(Clone, Debug)] pub struct TransactionId(u128); impl TransactionId { /// TODO docs #[must_use] pub const fn as_u128(&self) -> u128 { self.0 } } impl From<u128> for TransactionId { #[must_use] fn from(value: u128) -> Self { Self(value) } } impl AsRef<TransactionId> for TransactionId { fn as_ref(&self) -> &Self { self } }
// 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 #[cfg(any(feature = "v2_12", feature = "dox"))] use glib::translate::*; #[cfg(any(feature = "v2_12", feature = "dox"))] use glib::GString; use webkit2_webextension_sys; glib_wrapper! { #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ConsoleMessage(Boxed<webkit2_webextension_sys::WebKitConsoleMessage>); match fn { copy => |ptr| webkit2_webextension_sys::webkit_console_message_copy(mut_override(ptr)), free => |ptr| webkit2_webextension_sys::webkit_console_message_free(ptr), get_type => || webkit2_webextension_sys::webkit_console_message_get_type(), } } impl ConsoleMessage { //#[cfg(any(feature = "v2_12", feature = "dox"))] //pub fn get_level(&mut self) -> /*Ignored*/ConsoleMessageLevel { // unsafe { TODO: call webkit2_webextension_sys:webkit_console_message_get_level() } //} #[cfg(any(feature = "v2_12", feature = "dox"))] pub fn get_line(&mut self) -> u32 { unsafe { webkit2_webextension_sys::webkit_console_message_get_line(self.to_glib_none_mut().0) } } //#[cfg(any(feature = "v2_12", feature = "dox"))] //pub fn get_source(&mut self) -> /*Ignored*/ConsoleMessageSource { // unsafe { TODO: call webkit2_webextension_sys:webkit_console_message_get_source() } //} #[cfg(any(feature = "v2_12", feature = "dox"))] pub fn get_source_id(&mut self) -> Option<GString> { unsafe { from_glib_none( webkit2_webextension_sys::webkit_console_message_get_source_id( self.to_glib_none_mut().0, ), ) } } #[cfg(any(feature = "v2_12", feature = "dox"))] pub fn get_text(&mut self) -> Option<GString> { unsafe { from_glib_none(webkit2_webextension_sys::webkit_console_message_get_text( self.to_glib_none_mut().0, )) } } }
use libc; use libc::toupper; use crate::clist::*; use crate::mailimf_types::*; use crate::mailmime_decode::*; use crate::mailmime_types::*; use crate::mmapstring::*; use crate::x::*; pub const UNSTRUCTURED_START: libc::c_uint = 0; pub const UNSTRUCTURED_LF: libc::c_uint = 2; pub const UNSTRUCTURED_CR: libc::c_uint = 1; pub const UNSTRUCTURED_WSP: libc::c_uint = 3; pub const UNSTRUCTURED_OUT: libc::c_uint = 4; pub const STATE_ZONE_ERR: libc::c_uint = 4; pub const STATE_ZONE_OK: libc::c_uint = 3; pub const STATE_ZONE_3: libc::c_uint = 2; pub const STATE_ZONE_2: libc::c_uint = 1; pub const STATE_ZONE_CONT: libc::c_uint = 5; pub const STATE_ZONE_1: libc::c_uint = 0; pub const MONTH_A: libc::c_uint = 5; pub const MONTH_MA: libc::c_uint = 4; pub const MONTH_M: libc::c_uint = 3; pub const MONTH_JU: libc::c_uint = 2; pub const MONTH_J: libc::c_uint = 1; pub const MONTH_START: libc::c_uint = 0; pub const DAY_NAME_S: libc::c_uint = 2; pub const DAY_NAME_T: libc::c_uint = 1; pub const DAY_NAME_START: libc::c_uint = 0; pub const HEADER_RES: libc::c_uint = 5; pub const HEADER_S: libc::c_uint = 4; pub const HEADER_RE: libc::c_uint = 3; pub const HEADER_R: libc::c_uint = 2; pub const HEADER_C: libc::c_uint = 1; pub const HEADER_START: libc::c_uint = 0; /* day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" */ #[derive(Copy, Clone)] #[repr(C)] pub struct mailimf_token_value { pub value: libc::c_int, pub str_0: *mut libc::c_char, } /* mailimf_message_parse will parse the given message @param message this is a string containing the message content @param length this is the size of the given string @param indx this is a pointer to the start of the message in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_message_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_message, ) -> libc::c_int { let mut fields: *mut mailimf_fields = 0 as *mut mailimf_fields; let mut body: *mut mailimf_body = 0 as *mut mailimf_body; let mut msg: *mut mailimf_message = 0 as *mut mailimf_message; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_fields_parse(message, length, &mut cur_token, &mut fields); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_body_parse(message, length, &mut cur_token, &mut body); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { msg = mailimf_message_new(fields, body); if msg.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; mailimf_body_free(body); } else { *indx = cur_token; *result = msg; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_fields_free(fields); } } return res; } /* mailimf_body_parse will parse the given text part of a message @param message this is a string containing the message text part @param length this is the size of the given string @param indx this is a pointer to the start of the message text part in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_body_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_body, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut body: *mut mailimf_body = 0 as *mut mailimf_body; cur_token = *indx; body = mailimf_body_new( message.offset(cur_token as isize), length.wrapping_sub(cur_token), ); if body.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } cur_token = length; *result = body; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_crlf_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_char_parse(message, length, &mut cur_token, '\r' as i32 as libc::c_char); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_char_parse(message, length, &mut cur_token, '\n' as i32 as libc::c_char); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_char_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut token: libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; cur_token = *indx; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if *message.offset(cur_token as isize) as libc::c_int == token as libc::c_int { cur_token = cur_token.wrapping_add(1); *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } else { return MAILIMF_ERROR_PARSE as libc::c_int; }; } /* mailimf_fields_parse will parse the given header fields @param message this is a string containing the header fields @param length this is the size of the given string @param indx this is a pointer to the start of the header fields in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_fields_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_fields, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut fields: *mut mailimf_fields = 0 as *mut mailimf_fields; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; list = 0 as *mut clist; r = mailimf_struct_multiple_parse( message, length, &mut cur_token, &mut list, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut mailimf_field, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_field_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_field_free)), ); /* if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) { res = r; goto err; } */ match r { 0 => { /* do nothing */ current_block = 11050875288958768710; } 1 => { list = clist_new(); if list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 6724962012950341805; } else { current_block = 11050875288958768710; } } _ => { res = r; current_block = 6724962012950341805; } } match current_block { 11050875288958768710 => { fields = mailimf_fields_new(list); if fields.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !list.is_null() { clist_foreach( list, ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, clist_func, >(Some(mailimf_field_free)), 0 as *mut libc::c_void, ); clist_free(list); } } else { *result = fields; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } _ => {} } return res; } unsafe fn mailimf_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_field, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut type_0: libc::c_int = 0; let mut return_path: *mut mailimf_return = 0 as *mut mailimf_return; let mut resent_date: *mut mailimf_orig_date = 0 as *mut mailimf_orig_date; let mut resent_from: *mut mailimf_from = 0 as *mut mailimf_from; let mut resent_sender: *mut mailimf_sender = 0 as *mut mailimf_sender; let mut resent_to: *mut mailimf_to = 0 as *mut mailimf_to; let mut resent_cc: *mut mailimf_cc = 0 as *mut mailimf_cc; let mut resent_bcc: *mut mailimf_bcc = 0 as *mut mailimf_bcc; let mut resent_msg_id: *mut mailimf_message_id = 0 as *mut mailimf_message_id; let mut orig_date: *mut mailimf_orig_date = 0 as *mut mailimf_orig_date; let mut from: *mut mailimf_from = 0 as *mut mailimf_from; let mut sender: *mut mailimf_sender = 0 as *mut mailimf_sender; let mut reply_to: *mut mailimf_reply_to = 0 as *mut mailimf_reply_to; let mut to: *mut mailimf_to = 0 as *mut mailimf_to; let mut cc: *mut mailimf_cc = 0 as *mut mailimf_cc; let mut bcc: *mut mailimf_bcc = 0 as *mut mailimf_bcc; let mut message_id: *mut mailimf_message_id = 0 as *mut mailimf_message_id; let mut in_reply_to: *mut mailimf_in_reply_to = 0 as *mut mailimf_in_reply_to; let mut references: *mut mailimf_references = 0 as *mut mailimf_references; let mut subject: *mut mailimf_subject = 0 as *mut mailimf_subject; let mut comments: *mut mailimf_comments = 0 as *mut mailimf_comments; let mut keywords: *mut mailimf_keywords = 0 as *mut mailimf_keywords; let mut optional_field: *mut mailimf_optional_field = 0 as *mut mailimf_optional_field; let mut field: *mut mailimf_field = 0 as *mut mailimf_field; let mut guessed_type: libc::c_int = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; return_path = 0 as *mut mailimf_return; resent_date = 0 as *mut mailimf_orig_date; resent_from = 0 as *mut mailimf_from; resent_sender = 0 as *mut mailimf_sender; resent_to = 0 as *mut mailimf_to; resent_cc = 0 as *mut mailimf_cc; resent_bcc = 0 as *mut mailimf_bcc; resent_msg_id = 0 as *mut mailimf_message_id; orig_date = 0 as *mut mailimf_orig_date; from = 0 as *mut mailimf_from; sender = 0 as *mut mailimf_sender; reply_to = 0 as *mut mailimf_reply_to; to = 0 as *mut mailimf_to; cc = 0 as *mut mailimf_cc; bcc = 0 as *mut mailimf_bcc; message_id = 0 as *mut mailimf_message_id; in_reply_to = 0 as *mut mailimf_in_reply_to; references = 0 as *mut mailimf_references; subject = 0 as *mut mailimf_subject; comments = 0 as *mut mailimf_comments; keywords = 0 as *mut mailimf_keywords; optional_field = 0 as *mut mailimf_optional_field; guessed_type = guess_header_type(message, length, cur_token); type_0 = MAILIMF_FIELD_NONE as libc::c_int; match guessed_type { 9 => { r = mailimf_orig_date_parse(message, length, &mut cur_token, &mut orig_date); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = MAILIMF_FIELD_ORIG_DATE as libc::c_int; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 10 => { r = mailimf_from_parse(message, length, &mut cur_token, &mut from); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 11 => { r = mailimf_sender_parse(message, length, &mut cur_token, &mut sender); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 12 => { r = mailimf_reply_to_parse(message, length, &mut cur_token, &mut reply_to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 13 => { r = mailimf_to_parse(message, length, &mut cur_token, &mut to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 14 => { r = mailimf_cc_parse(message, length, &mut cur_token, &mut cc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 15 => { r = mailimf_bcc_parse(message, length, &mut cur_token, &mut bcc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 16 => { r = mailimf_message_id_parse(message, length, &mut cur_token, &mut message_id); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 17 => { r = mailimf_in_reply_to_parse(message, length, &mut cur_token, &mut in_reply_to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 18 => { r = mailimf_references_parse(message, length, &mut cur_token, &mut references); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 19 => { r = mailimf_subject_parse(message, length, &mut cur_token, &mut subject); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 20 => { r = mailimf_comments_parse(message, length, &mut cur_token, &mut comments); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 21 => { r = mailimf_keywords_parse(message, length, &mut cur_token, &mut keywords); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 1 => { r = mailimf_return_parse(message, length, &mut cur_token, &mut return_path); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 2 => { r = mailimf_resent_date_parse(message, length, &mut cur_token, &mut resent_date); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 3 => { r = mailimf_resent_from_parse(message, length, &mut cur_token, &mut resent_from); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 4 => { r = mailimf_resent_sender_parse(message, length, &mut cur_token, &mut resent_sender); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 5 => { r = mailimf_resent_to_parse(message, length, &mut cur_token, &mut resent_to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 6 => { r = mailimf_resent_cc_parse(message, length, &mut cur_token, &mut resent_cc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 7 => { r = mailimf_resent_bcc_parse(message, length, &mut cur_token, &mut resent_bcc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } 8 => { r = mailimf_resent_msg_id_parse(message, length, &mut cur_token, &mut resent_msg_id); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 9846950269610550213; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9846950269610550213; } else { /* do nothing */ res = r; current_block = 10956553358380301606; } } _ => { current_block = 9846950269610550213; } } match current_block { 9846950269610550213 => { if type_0 == MAILIMF_FIELD_NONE as libc::c_int { r = mailimf_optional_field_parse( message, length, &mut cur_token, &mut optional_field, ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r; current_block = 10956553358380301606; } else { type_0 = MAILIMF_FIELD_OPTIONAL_FIELD as libc::c_int; current_block = 2920409193602730479; } } else { current_block = 2920409193602730479; } match current_block { 10956553358380301606 => {} _ => { field = mailimf_field_new( type_0, return_path, resent_date, resent_from, resent_sender, resent_to, resent_cc, resent_bcc, resent_msg_id, orig_date, from, sender, reply_to, to, cc, bcc, message_id, in_reply_to, references, subject, comments, keywords, optional_field, ); if field.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !return_path.is_null() { mailimf_return_free(return_path); } if !resent_date.is_null() { mailimf_orig_date_free(resent_date); } if !resent_from.is_null() { mailimf_from_free(resent_from); } if !resent_sender.is_null() { mailimf_sender_free(resent_sender); } if !resent_to.is_null() { mailimf_to_free(resent_to); } if !resent_cc.is_null() { mailimf_cc_free(resent_cc); } if !resent_bcc.is_null() { mailimf_bcc_free(resent_bcc); } if !resent_msg_id.is_null() { mailimf_message_id_free(resent_msg_id); } if !orig_date.is_null() { mailimf_orig_date_free(orig_date); } if !from.is_null() { mailimf_from_free(from); } if !sender.is_null() { mailimf_sender_free(sender); } if !reply_to.is_null() { mailimf_reply_to_free(reply_to); } if !to.is_null() { mailimf_to_free(to); } if !cc.is_null() { mailimf_cc_free(cc); } if !bcc.is_null() { mailimf_bcc_free(bcc); } if !message_id.is_null() { mailimf_message_id_free(message_id); } if !in_reply_to.is_null() { mailimf_in_reply_to_free(in_reply_to); } if !references.is_null() { mailimf_references_free(references); } if !subject.is_null() { mailimf_subject_free(subject); } if !comments.is_null() { mailimf_comments_free(comments); } if !keywords.is_null() { mailimf_keywords_free(keywords); } if !optional_field.is_null() { mailimf_optional_field_free(optional_field); } } else { *result = field; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } } _ => {} } return res; } unsafe fn mailimf_optional_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_optional_field, ) -> libc::c_int { let mut name: *mut libc::c_char = 0 as *mut libc::c_char; let mut value: *mut libc::c_char = 0 as *mut libc::c_char; let mut optional_field: *mut mailimf_optional_field = 0 as *mut mailimf_optional_field; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_field_name_parse(message, length, &mut cur_token, &mut name); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstructured_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { optional_field = mailimf_optional_field_new(name, value); if optional_field.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = optional_field; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_unstructured_free(value); } } mailimf_field_name_free(name); } return res; } unsafe fn mailimf_unstrict_crlf_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; mailimf_cfws_parse(message, length, &mut cur_token); r = mailimf_char_parse(message, length, &mut cur_token, '\r' as i32 as libc::c_char); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_char_parse(message, length, &mut cur_token, '\n' as i32 as libc::c_char); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_cfws_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut has_comment: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; has_comment = 0i32; loop { r = mailimf_cfws_fws_comment_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } else { has_comment = 1i32 } } if 0 == has_comment { r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* internal use, exported for MIME */ pub unsafe fn mailimf_fws_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut final_token: size_t = 0; let mut fws_1: libc::c_int = 0; let mut fws_2: libc::c_int = 0; let mut fws_3: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; fws_1 = 0i32; loop { r = mailimf_wsp_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } else { fws_1 = 1i32 } } final_token = cur_token; r = mailimf_crlf_parse(message, length, &mut cur_token); match r { 0 => fws_2 = 1i32, 1 => fws_2 = 0i32, _ => return r, } fws_3 = 0i32; if 0 != fws_2 { loop { r = mailimf_wsp_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } else { fws_3 = 1i32 } } } if 0 == fws_1 && 0 == fws_3 { return MAILIMF_ERROR_PARSE as libc::c_int; } if 0 == fws_3 { cur_token = final_token } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } #[inline] unsafe fn mailimf_wsp_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; cur_token = *indx; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if *message.offset(cur_token as isize) as libc::c_int != ' ' as i32 && *message.offset(cur_token as isize) as libc::c_int != '\t' as i32 { return MAILIMF_ERROR_PARSE as libc::c_int; } cur_token = cur_token.wrapping_add(1); *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* [FWS] comment */ #[inline] unsafe fn mailimf_cfws_fws_comment_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_comment_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } #[inline] unsafe fn mailimf_comment_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_oparenth_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } loop { r = mailimf_comment_fws_ccontent_parse(message, length, &mut cur_token); if !(r != MAILIMF_NO_ERROR as libc::c_int) { continue; } if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_cparenth_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_cparenth_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_char_parse(message, length, indx, ')' as i32 as libc::c_char); } #[inline] unsafe fn mailimf_comment_fws_ccontent_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_ccontent_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } #[inline] unsafe fn mailimf_ccontent_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut ch: libc::c_char = 0; let mut r: libc::c_int = 0; cur_token = *indx; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if 0 != is_ctext(*message.offset(cur_token as isize)) { cur_token = cur_token.wrapping_add(1) } else { r = mailimf_quoted_pair_parse(message, length, &mut cur_token, &mut ch); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_comment_parse(message, length, &mut cur_token) } if r == MAILIMF_ERROR_PARSE as libc::c_int { return r; } } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } #[inline] unsafe fn mailimf_quoted_pair_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; cur_token = *indx; if cur_token.wrapping_add(1i32 as libc::size_t) >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if *message.offset(cur_token as isize) as libc::c_int != '\\' as i32 { return MAILIMF_ERROR_PARSE as libc::c_int; } cur_token = cur_token.wrapping_add(1); *result = *message.offset(cur_token as isize); cur_token = cur_token.wrapping_add(1); *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* ctext = NO-WS-CTL / ; Non white space controls %d33-39 / ; The rest of the US-ASCII %d42-91 / ; characters not including "(", %d93-126 ; ")", or "\" */ #[inline] unsafe fn is_ctext(mut ch: libc::c_char) -> libc::c_int { let mut uch: libc::c_uchar = ch as libc::c_uchar; if 0 != is_no_ws_ctl(ch) { return 1i32; } if (uch as libc::c_int) < 33i32 { return 0i32; } if uch as libc::c_int == 40i32 || uch as libc::c_int == 41i32 { return 0i32; } if uch as libc::c_int == 92i32 { return 0i32; } if uch as libc::c_int == 127i32 { return 0i32; } return 1i32; } /* ************************************************************************ */ /* RFC 2822 grammar */ /* NO-WS-CTL = %d1-8 / ; US-ASCII control characters %d11 / ; that do not include the %d12 / ; carriage return, line feed, %d14-31 / ; and white space characters %d127 */ #[inline] unsafe fn is_no_ws_ctl(mut ch: libc::c_char) -> libc::c_int { if ch as libc::c_int == 9i32 || ch as libc::c_int == 10i32 || ch as libc::c_int == 13i32 { return 0i32; } if ch as libc::c_int == 127i32 { return 1i32; } return (ch as libc::c_int >= 1i32 && ch as libc::c_int <= 31i32) as libc::c_int; } unsafe fn mailimf_oparenth_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_char_parse(message, length, indx, '(' as i32 as libc::c_char); } unsafe fn mailimf_unstructured_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut state: libc::c_int = 0; let mut begin: size_t = 0; let mut terminal: size_t = 0; let mut str: *mut libc::c_char = 0 as *mut libc::c_char; cur_token = *indx; loop { let mut r: libc::c_int = 0; r = mailimf_wsp_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { continue; } /* do nothing */ if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } state = UNSTRUCTURED_START as libc::c_int; begin = cur_token; terminal = cur_token; while state != UNSTRUCTURED_OUT as libc::c_int { match state { 0 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } terminal = cur_token; match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } 1 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } 2 => { if cur_token >= length { state = UNSTRUCTURED_OUT as libc::c_int } else { match *message.offset(cur_token as isize) as libc::c_int { 9 | 32 => state = UNSTRUCTURED_WSP as libc::c_int, _ => state = UNSTRUCTURED_OUT as libc::c_int, } } } 3 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } _ => {} } cur_token = cur_token.wrapping_add(1) } str = malloc( terminal .wrapping_sub(begin) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if str.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } strncpy( str, message.offset(begin as isize), terminal.wrapping_sub(begin), ); *str.offset(terminal.wrapping_sub(begin) as isize) = '\u{0}' as i32 as libc::c_char; *indx = terminal; *result = str; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_colon_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, ':' as i32 as libc::c_char); } pub unsafe fn mailimf_unstrict_char_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut token: libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_char_parse(message, length, &mut cur_token, token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_field_name_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut field_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut end: size_t = 0; cur_token = *indx; end = cur_token; if end >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } while 0 != is_ftext(*message.offset(end as isize)) { end = end.wrapping_add(1); if end >= length { break; } } if end == cur_token { return MAILIMF_ERROR_PARSE as libc::c_int; } field_name = malloc( end.wrapping_sub(cur_token) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if field_name.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } strncpy( field_name, message.offset(cur_token as isize), end.wrapping_sub(cur_token), ); *field_name.offset(end.wrapping_sub(cur_token) as isize) = '\u{0}' as i32 as libc::c_char; cur_token = end; *indx = cur_token; *result = field_name; return MAILIMF_NO_ERROR as libc::c_int; } /* field-name = 1*ftext */ #[inline] unsafe fn is_ftext(mut ch: libc::c_char) -> libc::c_int { let mut uch: libc::c_uchar = ch as libc::c_uchar; if (uch as libc::c_int) < 33i32 { return 0i32; } if uch as libc::c_int == 58i32 { return 0i32; } return 1i32; } unsafe fn mailimf_resent_msg_id_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_message_id, ) -> libc::c_int { let mut value: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut message_id: *mut mailimf_message_id = 0 as *mut mailimf_message_id; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-Message-ID\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-Message-ID\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_msg_id_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { message_id = mailimf_message_id_new(value); if message_id.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = message_id; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_msg_id_free(value); } } } return res; } pub unsafe fn mailimf_msg_id_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut msg_id: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_lower_parse(message, length, &mut cur_token); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_addr_spec_msg_id_parse(message, length, &mut cur_token, &mut msg_id); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { *result = msg_id; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } else if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_lower_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { current_block = 2668756484064249700; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 2668756484064249700; } else { // ok res = r; current_block = 9394595304415473402; } match current_block { 9394595304415473402 => {} _ => { r = mailimf_addr_spec_msg_id_parse(message, length, &mut cur_token, &mut msg_id); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_greater_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { free(msg_id as *mut libc::c_void); res = r } else { r = mailimf_greater_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { current_block = 6450636197030046351; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 6450636197030046351; } else { // ok free(msg_id as *mut libc::c_void); res = r; current_block = 9394595304415473402; } match current_block { 9394595304415473402 => {} _ => { *result = msg_id; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } } } } } return res; } unsafe fn mailimf_greater_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '>' as i32 as libc::c_char); } /* for msg id addr-spec = local-part "@" domain */ unsafe fn mailimf_addr_spec_msg_id_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut addr_spec: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut begin: size_t = 0; let mut end: size_t = 0; let mut final_0: libc::c_int = 0; let mut count: size_t = 0; let mut src: *const libc::c_char = 0 as *const libc::c_char; let mut dest: *mut libc::c_char = 0 as *mut libc::c_char; let mut i: size_t = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { end = cur_token; if end >= length { res = MAILIMF_ERROR_PARSE as libc::c_int } else { begin = cur_token; final_0 = 0i32; loop { match *message.offset(end as isize) as libc::c_int { 62 | 13 | 10 => final_0 = 1i32, _ => {} } if 0 != final_0 { break; } end = end.wrapping_add(1); if end >= length { break; } } if end == begin { res = MAILIMF_ERROR_PARSE as libc::c_int } else { addr_spec = malloc( end.wrapping_sub(cur_token) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if addr_spec.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { count = end.wrapping_sub(cur_token); src = message.offset(cur_token as isize); dest = addr_spec; i = 0i32 as size_t; while i < count { if *src as libc::c_int != ' ' as i32 && *src as libc::c_int != '\t' as i32 { *dest = *src; dest = dest.offset(1isize) } src = src.offset(1isize); i = i.wrapping_add(1) } *dest = '\u{0}' as i32 as libc::c_char; cur_token = end; *result = addr_spec; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } } return res; } unsafe fn mailimf_lower_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '<' as i32 as libc::c_char); } pub unsafe fn mailimf_token_case_insensitive_len_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut token: *mut libc::c_char, mut token_length: size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; cur_token = *indx; if cur_token .wrapping_add(token_length) .wrapping_sub(1i32 as libc::size_t) >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if strncasecmp(message.offset(cur_token as isize), token, token_length) == 0i32 { cur_token = (cur_token as libc::size_t).wrapping_add(token_length) as size_t as size_t; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } else { return MAILIMF_ERROR_PARSE as libc::c_int; }; } unsafe fn mailimf_resent_bcc_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_bcc, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut bcc: *mut mailimf_bcc = 0 as *mut mailimf_bcc; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; bcc = 0 as *mut mailimf_bcc; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-Bcc\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-Bcc\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { addr_list = 0 as *mut mailimf_address_list; r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { bcc = mailimf_bcc_new(addr_list); if bcc.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = bcc; *indx = cur_token; return 1i32; } } mailimf_address_list_free(addr_list); } } } return res; } /* mailimf_address_list_parse will parse the given address list @param message this is a string containing the address list @param length this is the size of the given string @param indx this is a pointer to the start of the address list in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_address_list_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_address_list, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut address_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_struct_list_parse( message, length, &mut cur_token, &mut list, ',' as i32 as libc::c_char, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut mailimf_address, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_address_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_address) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_address_free)), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { address_list = mailimf_address_list_new(list); if address_list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; clist_foreach( list, ::std::mem::transmute::<Option<unsafe fn(_: *mut mailimf_address) -> ()>, clist_func>( Some(mailimf_address_free), ), 0 as *mut libc::c_void, ); clist_free(list); } else { *result = address_list; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } /* mailimf_address_parse will parse the given address @param message this is a string containing the address @param length this is the size of the given string @param indx this is a pointer to the start of the address in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_address_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_address, ) -> libc::c_int { let mut type_0: libc::c_int = 0; let mut cur_token: size_t = 0; let mut mailbox: *mut mailimf_mailbox = 0 as *mut mailimf_mailbox; let mut group: *mut mailimf_group = 0 as *mut mailimf_group; let mut address: *mut mailimf_address = 0 as *mut mailimf_address; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; mailbox = 0 as *mut mailimf_mailbox; group = 0 as *mut mailimf_group; type_0 = MAILIMF_ADDRESS_ERROR as libc::c_int; r = mailimf_group_parse(message, length, &mut cur_token, &mut group); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = MAILIMF_ADDRESS_GROUP as libc::c_int } if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_mailbox_parse(message, length, &mut cur_token, &mut mailbox); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = MAILIMF_ADDRESS_MAILBOX as libc::c_int } } if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { address = mailimf_address_new(type_0, mailbox, group); if address.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !mailbox.is_null() { mailimf_mailbox_free(mailbox); } if !group.is_null() { mailimf_group_free(group); } } else { *result = address; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } /* mailimf_mailbox_parse will parse the given address @param message this is a string containing the mailbox @param length this is the size of the given string @param indx this is a pointer to the start of the mailbox in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_mailbox_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_mailbox, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut display_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut mailbox: *mut mailimf_mailbox = 0 as *mut mailimf_mailbox; let mut addr_spec: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; display_name = 0 as *mut libc::c_char; addr_spec = 0 as *mut libc::c_char; r = mailimf_name_addr_parse( message, length, &mut cur_token, &mut display_name, &mut addr_spec, ); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_addr_spec_parse(message, length, &mut cur_token, &mut addr_spec) } if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { mailbox = mailimf_mailbox_new(display_name, addr_spec); if mailbox.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !display_name.is_null() { mailimf_display_name_free(display_name); } if !addr_spec.is_null() { mailimf_addr_spec_free(addr_spec); } } else { *result = mailbox; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } unsafe fn mailimf_addr_spec_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut addr_spec: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut begin: size_t = 0; let mut end: size_t = 0; let mut final_0: libc::c_int = 0; let mut count: size_t = 0; let mut src: *const libc::c_char = 0 as *const libc::c_char; let mut dest: *mut libc::c_char = 0 as *mut libc::c_char; let mut i: size_t = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { end = cur_token; if end >= length { res = MAILIMF_ERROR_PARSE as libc::c_int } else { begin = cur_token; final_0 = 0i32; loop { match *message.offset(end as isize) as libc::c_int { 62 | 44 | 13 | 10 | 40 | 41 | 58 | 59 => final_0 = 1i32, _ => {} } if 0 != final_0 { break; } end = end.wrapping_add(1); if end >= length { break; } } if end == begin { res = MAILIMF_ERROR_PARSE as libc::c_int } else { addr_spec = malloc( end.wrapping_sub(cur_token) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if addr_spec.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { count = end.wrapping_sub(cur_token); src = message.offset(cur_token as isize); dest = addr_spec; i = 0i32 as size_t; while i < count { if *src as libc::c_int != ' ' as i32 && *src as libc::c_int != '\t' as i32 { *dest = *src; dest = dest.offset(1isize) } src = src.offset(1isize); i = i.wrapping_add(1) } *dest = '\u{0}' as i32 as libc::c_char; cur_token = end; *result = addr_spec; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } } return res; } unsafe fn mailimf_name_addr_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut pdisplay_name: *mut *mut libc::c_char, mut pangle_addr: *mut *mut libc::c_char, ) -> libc::c_int { let mut display_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut angle_addr: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; display_name = 0 as *mut libc::c_char; angle_addr = 0 as *mut libc::c_char; r = mailimf_display_name_parse(message, length, &mut cur_token, &mut display_name); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_angle_addr_parse(message, length, &mut cur_token, &mut angle_addr); if r != MAILIMF_NO_ERROR as libc::c_int { res = r; if !display_name.is_null() { mailimf_display_name_free(display_name); } } else { *pdisplay_name = display_name; *pangle_addr = angle_addr; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } unsafe fn mailimf_angle_addr_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut addr_spec: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_lower_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_addr_spec_parse(message, length, &mut cur_token, &mut addr_spec); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_greater_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { free(addr_spec as *mut libc::c_void); return r; } *result = addr_spec; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_display_name_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { return mailimf_phrase_parse(message, length, indx, result); } unsafe fn mailimf_phrase_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut gphrase: *mut MMAPString = 0 as *mut MMAPString; let mut word: *mut libc::c_char = 0 as *mut libc::c_char; let mut first: libc::c_int = 0; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut str: *mut libc::c_char = 0 as *mut libc::c_char; let mut has_missing_closing_quote: libc::c_int = 0; cur_token = *indx; has_missing_closing_quote = 0i32; gphrase = mmap_string_new(b"\x00" as *const u8 as *const libc::c_char); if gphrase.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { first = 1i32; loop { let mut missing_quote: libc::c_int = 0i32; r = mailimf_fws_word_parse( message, length, &mut cur_token, &mut word, &mut missing_quote, ); if 0 != missing_quote { has_missing_closing_quote = 1i32 } if r == MAILIMF_NO_ERROR as libc::c_int { if 0 == first { if mmap_string_append_c(gphrase, ' ' as i32 as libc::c_char).is_null() { mailimf_word_free(word); res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 17261756273978092585; break; } } if mmap_string_append(gphrase, word).is_null() { mailimf_word_free(word); res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 17261756273978092585; break; } else { mailimf_word_free(word); first = 0i32 } } else { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 11636175345244025579; break; } res = r; current_block = 17261756273978092585; break; } } match current_block { 11636175345244025579 => { if 0 != first { res = MAILIMF_ERROR_PARSE as libc::c_int } else { if 0 != has_missing_closing_quote { r = mailimf_char_parse( message, length, &mut cur_token, '\"' as i32 as libc::c_char, ) } str = strdup((*gphrase).str_0); if str.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { mmap_string_free(gphrase); *result = str; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } _ => {} } mmap_string_free(gphrase); } return res; } pub unsafe fn mailimf_fws_word_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, mut p_missing_closing_quote: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut word: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut missing_closing_quote: libc::c_int = 0; cur_token = *indx; missing_closing_quote = 0i32; r = mailimf_fws_atom_for_word_parse( message, length, &mut cur_token, &mut word, &mut missing_closing_quote, ); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_fws_quoted_string_parse(message, length, &mut cur_token, &mut word) } if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = word; *indx = cur_token; *p_missing_closing_quote = missing_closing_quote; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_fws_quoted_string_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut gstr: *mut MMAPString = 0 as *mut MMAPString; let mut ch: libc::c_char = 0; let mut str: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_dquote_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { gstr = mmap_string_new(b"\x00" as *const u8 as *const libc::c_char); if gstr.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { loop { r = mailimf_fws_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { if mmap_string_append_c(gstr, ' ' as i32 as libc::c_char).is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 15096897878952122875; break; } } else if r != MAILIMF_ERROR_PARSE as libc::c_int { res = r; current_block = 15096897878952122875; break; } r = mailimf_qcontent_parse(message, length, &mut cur_token, &mut ch); if r == MAILIMF_NO_ERROR as libc::c_int { if !mmap_string_append_c(gstr, ch).is_null() { continue; } res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 15096897878952122875; break; } else { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 5494826135382683477; break; } res = r; current_block = 15096897878952122875; break; } } match current_block { 5494826135382683477 => { r = mailimf_dquote_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { str = strdup((*gstr).str_0); if str.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { mmap_string_free(gstr); *indx = cur_token; *result = str; return MAILIMF_NO_ERROR as libc::c_int; } } } _ => {} } mmap_string_free(gstr); } } } return res; } unsafe fn mailimf_dquote_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_char_parse(message, length, indx, '\"' as i32 as libc::c_char); } unsafe fn mailimf_qcontent_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut ch: libc::c_char = 0; let mut r: libc::c_int = 0; cur_token = *indx; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if 0 != is_qtext(*message.offset(cur_token as isize)) { ch = *message.offset(cur_token as isize); cur_token = cur_token.wrapping_add(1) } else { r = mailimf_quoted_pair_parse(message, length, &mut cur_token, &mut ch); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } *result = ch; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* dot-atom = [CFWS] dot-atom-text [CFWS] */ /* dot-atom-text = 1*atext *("." 1*atext) */ /* qtext = NO-WS-CTL / ; Non white space controls %d33 / ; The rest of the US-ASCII %d35-91 / ; characters not including "\" %d93-126 ; or the quote character */ #[inline] unsafe fn is_qtext(mut ch: libc::c_char) -> libc::c_int { let mut uch: libc::c_uchar = ch as libc::c_uchar; if 0 != is_no_ws_ctl(ch) { return 1i32; } if (uch as libc::c_int) < 33i32 { return 0i32; } if uch as libc::c_int == 34i32 { return 0i32; } if uch as libc::c_int == 92i32 { return 0i32; } if uch as libc::c_int == 127i32 { return 0i32; } return 1i32; } unsafe fn mailimf_fws_atom_for_word_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, mut p_missing_closing_quote: *mut libc::c_int, ) -> libc::c_int { let mut end: size_t = 0; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut word: *mut mailmime_encoded_word = 0 as *mut mailmime_encoded_word; let mut has_fwd: libc::c_int = 0; let mut missing_closing_quote: libc::c_int = 0; let mut atom: *mut libc::c_char = 0 as *mut libc::c_char; cur_token = *indx; missing_closing_quote = 0i32; r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { end = cur_token; r = mailmime_encoded_word_parse( message, length, &mut cur_token, &mut word, &mut has_fwd, &mut missing_closing_quote, ); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { if r == MAILIMF_ERROR_PARSE as libc::c_int { return mailimf_fws_atom_parse(message, length, indx, result); } mailmime_encoded_word_free(word); atom = malloc( cur_token .wrapping_sub(end) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if atom.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { strncpy( atom, message.offset(end as isize), cur_token.wrapping_sub(end), ); *atom.offset(cur_token.wrapping_sub(end) as isize) = '\u{0}' as i32 as libc::c_char; *result = atom; *indx = cur_token; *p_missing_closing_quote = missing_closing_quote; return MAILIMF_NO_ERROR as libc::c_int; } } } return res; } pub unsafe fn mailimf_fws_atom_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut atom: *mut libc::c_char = 0 as *mut libc::c_char; let mut end: size_t = 0; cur_token = *indx; r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { end = cur_token; if end >= length { res = MAILIMF_ERROR_PARSE as libc::c_int } else { while 0 != is_atext(*message.offset(end as isize)) { end = end.wrapping_add(1); if end >= length { break; } } if end == cur_token { res = MAILIMF_ERROR_PARSE as libc::c_int } else { atom = malloc( end.wrapping_sub(cur_token) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if atom.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { strncpy( atom, message.offset(cur_token as isize), end.wrapping_sub(cur_token), ); *atom.offset(end.wrapping_sub(cur_token) as isize) = '\u{0}' as i32 as libc::c_char; cur_token = end; *indx = cur_token; *result = atom; return MAILIMF_NO_ERROR as libc::c_int; } } } } return res; } /* atext = ALPHA / DIGIT / ; Any character except controls, "!" / "#" / ; SP, and specials. "$" / "%" / ; Used for atoms "&" / "'" / "*" / "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" */ #[inline] unsafe fn is_atext(mut ch: libc::c_char) -> libc::c_int { match ch as libc::c_int { 32 | 9 | 10 | 13 | 60 | 62 | 44 | 34 | 58 | 59 => return 0i32, _ => return 1i32, }; } unsafe fn mailimf_group_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_group, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut display_name: *mut libc::c_char = 0 as *mut libc::c_char; let mut mailbox_list: *mut mailimf_mailbox_list = 0 as *mut mailimf_mailbox_list; let mut group: *mut mailimf_group = 0 as *mut mailimf_group; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut list: *mut clist = 0 as *mut clist; cur_token = *indx; mailbox_list = 0 as *mut mailimf_mailbox_list; r = mailimf_display_name_parse(message, length, &mut cur_token, &mut display_name); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_mailbox_list_parse(message, length, &mut cur_token, &mut mailbox_list); match r { 0 => { current_block = 1608152415753874203; } 1 => { r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r; current_block = 14904789583098922708; } else { list = clist_new(); if list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 14904789583098922708; } else { mailbox_list = mailimf_mailbox_list_new(list); if mailbox_list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; clist_free(list); current_block = 14904789583098922708; } else { current_block = 1608152415753874203; } } } } _ => { res = r; current_block = 14904789583098922708; } } match current_block { 14904789583098922708 => {} _ => { r = mailimf_semi_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { group = mailimf_group_new(display_name, mailbox_list); if group.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *indx = cur_token; *result = group; return MAILIMF_NO_ERROR as libc::c_int; } } if !mailbox_list.is_null() { mailimf_mailbox_list_free(mailbox_list); } } } } mailimf_display_name_free(display_name); } return res; } unsafe fn mailimf_semi_colon_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, ';' as i32 as libc::c_char); } /* mailimf_mailbox_list_parse will parse the given mailbox list @param message this is a string containing the mailbox list @param length this is the size of the given string @param indx this is a pointer to the start of the mailbox list in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_mailbox_list_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_mailbox_list, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut mailbox_list: *mut mailimf_mailbox_list = 0 as *mut mailimf_mailbox_list; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_struct_list_parse( message, length, &mut cur_token, &mut list, ',' as i32 as libc::c_char, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut mailimf_mailbox, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_mailbox_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_mailbox) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_mailbox_free)), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { mailbox_list = mailimf_mailbox_list_new(list); if mailbox_list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; clist_foreach( list, ::std::mem::transmute::<Option<unsafe fn(_: *mut mailimf_mailbox) -> ()>, clist_func>( Some(mailimf_mailbox_free), ), 0 as *mut libc::c_void, ); clist_free(list); } else { *result = mailbox_list; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } return res; } unsafe fn mailimf_struct_list_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut clist, mut symbol: libc::c_char, mut parser: Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, mut destructor: Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, ) -> libc::c_int { let mut current_block: u64; let mut struct_list: *mut clist = 0 as *mut clist; let mut cur_token: size_t = 0; let mut value: *mut libc::c_void = 0 as *mut libc::c_void; let mut final_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = parser.expect("non-null function pointer")( message, length, &mut cur_token, &mut value as *mut *mut libc::c_void as *mut libc::c_void, ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { struct_list = clist_new(); if struct_list.is_null() { destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int } else { r = clist_insert_after(struct_list, (*struct_list).last, value); if r < 0i32 { destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int } else { final_token = cur_token; loop { r = mailimf_unstrict_char_parse(message, length, &mut cur_token, symbol); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9853141518545631134; break; } res = r; current_block = 17524159567010234572; break; } else { r = parser.expect("non-null function pointer")( message, length, &mut cur_token, &mut value as *mut *mut libc::c_void as *mut libc::c_void, ); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 9853141518545631134; break; } res = r; current_block = 17524159567010234572; break; } else { r = clist_insert_after(struct_list, (*struct_list).last, value); if r < 0i32 { destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 17524159567010234572; break; } else { final_token = cur_token } } } } match current_block { 17524159567010234572 => {} _ => { *result = struct_list; *indx = final_token; return MAILIMF_NO_ERROR as libc::c_int; } } } clist_foreach( struct_list, ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, clist_func, >(destructor), 0 as *mut libc::c_void, ); clist_free(struct_list); } } return res; } unsafe fn mailimf_resent_cc_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_cc, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut cc: *mut mailimf_cc = 0 as *mut mailimf_cc; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-Cc\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-Cc\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { cc = mailimf_cc_new(addr_list); if cc.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = cc; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_address_list_free(addr_list); } } } return res; } unsafe fn mailimf_resent_to_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_to, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut to: *mut mailimf_to = 0 as *mut mailimf_to; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-To\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-To\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { to = mailimf_to_new(addr_list); if to.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = to; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_address_list_free(addr_list); } } } return res; } unsafe fn mailimf_resent_sender_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_sender, ) -> libc::c_int { let mut mb: *mut mailimf_mailbox = 0 as *mut mailimf_mailbox; let mut sender: *mut mailimf_sender = 0 as *mut mailimf_sender; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = length; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-Sender\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-Sender\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_mailbox_parse(message, length, &mut cur_token, &mut mb); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { sender = mailimf_sender_new(mb); if sender.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = sender; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_mailbox_free(mb); } } } return res; } unsafe fn mailimf_resent_from_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_from, ) -> libc::c_int { let mut mb_list: *mut mailimf_mailbox_list = 0 as *mut mailimf_mailbox_list; let mut from: *mut mailimf_from = 0 as *mut mailimf_from; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-From\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-From\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_mailbox_list_parse(message, length, &mut cur_token, &mut mb_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { from = mailimf_from_new(mb_list); if from.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = from; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_mailbox_list_free(mb_list); } } } return res; } unsafe fn mailimf_resent_date_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_orig_date, ) -> libc::c_int { let mut orig_date: *mut mailimf_orig_date = 0 as *mut mailimf_orig_date; let mut date_time: *mut mailimf_date_time = 0 as *mut mailimf_date_time; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Resent-Date\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Resent-Date\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_date_time_parse(message, length, &mut cur_token, &mut date_time); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { orig_date = mailimf_orig_date_new(date_time); if orig_date.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = orig_date; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_date_time_free(date_time); } } } return res; } /* mailimf_date_time_parse will parse the given RFC 2822 date @param message this is a string containing the date @param length this is the size of the given string @param indx this is a pointer to the start of the date in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_date_time_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_date_time, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day_of_week: libc::c_int = 0; let mut date_time: *mut mailimf_date_time = 0 as *mut mailimf_date_time; let mut day: libc::c_int = 0; let mut month: libc::c_int = 0; let mut year: libc::c_int = 0; let mut hour: libc::c_int = 0; let mut min: libc::c_int = 0; let mut sec: libc::c_int = 0; let mut zone: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; day_of_week = -1i32; r = mailimf_day_of_week_parse(message, length, &mut cur_token, &mut day_of_week); if r == MAILIMF_NO_ERROR as libc::c_int { r = mailimf_comma_parse(message, length, &mut cur_token); if !(r == MAILIMF_ERROR_PARSE as libc::c_int) { if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } } else if r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } day = 0i32; month = 0i32; year = 0i32; r = mailimf_date_parse( message, length, &mut cur_token, &mut day, &mut month, &mut year, ); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_broken_date_parse( message, length, &mut cur_token, &mut day, &mut month, &mut year, ) } else if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } hour = 0i32; min = 0i32; sec = 0i32; zone = 0i32; r = mailimf_time_parse( message, length, &mut cur_token, &mut hour, &mut min, &mut sec, &mut zone, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } date_time = mailimf_date_time_new(day, month, year, hour, min, sec, zone); if date_time.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } *indx = cur_token; *result = date_time; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_time_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut phour: *mut libc::c_int, mut pmin: *mut libc::c_int, mut psec: *mut libc::c_int, mut pzone: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut hour: libc::c_int = 0; let mut min: libc::c_int = 0; let mut sec: libc::c_int = 0; let mut zone: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_time_of_day_parse( message, length, &mut cur_token, &mut hour, &mut min, &mut sec, ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_fws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_zone_parse(message, length, &mut cur_token, &mut zone); if !(r == MAILIMF_NO_ERROR as libc::c_int) { if r == MAILIMF_ERROR_PARSE as libc::c_int { zone = 0i32 } else { return r; } } *phour = hour; *pmin = min; *psec = sec; *pzone = zone; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_zone_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut zone: libc::c_int = 0; let mut sign: libc::c_int = 0; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut value: uint32_t = 0; cur_token = *indx; if cur_token.wrapping_add(1i32 as libc::size_t) < length { if *message.offset(cur_token as isize) as libc::c_int == 'U' as i32 && *message.offset(cur_token.wrapping_add(1i32 as libc::size_t) as isize) as libc::c_int == 'T' as i32 { *result = 1i32; *indx = cur_token.wrapping_add(2i32 as libc::size_t); return MAILIMF_NO_ERROR as libc::c_int; } } zone = 0i32; if cur_token.wrapping_add(2i32 as libc::size_t) < length { let mut state: libc::c_int = 0; state = STATE_ZONE_1 as libc::c_int; while state <= 2i32 { match state { 0 => match *message.offset(cur_token as isize) as libc::c_int { 71 => { if *message.offset(cur_token.wrapping_add(1i32 as libc::size_t) as isize) as libc::c_int == 'M' as i32 && *message .offset(cur_token.wrapping_add(2i32 as libc::size_t) as isize) as libc::c_int == 'T' as i32 { if cur_token.wrapping_add(3i32 as libc::size_t) < length && (*message .offset(cur_token.wrapping_add(3i32 as libc::size_t) as isize) as libc::c_int == '+' as i32 || *message.offset( cur_token.wrapping_add(3i32 as libc::size_t) as isize ) as libc::c_int == '-' as i32) { cur_token = (cur_token as libc::size_t) .wrapping_add(3i32 as libc::size_t) as size_t as size_t; state = STATE_ZONE_CONT as libc::c_int } else { zone = 0i32; state = STATE_ZONE_OK as libc::c_int } } else { state = STATE_ZONE_ERR as libc::c_int } } 69 => { zone = -5i32; state = STATE_ZONE_2 as libc::c_int } 67 => { zone = -6i32; state = STATE_ZONE_2 as libc::c_int } 77 => { zone = -7i32; state = STATE_ZONE_2 as libc::c_int } 80 => { zone = -8i32; state = STATE_ZONE_2 as libc::c_int } _ => state = STATE_ZONE_CONT as libc::c_int, }, 1 => { match *message.offset(cur_token.wrapping_add(1i32 as libc::size_t) as isize) as libc::c_int { 83 => state = STATE_ZONE_3 as libc::c_int, 68 => { zone += 1; state = STATE_ZONE_3 as libc::c_int } _ => state = STATE_ZONE_ERR as libc::c_int, } } 2 => { if *message.offset(cur_token.wrapping_add(2i32 as libc::size_t) as isize) as libc::c_int == 'T' as i32 { zone *= 100i32; state = STATE_ZONE_OK as libc::c_int } else { state = STATE_ZONE_ERR as libc::c_int } } _ => {} } } match state { 3 => { *result = zone; *indx = cur_token.wrapping_add(3i32 as libc::size_t); return MAILIMF_NO_ERROR as libc::c_int; } 4 => return MAILIMF_ERROR_PARSE as libc::c_int, _ => {} } } sign = 1i32; r = mailimf_plus_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { sign = 1i32 } if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_minus_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { sign = -1i32 } } if !(r == MAILIMF_NO_ERROR as libc::c_int) { if r == MAILIMF_ERROR_PARSE as libc::c_int { sign = 1i32 } else { return r; } } r = mailimf_number_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } zone = value.wrapping_mul(sign as libc::c_uint) as libc::c_int; *indx = cur_token; *result = zone; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_number_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut uint32_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut digit: libc::c_int = 0; let mut number: uint32_t = 0; let mut parsed: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; parsed = 0i32; number = 0i32 as uint32_t; loop { r = mailimf_digit_parse(message, length, &mut cur_token, &mut digit); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { break; } return r; } else { number = (number as libc::c_uint).wrapping_mul(10i32 as libc::c_uint) as uint32_t as uint32_t; number = (number as libc::c_uint).wrapping_add(digit as libc::c_uint) as uint32_t as uint32_t; parsed = 1i32 } } if 0 == parsed { return MAILIMF_ERROR_PARSE as libc::c_int; } *result = number; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_digit_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; cur_token = *indx; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } if 0 != is_digit(*message.offset(cur_token as isize)) { *result = *message.offset(cur_token as isize) as libc::c_int - '0' as i32; cur_token = cur_token.wrapping_add(1); *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } else { return MAILIMF_ERROR_PARSE as libc::c_int; }; } /* *************************************************************** */ #[inline] unsafe fn is_digit(mut ch: libc::c_char) -> libc::c_int { return (ch as libc::c_int >= '0' as i32 && ch as libc::c_int <= '9' as i32) as libc::c_int; } unsafe fn mailimf_minus_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '-' as i32 as libc::c_char); } unsafe fn mailimf_plus_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '+' as i32 as libc::c_char); } unsafe fn mailimf_time_of_day_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut phour: *mut libc::c_int, mut pmin: *mut libc::c_int, mut psec: *mut libc::c_int, ) -> libc::c_int { let mut hour: libc::c_int = 0; let mut min: libc::c_int = 0; let mut sec: libc::c_int = 0; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_hour_parse(message, length, &mut cur_token, &mut hour); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_minute_parse(message, length, &mut cur_token, &mut min); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_colon_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { r = mailimf_second_parse(message, length, &mut cur_token, &mut sec); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } } else if r == MAILIMF_ERROR_PARSE as libc::c_int { sec = 0i32 } else { return r; } *phour = hour; *pmin = min; *psec = sec; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_second_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut second: uint32_t = 0; let mut r: libc::c_int = 0; r = mailimf_number_parse(message, length, indx, &mut second); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = second as libc::c_int; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_minute_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut minute: uint32_t = 0; let mut r: libc::c_int = 0; r = mailimf_number_parse(message, length, indx, &mut minute); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = minute as libc::c_int; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_hour_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut hour: uint32_t = 0; let mut r: libc::c_int = 0; r = mailimf_number_parse(message, length, indx, &mut hour); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = hour as libc::c_int; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_broken_date_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut pday: *mut libc::c_int, mut pmonth: *mut libc::c_int, mut pyear: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day: libc::c_int = 0; let mut month: libc::c_int = 0; let mut year: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; month = 1i32; r = mailimf_month_parse(message, length, &mut cur_token, &mut month); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } day = 1i32; r = mailimf_day_parse(message, length, &mut cur_token, &mut day); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } year = 2001i32; r = mailimf_year_parse(message, length, &mut cur_token, &mut year); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *pday = day; *pmonth = month; *pyear = year; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_year_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut number: uint32_t = 0; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_number_parse(message, length, &mut cur_token, &mut number); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; *result = number as libc::c_int; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_day_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day: uint32_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_number_parse(message, length, &mut cur_token, &mut day); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = day as libc::c_int; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_month_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut month: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_month_name_parse(message, length, &mut cur_token, &mut month); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = month; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_month_name_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut month: libc::c_int = 0; let mut guessed_month: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; guessed_month = guess_month(message, length, cur_token); if guessed_month == -1i32 { return MAILIMF_ERROR_PARSE as libc::c_int; } r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, month_names[(guessed_month - 1i32) as usize].str_0, strlen(month_names[(guessed_month - 1i32) as usize].str_0), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } month = guessed_month; *result = month; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / "Sep" / "Oct" / "Nov" / "Dec" */ static mut month_names: [mailimf_token_value; 12] = [ mailimf_token_value { value: 1i32, str_0: b"Jan\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 2i32, str_0: b"Feb\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 3i32, str_0: b"Mar\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 4i32, str_0: b"Apr\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 5i32, str_0: b"May\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 6i32, str_0: b"Jun\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 7i32, str_0: b"Jul\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 8i32, str_0: b"Aug\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 9i32, str_0: b"Sep\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 10i32, str_0: b"Oct\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 11i32, str_0: b"Nov\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 12i32, str_0: b"Dec\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, ]; unsafe fn guess_month( mut message: *const libc::c_char, mut length: size_t, mut indx: size_t, ) -> libc::c_int { let mut state: libc::c_int = 0; state = MONTH_START as libc::c_int; loop { if indx >= length { return -1i32; } match state { 0 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 74 => state = MONTH_J as libc::c_int, 70 => return 2i32, 77 => state = MONTH_M as libc::c_int, 65 => state = MONTH_A as libc::c_int, 83 => return 9i32, 79 => return 10i32, 78 => return 11i32, 68 => return 12i32, _ => return -1i32, } } 1 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 65 => return 1i32, 85 => state = MONTH_JU as libc::c_int, _ => return -1i32, } } 2 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 78 => return 6i32, 76 => return 7i32, _ => return -1i32, } } 3 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 65 => state = MONTH_MA as libc::c_int, _ => return -1i32, } } 4 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 89 => return 5i32, 82 => return 3i32, _ => return -1i32, } } 5 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 80 => return 4i32, 85 => return 8i32, _ => return -1i32, } } _ => {} } indx = indx.wrapping_add(1) } } unsafe fn mailimf_date_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut pday: *mut libc::c_int, mut pmonth: *mut libc::c_int, mut pyear: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day: libc::c_int = 0; let mut month: libc::c_int = 0; let mut year: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; day = 1i32; r = mailimf_day_parse(message, length, &mut cur_token, &mut day); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } month = 1i32; r = mailimf_month_parse(message, length, &mut cur_token, &mut month); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } year = 2001i32; r = mailimf_year_parse(message, length, &mut cur_token, &mut year); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *pday = day; *pmonth = month; *pyear = year; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_comma_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, ',' as i32 as libc::c_char); } unsafe fn mailimf_day_of_week_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day_of_week: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_day_name_parse(message, length, &mut cur_token, &mut day_of_week); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *indx = cur_token; *result = day_of_week; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_day_name_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut libc::c_int, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut day_of_week: libc::c_int = 0; let mut guessed_day: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; guessed_day = guess_day_name(message, length, cur_token); if guessed_day == -1i32 { return MAILIMF_ERROR_PARSE as libc::c_int; } r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, day_names[(guessed_day - 1i32) as usize].str_0, strlen(day_names[(guessed_day - 1i32) as usize].str_0), ); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } day_of_week = guessed_day; *result = day_of_week; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } static mut day_names: [mailimf_token_value; 7] = [ mailimf_token_value { value: 1i32, str_0: b"Mon\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 2i32, str_0: b"Tue\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 3i32, str_0: b"Wed\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 4i32, str_0: b"Thu\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 5i32, str_0: b"Fri\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 6i32, str_0: b"Sat\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, mailimf_token_value { value: 7i32, str_0: b"Sun\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, }, ]; unsafe fn guess_day_name( mut message: *const libc::c_char, mut length: size_t, mut indx: size_t, ) -> libc::c_int { let mut state: libc::c_int = 0; state = DAY_NAME_START as libc::c_int; loop { if indx >= length { return -1i32; } match state { 0 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 77 => return 1i32, 84 => state = DAY_NAME_T as libc::c_int, 87 => return 3i32, 70 => return 5i32, 83 => state = DAY_NAME_S as libc::c_int, _ => return -1i32, } } 1 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 85 => return 2i32, 72 => return 4i32, _ => return -1i32, } } 2 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 65 => return 6i32, 85 => return 7i32, _ => return -1i32, } } _ => {} } indx = indx.wrapping_add(1) } } unsafe fn mailimf_return_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_return, ) -> libc::c_int { let mut path: *mut mailimf_path = 0 as *mut mailimf_path; let mut return_path: *mut mailimf_return = 0 as *mut mailimf_return; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Return-Path\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Return-Path\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { path = 0 as *mut mailimf_path; r = mailimf_path_parse(message, length, &mut cur_token, &mut path); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { return_path = mailimf_return_new(path); if return_path.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = return_path; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_path_free(path); } } } return res; } unsafe fn mailimf_path_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_path, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut addr_spec: *mut libc::c_char = 0 as *mut libc::c_char; let mut path: *mut mailimf_path = 0 as *mut mailimf_path; let mut res: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; addr_spec = 0 as *mut libc::c_char; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_lower_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_addr_spec_parse(message, length, &mut cur_token, &mut addr_spec); match r { 0 => { current_block = 2370887241019905314; } 1 => { r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r; current_block = 14973541214802992465; } else { current_block = 2370887241019905314; } } _ => return r, } match current_block { 14973541214802992465 => {} _ => { r = mailimf_greater_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { path = mailimf_path_new(addr_spec); if path.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if addr_spec.is_null() { mailimf_addr_spec_free(addr_spec); } } else { *indx = cur_token; *result = path; return MAILIMF_NO_ERROR as libc::c_int; } } } } } } return res; } unsafe fn mailimf_keywords_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_keywords, ) -> libc::c_int { let mut keywords: *mut mailimf_keywords = 0 as *mut mailimf_keywords; let mut list: *mut clist = 0 as *mut clist; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Keywords\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Keywords\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_struct_list_parse( message, length, &mut cur_token, &mut list, ',' as i32 as libc::c_char, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut libc::c_char, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_phrase_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_char) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_phrase_free)), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { keywords = mailimf_keywords_new(list); if keywords.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = keywords; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } clist_foreach( list, ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_char) -> ()>, clist_func, >(Some(mailimf_phrase_free)), 0 as *mut libc::c_void, ); clist_free(list); } } } return res; } unsafe fn mailimf_comments_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_comments, ) -> libc::c_int { let mut comments: *mut mailimf_comments = 0 as *mut mailimf_comments; let mut value: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Comments\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Comments\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstructured_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { comments = mailimf_comments_new(value); if comments.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = comments; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_unstructured_free(value); } } } return res; } unsafe fn mailimf_subject_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_subject, ) -> libc::c_int { let mut subject: *mut mailimf_subject = 0 as *mut mailimf_subject; let mut value: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Subject\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Subject\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstructured_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { subject = mailimf_subject_new(value); if subject.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = subject; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_unstructured_free(value); } } } return res; } /* exported for IMAP */ pub unsafe fn mailimf_references_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_references, ) -> libc::c_int { let mut references: *mut mailimf_references = 0 as *mut mailimf_references; let mut cur_token: size_t = 0; let mut msg_id_list: *mut clist = 0 as *mut clist; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"References\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"References\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_msg_id_list_parse(message, length, &mut cur_token, &mut msg_id_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { references = mailimf_references_new(msg_id_list); if references.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = references; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } clist_foreach( msg_id_list, ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_char) -> ()>, clist_func, >(Some(mailimf_msg_id_free)), 0 as *mut libc::c_void, ); clist_free(msg_id_list); } } } return res; } pub unsafe fn mailimf_msg_id_list_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut clist, ) -> libc::c_int { return mailimf_struct_multiple_parse( message, length, indx, result, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut libc::c_char, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_unstrict_msg_id_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_char) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_msg_id_free)), ); } unsafe fn mailimf_unstrict_msg_id_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut msgid: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { return r; } r = mailimf_parse_unwanted_msg_id(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_msg_id_parse(message, length, &mut cur_token, &mut msgid); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } r = mailimf_parse_unwanted_msg_id(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { free(msgid as *mut libc::c_void); return r; } *result = msgid; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_parse_unwanted_msg_id( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut word: *mut libc::c_char = 0 as *mut libc::c_char; let mut token_parsed: libc::c_int = 0; cur_token = *indx; token_parsed = 1i32; while 0 != token_parsed { token_parsed = 0i32; r = mailimf_word_parse(message, length, &mut cur_token, &mut word); if r == MAILIMF_NO_ERROR as libc::c_int { mailimf_word_free(word); token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_semi_colon_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_comma_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_plus_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_colon_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_point_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } r = mailimf_at_sign_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { token_parsed = 1i32 } else if r == MAILIMF_ERROR_PARSE as libc::c_int { } else { return r; } } *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn mailimf_at_sign_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '@' as i32 as libc::c_char); } unsafe fn mailimf_point_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { return mailimf_unstrict_char_parse(message, length, indx, '.' as i32 as libc::c_char); } pub unsafe fn mailimf_word_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut word: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_atom_parse(message, length, &mut cur_token, &mut word); if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_quoted_string_parse(message, length, &mut cur_token, &mut word) } if r != MAILIMF_NO_ERROR as libc::c_int { return r; } *result = word; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_quoted_string_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut gstr: *mut MMAPString = 0 as *mut MMAPString; let mut ch: libc::c_char = 0; let mut str: *mut libc::c_char = 0 as *mut libc::c_char; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { r = mailimf_dquote_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { gstr = mmap_string_new(b"\x00" as *const u8 as *const libc::c_char); if gstr.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { loop { r = mailimf_fws_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { if mmap_string_append_c(gstr, ' ' as i32 as libc::c_char).is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 14861901777624095282; break; } } else if r != MAILIMF_ERROR_PARSE as libc::c_int { res = r; current_block = 14861901777624095282; break; } r = mailimf_qcontent_parse(message, length, &mut cur_token, &mut ch); if r == MAILIMF_NO_ERROR as libc::c_int { if !mmap_string_append_c(gstr, ch).is_null() { continue; } res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 14861901777624095282; break; } else { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 5494826135382683477; break; } res = r; current_block = 14861901777624095282; break; } } match current_block { 5494826135382683477 => { r = mailimf_dquote_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { str = strdup((*gstr).str_0); if str.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { mmap_string_free(gstr); *indx = cur_token; *result = str; return MAILIMF_NO_ERROR as libc::c_int; } } } _ => {} } mmap_string_free(gstr); } } } return res; } pub unsafe fn mailimf_atom_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; let mut atom: *mut libc::c_char = 0 as *mut libc::c_char; let mut end: size_t = 0; cur_token = *indx; r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r } else { end = cur_token; if end >= length { res = MAILIMF_ERROR_PARSE as libc::c_int } else { while 0 != is_atext(*message.offset(end as isize)) { end = end.wrapping_add(1); if end >= length { break; } } if end == cur_token { res = MAILIMF_ERROR_PARSE as libc::c_int } else { atom = malloc( end.wrapping_sub(cur_token) .wrapping_add(1i32 as libc::size_t), ) as *mut libc::c_char; if atom.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { strncpy( atom, message.offset(cur_token as isize), end.wrapping_sub(cur_token), ); *atom.offset(end.wrapping_sub(cur_token) as isize) = '\u{0}' as i32 as libc::c_char; cur_token = end; *indx = cur_token; *result = atom; return MAILIMF_NO_ERROR as libc::c_int; } } } } return res; } unsafe fn mailimf_struct_multiple_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut clist, mut parser: Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, mut destructor: Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, ) -> libc::c_int { let mut current_block: u64; let mut struct_list: *mut clist = 0 as *mut clist; let mut cur_token: size_t = 0; let mut value: *mut libc::c_void = 0 as *mut libc::c_void; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = parser.expect("non-null function pointer")( message, length, &mut cur_token, &mut value as *mut *mut libc::c_void as *mut libc::c_void, ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { struct_list = clist_new(); if struct_list.is_null() { destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int } else { r = clist_insert_after(struct_list, (*struct_list).last, value); if r < 0i32 { destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int } else { loop { r = parser.expect("non-null function pointer")( message, length, &mut cur_token, &mut value as *mut *mut libc::c_void as *mut libc::c_void, ); if r != MAILIMF_NO_ERROR as libc::c_int { if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 11057878835866523405; break; } res = r; current_block = 8222683242185098763; break; } else { r = clist_insert_after(struct_list, (*struct_list).last, value); if !(r < 0i32) { continue; } destructor.expect("non-null function pointer")(value); res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 8222683242185098763; break; } } match current_block { 8222683242185098763 => {} _ => { *result = struct_list; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } clist_foreach( struct_list, ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, clist_func, >(destructor), 0 as *mut libc::c_void, ); clist_free(struct_list); } } return res; } unsafe fn mailimf_in_reply_to_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_in_reply_to, ) -> libc::c_int { let mut in_reply_to: *mut mailimf_in_reply_to = 0 as *mut mailimf_in_reply_to; let mut cur_token: size_t = 0; let mut msg_id_list: *mut clist = 0 as *mut clist; let mut res: libc::c_int = 0; let mut r: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"In-Reply-To\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"In-Reply-To\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_msg_id_list_parse(message, length, &mut cur_token, &mut msg_id_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { in_reply_to = mailimf_in_reply_to_new(msg_id_list); if in_reply_to.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = in_reply_to; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } clist_foreach( msg_id_list, ::std::mem::transmute::< Option<unsafe fn(_: *mut libc::c_char) -> ()>, clist_func, >(Some(mailimf_msg_id_free)), 0 as *mut libc::c_void, ); clist_free(msg_id_list); } } } return res; } unsafe fn mailimf_message_id_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_message_id, ) -> libc::c_int { let mut value: *mut libc::c_char = 0 as *mut libc::c_char; let mut cur_token: size_t = 0; let mut message_id: *mut mailimf_message_id = 0 as *mut mailimf_message_id; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Message-ID\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Message-ID\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_msg_id_parse(message, length, &mut cur_token, &mut value); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { message_id = mailimf_message_id_new(value); if message_id.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = message_id; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_msg_id_free(value); } } } return res; } unsafe fn mailimf_bcc_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_bcc, ) -> libc::c_int { let mut current_block: u64; let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut bcc: *mut mailimf_bcc = 0 as *mut mailimf_bcc; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; addr_list = 0 as *mut mailimf_address_list; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Bcc\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Bcc\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); match r { 0 => { /* do nothing */ current_block = 2838571290723028321; } 1 => { r = mailimf_cfws_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int && r != MAILIMF_ERROR_PARSE as libc::c_int { res = r; current_block = 15260376711225273221; } else { current_block = 2838571290723028321; } } _ => { res = r; current_block = 15260376711225273221; } } match current_block { 15260376711225273221 => {} _ => { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { bcc = mailimf_bcc_new(addr_list); if bcc.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = bcc; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } } } } if !addr_list.is_null() { mailimf_address_list_free(addr_list); } return res; } unsafe fn mailimf_cc_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_cc, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut cc: *mut mailimf_cc = 0 as *mut mailimf_cc; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Cc\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Cc\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { cc = mailimf_cc_new(addr_list); if cc.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = cc; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_address_list_free(addr_list); } } } return res; } unsafe fn mailimf_to_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_to, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut to: *mut mailimf_to = 0 as *mut mailimf_to; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"To\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"To\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { to = mailimf_to_new(addr_list); if to.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = to; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_address_list_free(addr_list); } } } return res; } unsafe fn mailimf_reply_to_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_reply_to, ) -> libc::c_int { let mut addr_list: *mut mailimf_address_list = 0 as *mut mailimf_address_list; let mut reply_to: *mut mailimf_reply_to = 0 as *mut mailimf_reply_to; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Reply-To\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Reply-To\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_address_list_parse(message, length, &mut cur_token, &mut addr_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { reply_to = mailimf_reply_to_new(addr_list); if reply_to.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = reply_to; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_address_list_free(addr_list); } } } return res; } unsafe fn mailimf_sender_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_sender, ) -> libc::c_int { let mut mb: *mut mailimf_mailbox = 0 as *mut mailimf_mailbox; let mut sender: *mut mailimf_sender = 0 as *mut mailimf_sender; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Sender\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Sender\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_mailbox_parse(message, length, &mut cur_token, &mut mb); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { sender = mailimf_sender_new(mb); if sender.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = sender; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_mailbox_free(mb); } } } return res; } unsafe fn mailimf_from_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_from, ) -> libc::c_int { let mut mb_list: *mut mailimf_mailbox_list = 0 as *mut mailimf_mailbox_list; let mut from: *mut mailimf_from = 0 as *mut mailimf_from; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"From\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"From\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_colon_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_mailbox_list_parse(message, length, &mut cur_token, &mut mb_list); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { from = mailimf_from_new(mb_list); if from.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = from; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } mailimf_mailbox_list_free(mb_list); } } } return res; } unsafe fn mailimf_orig_date_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_orig_date, ) -> libc::c_int { let mut date_time: *mut mailimf_date_time = 0 as *mut mailimf_date_time; let mut orig_date: *mut mailimf_orig_date = 0 as *mut mailimf_orig_date; let mut cur_token: size_t = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; r = mailimf_token_case_insensitive_len_parse( message, length, &mut cur_token, b"Date:\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"Date:\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_date_time_parse(message, length, &mut cur_token, &mut date_time); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_ignore_unstructured_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { r = mailimf_unstrict_crlf_parse(message, length, &mut cur_token); if r != MAILIMF_NO_ERROR as libc::c_int { res = r } else { orig_date = mailimf_orig_date_new(date_time); if orig_date.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = orig_date; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } mailimf_date_time_free(date_time); } } return res; } unsafe fn mailimf_ignore_unstructured_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut cur_token: size_t = 0; let mut state: libc::c_int = 0; let mut terminal: size_t = 0; cur_token = *indx; state = UNSTRUCTURED_START as libc::c_int; terminal = cur_token; while state != UNSTRUCTURED_OUT as libc::c_int { match state { 0 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } terminal = cur_token; match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } 1 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } 2 => { if cur_token >= length { state = UNSTRUCTURED_OUT as libc::c_int } else { match *message.offset(cur_token as isize) as libc::c_int { 9 | 32 => state = UNSTRUCTURED_WSP as libc::c_int, _ => state = UNSTRUCTURED_OUT as libc::c_int, } } } 3 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, _ => state = UNSTRUCTURED_START as libc::c_int, } } _ => {} } cur_token = cur_token.wrapping_add(1) } *indx = terminal; return MAILIMF_NO_ERROR as libc::c_int; } unsafe fn guess_header_type( mut message: *const libc::c_char, mut length: size_t, mut indx: size_t, ) -> libc::c_int { let mut state: libc::c_int = 0; let mut r: libc::c_int = 0; state = HEADER_START as libc::c_int; loop { if indx >= length { return MAILIMF_FIELD_NONE as libc::c_int; } match state { 0 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 66 => return MAILIMF_FIELD_BCC as libc::c_int, 67 => state = HEADER_C as libc::c_int, 68 => return MAILIMF_FIELD_ORIG_DATE as libc::c_int, 70 => return MAILIMF_FIELD_FROM as libc::c_int, 73 => return MAILIMF_FIELD_IN_REPLY_TO as libc::c_int, 75 => return MAILIMF_FIELD_KEYWORDS as libc::c_int, 77 => return MAILIMF_FIELD_MESSAGE_ID as libc::c_int, 82 => state = HEADER_R as libc::c_int, 84 => return MAILIMF_FIELD_TO as libc::c_int, 83 => state = HEADER_S as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } 1 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 79 => return MAILIMF_FIELD_COMMENTS as libc::c_int, 67 => return MAILIMF_FIELD_CC as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } 2 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 69 => state = HEADER_RE as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } 3 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 70 => return MAILIMF_FIELD_REFERENCES as libc::c_int, 80 => return MAILIMF_FIELD_REPLY_TO as libc::c_int, 83 => state = HEADER_RES as libc::c_int, 84 => return MAILIMF_FIELD_RETURN_PATH as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } 4 => { match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 69 => return MAILIMF_FIELD_SENDER as libc::c_int, 85 => return MAILIMF_FIELD_SUBJECT as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } 5 => { r = mailimf_token_case_insensitive_len_parse( message, length, &mut indx, b"ent-\x00" as *const u8 as *const libc::c_char as *mut libc::c_char, strlen(b"ent-\x00" as *const u8 as *const libc::c_char), ); if r != MAILIMF_NO_ERROR as libc::c_int { return MAILIMF_FIELD_NONE as libc::c_int; } if indx >= length { return MAILIMF_FIELD_NONE as libc::c_int; } match toupper(*message.offset(indx as isize) as libc::c_uchar as libc::c_int) as libc::c_char as libc::c_int { 68 => return MAILIMF_FIELD_RESENT_DATE as libc::c_int, 70 => return MAILIMF_FIELD_RESENT_FROM as libc::c_int, 83 => return MAILIMF_FIELD_RESENT_SENDER as libc::c_int, 84 => return MAILIMF_FIELD_RESENT_TO as libc::c_int, 67 => return MAILIMF_FIELD_RESENT_CC as libc::c_int, 66 => return MAILIMF_FIELD_RESENT_BCC as libc::c_int, 77 => return MAILIMF_FIELD_RESENT_MSG_ID as libc::c_int, _ => return MAILIMF_FIELD_NONE as libc::c_int, } } _ => {} } indx = indx.wrapping_add(1) } } /* mailimf_envelope_fields_parse will parse the given fields (Date, From, Sender, Reply-To, To, Cc, Bcc, Message-ID, In-Reply-To, References and Subject) @param message this is a string containing the header fields @param length this is the size of the given string @param indx this is a pointer to the start of the header fields in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_envelope_fields_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_fields, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut fields: *mut mailimf_fields = 0 as *mut mailimf_fields; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; list = clist_new(); if list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { loop { let mut elt: *mut mailimf_field = 0 as *mut mailimf_field; r = mailimf_envelope_field_parse(message, length, &mut cur_token, &mut elt); if r == MAILIMF_NO_ERROR as libc::c_int { r = clist_insert_after(list, (*list).last, elt as *mut libc::c_void); if !(r < 0i32) { continue; } res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 894413572976700158; break; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { r = mailimf_ignore_field_parse(message, length, &mut cur_token); if r == MAILIMF_NO_ERROR as libc::c_int { continue; } /* do nothing */ if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 2719512138335094285; break; } res = r; current_block = 894413572976700158; break; } else { res = r; current_block = 894413572976700158; break; } } match current_block { 2719512138335094285 => { fields = mailimf_fields_new(list); if fields.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int } else { *result = fields; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } _ => {} } if !list.is_null() { clist_foreach( list, ::std::mem::transmute::<Option<unsafe fn(_: *mut mailimf_field) -> ()>, clist_func>( Some(mailimf_field_free), ), 0 as *mut libc::c_void, ); clist_free(list); } } return res; } /* mailimf_ignore_field_parse will skip the given field @param message this is a string containing the header field @param length this is the size of the given string @param indx this is a pointer to the start of the header field in the given string, (* indx) is modified to point at the end of the parsed data @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_ignore_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, ) -> libc::c_int { let mut has_field: libc::c_int = 0; let mut cur_token: size_t = 0; let mut state: libc::c_int = 0; let mut terminal: size_t = 0; has_field = 0i32; cur_token = *indx; terminal = cur_token; state = UNSTRUCTURED_START as libc::c_int; if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 13 => return MAILIMF_ERROR_PARSE as libc::c_int, 10 => return MAILIMF_ERROR_PARSE as libc::c_int, _ => {} } while state != UNSTRUCTURED_OUT as libc::c_int { match state { 0 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, 58 => { has_field = 1i32; state = UNSTRUCTURED_START as libc::c_int } _ => state = UNSTRUCTURED_START as libc::c_int, } } 1 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 10 => state = UNSTRUCTURED_LF as libc::c_int, 58 => { has_field = 1i32; state = UNSTRUCTURED_START as libc::c_int } _ => state = UNSTRUCTURED_START as libc::c_int, } } 2 => { if cur_token >= length { terminal = cur_token; state = UNSTRUCTURED_OUT as libc::c_int } else { match *message.offset(cur_token as isize) as libc::c_int { 9 | 32 => state = UNSTRUCTURED_WSP as libc::c_int, _ => { terminal = cur_token; state = UNSTRUCTURED_OUT as libc::c_int } } } } 3 => { if cur_token >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } match *message.offset(cur_token as isize) as libc::c_int { 13 => state = UNSTRUCTURED_CR as libc::c_int, 10 => state = UNSTRUCTURED_LF as libc::c_int, 58 => { has_field = 1i32; state = UNSTRUCTURED_START as libc::c_int } _ => state = UNSTRUCTURED_START as libc::c_int, } } _ => {} } cur_token = cur_token.wrapping_add(1) } if 0 == has_field { return MAILIMF_ERROR_PARSE as libc::c_int; } *indx = terminal; return MAILIMF_NO_ERROR as libc::c_int; } /* static int mailimf_ftext_parse(const char * message, size_t length, size_t * indx, gchar * result) { return mailimf_typed_text_parse(message, length, indx, result, is_ftext); } */ unsafe fn mailimf_envelope_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_field, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut type_0: libc::c_int = 0; let mut orig_date: *mut mailimf_orig_date = 0 as *mut mailimf_orig_date; let mut from: *mut mailimf_from = 0 as *mut mailimf_from; let mut sender: *mut mailimf_sender = 0 as *mut mailimf_sender; let mut reply_to: *mut mailimf_reply_to = 0 as *mut mailimf_reply_to; let mut to: *mut mailimf_to = 0 as *mut mailimf_to; let mut cc: *mut mailimf_cc = 0 as *mut mailimf_cc; let mut bcc: *mut mailimf_bcc = 0 as *mut mailimf_bcc; let mut message_id: *mut mailimf_message_id = 0 as *mut mailimf_message_id; let mut in_reply_to: *mut mailimf_in_reply_to = 0 as *mut mailimf_in_reply_to; let mut references: *mut mailimf_references = 0 as *mut mailimf_references; let mut subject: *mut mailimf_subject = 0 as *mut mailimf_subject; let mut optional_field: *mut mailimf_optional_field = 0 as *mut mailimf_optional_field; let mut field: *mut mailimf_field = 0 as *mut mailimf_field; let mut guessed_type: libc::c_int = 0; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; orig_date = 0 as *mut mailimf_orig_date; from = 0 as *mut mailimf_from; sender = 0 as *mut mailimf_sender; reply_to = 0 as *mut mailimf_reply_to; to = 0 as *mut mailimf_to; cc = 0 as *mut mailimf_cc; bcc = 0 as *mut mailimf_bcc; message_id = 0 as *mut mailimf_message_id; in_reply_to = 0 as *mut mailimf_in_reply_to; references = 0 as *mut mailimf_references; subject = 0 as *mut mailimf_subject; optional_field = 0 as *mut mailimf_optional_field; guessed_type = guess_header_type(message, length, cur_token); type_0 = MAILIMF_FIELD_NONE as libc::c_int; match guessed_type { 9 => { r = mailimf_orig_date_parse(message, length, &mut cur_token, &mut orig_date); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 10 => { r = mailimf_from_parse(message, length, &mut cur_token, &mut from); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 11 => { r = mailimf_sender_parse(message, length, &mut cur_token, &mut sender); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 12 => { r = mailimf_reply_to_parse(message, length, &mut cur_token, &mut reply_to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 13 => { r = mailimf_to_parse(message, length, &mut cur_token, &mut to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 14 => { r = mailimf_cc_parse(message, length, &mut cur_token, &mut cc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 15 => { r = mailimf_bcc_parse(message, length, &mut cur_token, &mut bcc); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 16 => { r = mailimf_message_id_parse(message, length, &mut cur_token, &mut message_id); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 17 => { r = mailimf_in_reply_to_parse(message, length, &mut cur_token, &mut in_reply_to); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 18 => { r = mailimf_references_parse(message, length, &mut cur_token, &mut references); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } 19 => { r = mailimf_subject_parse(message, length, &mut cur_token, &mut subject); if r == MAILIMF_NO_ERROR as libc::c_int { type_0 = guessed_type; current_block = 4488496028633655612; } else if r == MAILIMF_ERROR_PARSE as libc::c_int { current_block = 4488496028633655612; } else { /* do nothing */ res = r; current_block = 15605017197726313499; } } _ => { current_block = 4488496028633655612; } } match current_block { 4488496028633655612 => { if type_0 == MAILIMF_FIELD_NONE as libc::c_int { res = MAILIMF_ERROR_PARSE as libc::c_int } else { field = mailimf_field_new( type_0, 0 as *mut mailimf_return, 0 as *mut mailimf_orig_date, 0 as *mut mailimf_from, 0 as *mut mailimf_sender, 0 as *mut mailimf_to, 0 as *mut mailimf_cc, 0 as *mut mailimf_bcc, 0 as *mut mailimf_message_id, orig_date, from, sender, reply_to, to, cc, bcc, message_id, in_reply_to, references, subject, 0 as *mut mailimf_comments, 0 as *mut mailimf_keywords, optional_field, ); if field.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !orig_date.is_null() { mailimf_orig_date_free(orig_date); } if !from.is_null() { mailimf_from_free(from); } if !sender.is_null() { mailimf_sender_free(sender); } if !reply_to.is_null() { mailimf_reply_to_free(reply_to); } if !to.is_null() { mailimf_to_free(to); } if !cc.is_null() { mailimf_cc_free(cc); } if !bcc.is_null() { mailimf_bcc_free(bcc); } if !message_id.is_null() { mailimf_message_id_free(message_id); } if !in_reply_to.is_null() { mailimf_in_reply_to_free(in_reply_to); } if !references.is_null() { mailimf_references_free(references); } if !subject.is_null() { mailimf_subject_free(subject); } if !optional_field.is_null() { mailimf_optional_field_free(optional_field); } } else { *result = field; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } } _ => {} } return res; } /* mailimf_envelope_fields will parse the given fields (Date, From, Sender, Reply-To, To, Cc, Bcc, Message-ID, In-Reply-To, References and Subject), other fields will be added as optional fields. @param message this is a string containing the header fields @param length this is the size of the given string @param indx this is a pointer to the start of the header fields in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_envelope_and_optional_fields_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_fields, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut fields: *mut mailimf_fields = 0 as *mut mailimf_fields; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; list = 0 as *mut clist; r = mailimf_struct_multiple_parse( message, length, &mut cur_token, &mut list, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut mailimf_field, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_envelope_or_optional_field_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_field_free)), ); match r { 0 => { /* do nothing */ current_block = 11050875288958768710; } 1 => { list = clist_new(); if list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 7755940856643933760; } else { current_block = 11050875288958768710; } } _ => { res = r; current_block = 7755940856643933760; } } match current_block { 11050875288958768710 => { fields = mailimf_fields_new(list); if fields.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !list.is_null() { clist_foreach( list, ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, clist_func, >(Some(mailimf_field_free)), 0 as *mut libc::c_void, ); clist_free(list); } } else { *result = fields; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } _ => {} } return res; } unsafe fn mailimf_envelope_or_optional_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_field, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut cur_token: size_t = 0; let mut optional_field: *mut mailimf_optional_field = 0 as *mut mailimf_optional_field; let mut field: *mut mailimf_field = 0 as *mut mailimf_field; r = mailimf_envelope_field_parse(message, length, indx, result); if r == MAILIMF_NO_ERROR as libc::c_int { return MAILIMF_NO_ERROR as libc::c_int; } cur_token = *indx; r = mailimf_optional_field_parse(message, length, &mut cur_token, &mut optional_field); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } field = mailimf_field_new( MAILIMF_FIELD_OPTIONAL_FIELD as libc::c_int, 0 as *mut mailimf_return, 0 as *mut mailimf_orig_date, 0 as *mut mailimf_from, 0 as *mut mailimf_sender, 0 as *mut mailimf_to, 0 as *mut mailimf_cc, 0 as *mut mailimf_bcc, 0 as *mut mailimf_message_id, 0 as *mut mailimf_orig_date, 0 as *mut mailimf_from, 0 as *mut mailimf_sender, 0 as *mut mailimf_reply_to, 0 as *mut mailimf_to, 0 as *mut mailimf_cc, 0 as *mut mailimf_bcc, 0 as *mut mailimf_message_id, 0 as *mut mailimf_in_reply_to, 0 as *mut mailimf_references, 0 as *mut mailimf_subject, 0 as *mut mailimf_comments, 0 as *mut mailimf_keywords, optional_field, ); if field.is_null() { mailimf_optional_field_free(optional_field); return MAILIMF_ERROR_MEMORY as libc::c_int; } *result = field; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } /* mailimf_envelope_fields will parse the given fields as optional fields. @param message this is a string containing the header fields @param length this is the size of the given string @param indx this is a pointer to the start of the header fields in the given string, (* indx) is modified to point at the end of the parsed data @param result the result of the parse operation is stored in (* result) @return MAILIMF_NO_ERROR on success, MAILIMF_ERROR_XXX on error */ pub unsafe fn mailimf_optional_fields_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_fields, ) -> libc::c_int { let mut current_block: u64; let mut cur_token: size_t = 0; let mut list: *mut clist = 0 as *mut clist; let mut fields: *mut mailimf_fields = 0 as *mut mailimf_fields; let mut r: libc::c_int = 0; let mut res: libc::c_int = 0; cur_token = *indx; list = 0 as *mut clist; r = mailimf_struct_multiple_parse( message, length, &mut cur_token, &mut list, ::std::mem::transmute::< Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut *mut mailimf_field, ) -> libc::c_int, >, Option< unsafe fn( _: *const libc::c_char, _: size_t, _: *mut size_t, _: *mut libc::c_void, ) -> libc::c_int, >, >(Some(mailimf_only_optional_field_parse)), ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, Option<unsafe fn(_: *mut libc::c_void) -> libc::c_int>, >(Some(mailimf_field_free)), ); match r { 0 => { /* do nothing */ current_block = 11050875288958768710; } 1 => { list = clist_new(); if list.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; current_block = 4409055091581443388; } else { current_block = 11050875288958768710; } } _ => { res = r; current_block = 4409055091581443388; } } match current_block { 11050875288958768710 => { fields = mailimf_fields_new(list); if fields.is_null() { res = MAILIMF_ERROR_MEMORY as libc::c_int; if !list.is_null() { clist_foreach( list, ::std::mem::transmute::< Option<unsafe fn(_: *mut mailimf_field) -> ()>, clist_func, >(Some(mailimf_field_free)), 0 as *mut libc::c_void, ); clist_free(list); } } else { *result = fields; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } } _ => {} } return res; } unsafe fn mailimf_only_optional_field_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut mailimf_field, ) -> libc::c_int { let mut r: libc::c_int = 0; let mut cur_token: size_t = 0; let mut optional_field: *mut mailimf_optional_field = 0 as *mut mailimf_optional_field; let mut field: *mut mailimf_field = 0 as *mut mailimf_field; cur_token = *indx; r = mailimf_optional_field_parse(message, length, &mut cur_token, &mut optional_field); if r != MAILIMF_NO_ERROR as libc::c_int { return r; } field = mailimf_field_new( MAILIMF_FIELD_OPTIONAL_FIELD as libc::c_int, 0 as *mut mailimf_return, 0 as *mut mailimf_orig_date, 0 as *mut mailimf_from, 0 as *mut mailimf_sender, 0 as *mut mailimf_to, 0 as *mut mailimf_cc, 0 as *mut mailimf_bcc, 0 as *mut mailimf_message_id, 0 as *mut mailimf_orig_date, 0 as *mut mailimf_from, 0 as *mut mailimf_sender, 0 as *mut mailimf_reply_to, 0 as *mut mailimf_to, 0 as *mut mailimf_cc, 0 as *mut mailimf_bcc, 0 as *mut mailimf_message_id, 0 as *mut mailimf_in_reply_to, 0 as *mut mailimf_references, 0 as *mut mailimf_subject, 0 as *mut mailimf_comments, 0 as *mut mailimf_keywords, optional_field, ); if field.is_null() { mailimf_optional_field_free(optional_field); return MAILIMF_ERROR_MEMORY as libc::c_int; } *result = field; *indx = cur_token; return MAILIMF_NO_ERROR as libc::c_int; } pub unsafe fn mailimf_custom_string_parse( mut message: *const libc::c_char, mut length: size_t, mut indx: *mut size_t, mut result: *mut *mut libc::c_char, mut is_custom_char: Option<unsafe fn(_: libc::c_char) -> libc::c_int>, ) -> libc::c_int { let mut begin: size_t = 0; let mut end: size_t = 0; let mut gstr: *mut libc::c_char = 0 as *mut libc::c_char; begin = *indx; end = begin; if end >= length { return MAILIMF_ERROR_PARSE as libc::c_int; } while 0 != is_custom_char.expect("non-null function pointer")(*message.offset(end as isize)) { end = end.wrapping_add(1); if end >= length { break; } } if end != begin { gstr = malloc(end.wrapping_sub(begin).wrapping_add(1i32 as libc::size_t)) as *mut libc::c_char; if gstr.is_null() { return MAILIMF_ERROR_MEMORY as libc::c_int; } strncpy( gstr, message.offset(begin as isize), end.wrapping_sub(begin), ); *gstr.offset(end.wrapping_sub(begin) as isize) = '\u{0}' as i32 as libc::c_char; *indx = end; *result = gstr; return MAILIMF_NO_ERROR as libc::c_int; } else { return MAILIMF_ERROR_PARSE as libc::c_int; }; }
use crate::archives::Id; use crate::archives::packages::patches::Version; use aes_gcm_siv::{Aes256GcmSiv}; use aes_gcm_siv::aead::{Aead, NewAead, generic_array::GenericArray}; pub const KEY_LENGTH: usize = 16; pub const NONCE_LENGTH: usize = 12; pub type Key = [u8; KEY_LENGTH]; pub type Nonce = [u8; NONCE_LENGTH];//GenericArray<u8, NONCE_LENGTH>; const KEY: Key = [ 0xD6, 0x2A, 0xB2, 0xC1, 0x0C, 0xC0, 0x1B, 0xC5, 0x35, 0xDB, 0x7B, 0x86, 0x55, 0xC7, 0xDC, 0x3B ]; const KEY_ALT: Key = [ 0x3A, 0x4A, 0x5D, 0x36, 0x73, 0xA6, 0x60, 0x58, 0x7E, 0x63, 0xE6, 0x76, 0xE4, 0x08, 0x92, 0xB5 ]; fn get_cipher(alternate: bool) -> Aes256GcmSiv { return if alternate { Aes256GcmSiv::new(GenericArray::from_slice(&KEY)) } else { Aes256GcmSiv::new(GenericArray::from_slice(&KEY_ALT)) } } fn make_nonce(package_id: Id, version: Version) -> Nonce { return [ 0x84 ^ (package_id >> 8 & 0xFF) as u8, 0xDF ^ (version as u8), 0x11, 0xC0, 0xAC, 0xAB, 0xFA, 0x20, 0x33, 0x11, 0x26, 0x99 ^ (package_id as u8 & 0xFF) ]; } pub fn decrypt(package_id: Id, version: Version, alternate_key: bool, data: Vec<u8>) -> Vec<u8> { let raw_nonce = make_nonce(package_id, version); let nonce = GenericArray::from_slice(&raw_nonce); let cipher = get_cipher(alternate_key); let result = cipher.decrypt(nonce, data.as_slice()); if result.is_err() { panic!("Decryption failed!") } else { return result.unwrap(); } }
//! Build script for chars. //! //! This just runs the generator/ subproject, to generate the source files from files in data/. use std::env; use std::error::Error; use std::path::Path; extern crate chars_data; fn main() -> Result<(), Box<dyn Error>> { let out_dir = env::var("OUT_DIR")?; chars_data::generate_files(Path::new(&out_dir))?; Ok(()) }
// 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::alloc::Layout; use std::fmt; use std::marker::PhantomData; use std::sync::Arc; use common_arrow::arrow::bitmap::Bitmap; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::number::Number; use common_expression::types::number::F64; use common_expression::types::DataType; use common_expression::types::NumberDataType; use common_expression::types::NumberType; use common_expression::types::ValueType; use common_expression::with_number_mapped_type; use common_expression::Column; use common_expression::ColumnBuilder; use common_expression::Scalar; use common_io::prelude::*; use num_traits::AsPrimitive; use serde::Deserialize; use serde::Serialize; use super::StateAddr; use crate::aggregates::aggregate_function_factory::AggregateFunctionDescription; use crate::aggregates::aggregator_common::assert_binary_arguments; use crate::aggregates::AggregateFunction; use crate::aggregates::AggregateFunctionRef; #[derive(Serialize, Deserialize)] pub struct AggregateCovarianceState { pub count: u64, pub co_moments: f64, pub left_mean: f64, pub right_mean: f64, } // Source: "Numerically Stable, Single-Pass, Parallel Statistics Algorithms" // (J. Bennett et al., Sandia National Laboratories, // 2009 IEEE International Conference on Cluster Computing) // Paper link: https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.214.8508&rep=rep1&type=pdf impl AggregateCovarianceState { // The idea is from the formula III.9 in the paper. The original formula is: // co-moments = co-moments + (n-1)/n * (s-left_mean) * (t-right_mean) // Since (n-1)/n may introduce some bias when n >> 1, Clickhouse transform the formula into: // co-moments = co-moments + (s-new_left_mean) * (t-right_mean). // This equals the formula in the paper. Here we take the same approach as Clickhouse // does. Thanks Clickhouse! #[inline(always)] fn add(&mut self, s: f64, t: f64) { let left_delta = s - self.left_mean; let right_delta = t - self.right_mean; self.count += 1; let new_left_mean = self.left_mean + left_delta / self.count as f64; let new_right_mean = self.right_mean + right_delta / self.count as f64; self.co_moments += (s - new_left_mean) * (t - self.right_mean); self.left_mean = new_left_mean; self.right_mean = new_right_mean; } // The idea is from the formula III.6 in the paper: // co-moments = co-moments + (n1*n2)/(n1+n2) * delta_left_mean * delta_right_mean // Clickhouse also has some optimization when two data sets are large and comparable in size. // Here we take the same approach as Clickhouse does. Thanks Clickhouse! #[inline(always)] fn merge(&mut self, other: &Self) { let total = self.count + other.count; if total == 0 { return; } let factor = self.count as f64 * other.count as f64 / total as f64; // 'n1*n2/n' in the paper let left_delta = self.left_mean - other.left_mean; let right_delta = self.right_mean - other.right_mean; self.co_moments += other.co_moments + left_delta * right_delta * factor; if large_and_comparable(self.count, other.count) { self.left_mean = (self.left_sum() + other.left_sum()) / total as f64; self.right_mean = (self.right_sum() + other.right_sum()) / total as f64; } else { self.left_mean = other.left_mean + left_delta * self.count as f64 / total as f64; self.right_mean = other.right_mean + right_delta * self.count as f64 / total as f64; } self.count = total; } #[inline(always)] fn left_sum(&self) -> f64 { self.count as f64 * self.left_mean } #[inline(always)] fn right_sum(&self) -> f64 { self.count as f64 * self.right_mean } } fn large_and_comparable(a: u64, b: u64) -> bool { if a == 0 || b == 0 { return false; } let sensitivity = 0.001_f64; let threshold = 10000_f64; let min = a.min(b) as f64; let max = a.max(b) as f64; (1.0 - min / max) < sensitivity && min > threshold } #[derive(Clone)] pub struct AggregateCovarianceFunction<T0, T1, R> { display_name: String, _t0: PhantomData<T0>, _t1: PhantomData<T1>, _r: PhantomData<R>, } impl<T0, T1, R> AggregateFunction for AggregateCovarianceFunction<T0, T1, R> where T0: Number + AsPrimitive<f64>, T1: Number + AsPrimitive<f64>, R: AggregateCovariance, { fn name(&self) -> &str { R::name() } fn return_type(&self) -> Result<DataType> { Ok(DataType::Number(NumberDataType::Float64)) } fn init_state(&self, place: StateAddr) { place.write(|| AggregateCovarianceState { count: 0, left_mean: 0.0, right_mean: 0.0, co_moments: 0.0, }); } fn state_layout(&self) -> Layout { Layout::new::<AggregateCovarianceState>() } fn accumulate( &self, place: StateAddr, columns: &[Column], validity: Option<&Bitmap>, _input_rows: usize, ) -> Result<()> { let state = place.get::<AggregateCovarianceState>(); let left = NumberType::<T0>::try_downcast_column(&columns[0]).unwrap(); let right = NumberType::<T1>::try_downcast_column(&columns[1]).unwrap(); match validity { Some(bitmap) => { left.iter().zip(right.iter()).zip(bitmap.iter()).for_each( |((left_val, right_val), valid)| { if valid { state.add(left_val.as_(), right_val.as_()); } }, ); } None => { left.iter() .zip(right.iter()) .for_each(|(left_val, right_val)| { state.add(left_val.as_(), right_val.as_()); }); } } Ok(()) } fn accumulate_keys( &self, places: &[StateAddr], offset: usize, columns: &[Column], _input_rows: usize, ) -> Result<()> { let left = NumberType::<T0>::try_downcast_column(&columns[0]).unwrap(); let right = NumberType::<T1>::try_downcast_column(&columns[1]).unwrap(); left.iter().zip(right.iter()).zip(places.iter()).for_each( |((left_val, right_val), place)| { let place = place.next(offset); let state = place.get::<AggregateCovarianceState>(); state.add(left_val.as_(), right_val.as_()); }, ); Ok(()) } fn accumulate_row(&self, place: StateAddr, columns: &[Column], row: usize) -> Result<()> { let left = NumberType::<T0>::try_downcast_column(&columns[0]).unwrap(); let right = NumberType::<T1>::try_downcast_column(&columns[1]).unwrap(); let left_val = unsafe { left.get_unchecked(row) }; let right_val = unsafe { right.get_unchecked(row) }; let state = place.get::<AggregateCovarianceState>(); state.add(left_val.as_(), right_val.as_()); Ok(()) } fn serialize(&self, place: StateAddr, writer: &mut Vec<u8>) -> Result<()> { let state = place.get::<AggregateCovarianceState>(); serialize_into_buf(writer, state) } fn deserialize(&self, place: StateAddr, reader: &mut &[u8]) -> Result<()> { let state = place.get::<AggregateCovarianceState>(); *state = deserialize_from_slice(reader)?; Ok(()) } fn merge(&self, place: StateAddr, rhs: StateAddr) -> Result<()> { let state = place.get::<AggregateCovarianceState>(); let rhs = rhs.get::<AggregateCovarianceState>(); state.merge(rhs); Ok(()) } #[allow(unused_mut)] fn merge_result(&self, place: StateAddr, builder: &mut ColumnBuilder) -> Result<()> { let state = place.get::<AggregateCovarianceState>(); let builder = NumberType::<F64>::try_downcast_builder(builder).unwrap(); builder.push(R::apply(state).into()); Ok(()) } } impl<T0, T1, R> fmt::Display for AggregateCovarianceFunction<T0, T1, R> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.display_name) } } impl<T0, T1, R> AggregateCovarianceFunction<T0, T1, R> where T0: Number + AsPrimitive<f64>, T1: Number + AsPrimitive<f64>, R: AggregateCovariance, { pub fn try_create( display_name: &str, _arguments: Vec<DataType>, ) -> Result<AggregateFunctionRef> { Ok(Arc::new(Self { display_name: display_name.to_string(), _t0: PhantomData, _t1: PhantomData, _r: PhantomData, })) } } pub fn try_create_aggregate_covariance<R: AggregateCovariance>( display_name: &str, _params: Vec<Scalar>, arguments: Vec<DataType>, ) -> Result<AggregateFunctionRef> { assert_binary_arguments(display_name, arguments.len())?; with_number_mapped_type!(|NUM_TYPE0| match &arguments[0] { DataType::Number(NumberDataType::NUM_TYPE0) => with_number_mapped_type!(|NUM_TYPE1| match &arguments[1] { DataType::Number(NumberDataType::NUM_TYPE1) => { return AggregateCovarianceFunction::<NUM_TYPE0, NUM_TYPE1, R>::try_create( display_name, arguments, ); } _ => (), }), _ => (), }); Err(ErrorCode::BadDataValueType(format!( "Expected number data type, but got {:?}", arguments ))) } pub trait AggregateCovariance: Send + Sync + 'static { fn name() -> &'static str; fn apply(state: &AggregateCovarianceState) -> f64; } // Sample covariance function implementation struct AggregateCovarianceSampleImpl; impl AggregateCovariance for AggregateCovarianceSampleImpl { fn name() -> &'static str { "AggregateCovarianceSampleFunction" } fn apply(state: &AggregateCovarianceState) -> f64 { if state.count < 2 { f64::INFINITY } else { state.co_moments / (state.count - 1) as f64 } } } pub fn aggregate_covariance_sample_desc() -> AggregateFunctionDescription { AggregateFunctionDescription::creator(Box::new( try_create_aggregate_covariance::<AggregateCovarianceSampleImpl>, )) } // Population covariance function implementation struct AggregateCovariancePopulationImpl; impl AggregateCovariance for AggregateCovariancePopulationImpl { fn name() -> &'static str { "AggregateCovariancePopulationFunction" } fn apply(state: &AggregateCovarianceState) -> f64 { if state.count == 0 { f64::INFINITY } else if state.count == 1 { 0.0 } else { state.co_moments / state.count as f64 } } } pub fn aggregate_covariance_population_desc() -> AggregateFunctionDescription { AggregateFunctionDescription::creator(Box::new( try_create_aggregate_covariance::<AggregateCovariancePopulationImpl>, )) }
use core::{ convert::TryInto, default::Default, fmt::{self, Write}, ops::{Add, Sub}, }; use num_derive::FromPrimitive; /// The default starting location of the vga text mode framebuffer. pub const DEFAULT_VGA_TEXT_BUFF_START: *mut VgatBuffer< DEFAULT_VGA_TEXT_BUFF_WIDTH, DEFAULT_VGA_TEXT_BUFF_HEIGHT, > = 0xb8000 as *mut VgatBuffer<DEFAULT_VGA_TEXT_BUFF_WIDTH, DEFAULT_VGA_TEXT_BUFF_HEIGHT>; /// The default dimensions of the VGA framebuffer. pub const DEFAULT_VGA_TEXT_BUFF_WIDTH: usize = 80; pub const DEFAULT_VGA_TEXT_BUFF_HEIGHT: usize = 25; /// A VGA text framebuffer color (see below wikipedia link for explanation). #[derive(Clone, Copy, PartialEq, PartialOrd, FromPrimitive)] #[repr(u8)] pub enum Color { Black = 0x0 as u8, Blue = 0x1, Green = 0x2, Cyan = 0x3, Red = 0x4, Magenta = 0x5, Brown = 0x6, LightGray = 0x7, DarkGray = 0x8, LightBlue = 0x9, LightGreen = 0xa, LightCyan = 0xb, LightRed = 0xc, Pink = 0xd, Yellow = 0xe, White = 0xf, } impl Color { pub fn dim_variant(&self) -> Self { if *self >= Self::DarkGray { *self - 0x8 as u8 } else { *self } } pub fn bold_variant(&self) -> Self { self.dim_variant() + 0x8 } /// Converts the index of the ANSI color to the color primitive. pub fn from_ansi_code(ansi_code: char) -> Self { match ansi_code { '0' => Self::Black, '1' => Self::Red, '2' => Self::Green, '3' => Self::Brown, '4' => Self::Blue, '5' => Self::Magenta, '6' => Self::Cyan, '7' => Self::LightGray, _ => Self::White, } } } impl Default for Color { fn default() -> Self { Self::White } } impl Add<u8> for Color { type Output = Self; fn add(self, other: u8) -> Self { num::FromPrimitive::from_u8(self as u8 + other).unwrap_or_default() } } impl Sub<u8> for Color { type Output = Self; fn sub(self, other: u8) -> Self { num::FromPrimitive::from_u8(self as u8 - other).unwrap_or_default() } } /// See [VGA text mode](https://en.wikipedia.org/wiki/VGA_text_mode): vga text /// mode chars include two chars: char style (e.g., blink) & the actual utf char. pub struct VgatDisplayStyle { blinking: bool, bg_color: Color, fg_color: Color, } impl Default for VgatDisplayStyle { fn default() -> Self { Self { blinking: false, bg_color: Color::Black, fg_color: Color::White, } } } impl Into<u8> for &VgatDisplayStyle { fn into(self) -> u8 { (self.blinking as u8) << 7 | (self.bg_color as u8) << 4 | self.fg_color as u8 } } // Non-copying conversion impl Into<u8> for VgatDisplayStyle { fn into(self) -> u8 { (self.blinking as u8) << 7 | (self.bg_color as u8) << 4 | self.fg_color as u8 } } /// A character displayed via the vga text mode driver with: /// - a UTF-8 char being displayed /// - a blinking status (0 | 1) /// - a background color OR a foreground color #[repr(C)] pub struct VgatChar { value: u8, style: u8, } impl VgatChar { pub fn new(value: u8, style: VgatDisplayStyle) -> Self { Self { value: value, style: style.into(), } } } impl From<char> for VgatChar { fn from(c: char) -> Self { Self::new(c as u8, VgatDisplayStyle::default()) } } #[repr(transparent)] pub struct VgatBuffer<const W: usize, const H: usize> { buff: [[VgatChar; W]; H], } /// An output that implements a byte-sink writer for the vga text mode out. pub struct VgatOut<'a, const W: usize, const H: usize> { // The resolution of the screen in terms of chars displayable char_buffer: &'a mut VgatBuffer<W, H>, // The index of the next position in which a char can be inserted head_pos: (usize, usize), // ANSI contexts are preserved from line to line color_state: VgatDisplayStyle, } /// Obtain a safe, bounds-checked slice of framebuffer slots from an unsafe, /// raw pointer provided by the developer (namely, vgat_buff_start). /// Dimensions are indicated by the associated W and H constants, also /// (optionally) provided by the developer (see provided Default implementation). impl<'a, const W: usize, const H: usize> VgatOut<'a, W, H> { pub unsafe fn new(vgat_buff_start: *mut VgatBuffer<W, H>) -> Self { Self { char_buffer: &mut *vgat_buff_start, head_pos: (0, 0), color_state: VgatDisplayStyle::default(), } } /// Writes a VGA char to the screen. pub fn write_char(&mut self, c: VgatChar) { self.char_buffer.buff[self.head_pos.0][self.head_pos.1] = c.into(); self.head_pos.1 += 1; if self.head_pos.1 >= W { self.advance_print_feed(); } } /// Moves the vga writer to the next print line. fn advance_print_feed(&mut self) { self.head_pos.1 = 0; self.head_pos.0 = (self.head_pos.0 + 1) % H; } /// Adopts the context specified in the given ANSI string. Returns the number /// of characters that were found to be part of the ANSI context escape sequence. fn adopt_ansi(&mut self, s: &str) -> u8 { let mut i = 0; let mut bold = false; for (i, c) in s.chars().enumerate() { match (i, c) { (0, '\\') | (1, 'x') | (2, '1') | (3, 'b') | (4, '[') => (), (5, n) => { match n { '0' => self.color_state = VgatDisplayStyle::default(), '1' => { self.color_state.fg_color = self.color_state.fg_color.bold_variant(); bold = true; } '2' => { self.color_state.fg_color = self.color_state.fg_color.dim_variant(); bold = false; } _ => (), }; } (6, ';') => (), (6, 'm') => break, (7, '0') => { self.color_state.fg_color = VgatDisplayStyle::default().fg_color; } (7, '3') => (), (8, ';') => (), (8, n) => { self.color_state.fg_color = Color::from_ansi_code(n); if bold { self.color_state.fg_color = self.color_state.fg_color.bold_variant(); } } (9, 'm') => break, (9, ';') => (), (10, '0') => { self.color_state.bg_color = VgatDisplayStyle::default().bg_color; } (10, '4') => (), (11, n) => { self.color_state.bg_color = Color::from_ansi_code(n); if bold { self.color_state.bg_color = self.color_state.bg_color.bold_variant(); } } _ => break, }; } i } } impl VgatOut<'static, DEFAULT_VGA_TEXT_BUFF_WIDTH, DEFAULT_VGA_TEXT_BUFF_HEIGHT> { const fn default() -> Self { unsafe { Self { } } } } /// If the user doesn't provide a specific framebuffer, use the default one, /// which has a static context. impl Default for VgatOut<'static, DEFAULT_VGA_TEXT_BUFF_WIDTH, DEFAULT_VGA_TEXT_BUFF_HEIGHT> { fn default() -> Self { Self::default() } } impl<'a, const W: usize, const H: usize> Write for VgatOut<'a, W, H> { fn write_str(&mut self, s: &str) -> fmt::Result { let mut skipped_ansi_chars = 0; for (i, c) in s.chars().enumerate() { if skipped_ansi_chars > 0 { skipped_ansi_chars -= 1; } if skipped_ansi_chars == 0 { if c == '\\' { skipped_ansi_chars = self.adopt_ansi(&s[i..]); } else if c == '\n' { self.advance_print_feed(); } else { self.write_char(VgatChar { value: c as u8, style: (&self.color_state).into(), }); } } } Ok(()) } }
#![feature(test)] use fraction::Fraction; use projecteuler::fraction; use projecteuler::helper; fn main() { dbg!(solve(8)); dbg!(solve(1_000_000)); helper::time_it( || { core::hint::black_box(solve(1_000_000)); }, 100, ); } fn solve(d: usize) -> Fraction<usize> { let mut low = Fraction::new(0, 1); let high = Fraction::new(3, 7); for i in 3..=d { //dbg!(i); //dbg!(low); /* low < a/i a > low*i a/i < high a < high*i */ let max = Fraction::new(high.num() * i, high.den()); //dbg!(max); let a = max.ceil() - 1; let new_low = Fraction::new(a, i); //dbg!(new_low); if new_low > low { low = new_low; } } low }
use super::super::generator::MazeGenerator; use super::super::grid::{Grid, BasicGrid}; use super::super::Tile; pub fn test_gen<T: MazeGenerator>(width: usize, height: usize) { let mut test_grid = BasicGrid::new(width, height); T::generate(&mut test_grid); for j in 0..height { for i in 0..width { let tile = test_grid .get_tile_data((i, j)) .expect("Failed to get tile data"); assert!(tile != Tile::new() || (width <= 1 && height <= 1), "A tile in the maze is not connected"); } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} pub type ActivationSignalDetectionConfiguration = *mut ::core::ffi::c_void; pub type ActivationSignalDetectionConfigurationCreationResult = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ActivationSignalDetectionConfigurationCreationStatus(pub i32); impl ActivationSignalDetectionConfigurationCreationStatus { pub const Success: Self = Self(0i32); pub const SignalIdNotAvailable: Self = Self(1i32); pub const ModelIdNotSupported: Self = Self(2i32); pub const InvalidSignalId: Self = Self(3i32); pub const InvalidModelId: Self = Self(4i32); pub const InvalidDisplayName: Self = Self(5i32); pub const ConfigurationAlreadyExists: Self = Self(6i32); pub const CreationNotSupported: Self = Self(7i32); } impl ::core::marker::Copy for ActivationSignalDetectionConfigurationCreationStatus {} impl ::core::clone::Clone for ActivationSignalDetectionConfigurationCreationStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ActivationSignalDetectionConfigurationRemovalResult(pub i32); impl ActivationSignalDetectionConfigurationRemovalResult { pub const Success: Self = Self(0i32); pub const NotFound: Self = Self(1i32); pub const CurrentlyEnabled: Self = Self(2i32); pub const RemovalNotSupported: Self = Self(3i32); } impl ::core::marker::Copy for ActivationSignalDetectionConfigurationRemovalResult {} impl ::core::clone::Clone for ActivationSignalDetectionConfigurationRemovalResult { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ActivationSignalDetectionConfigurationSetModelDataResult(pub i32); impl ActivationSignalDetectionConfigurationSetModelDataResult { pub const Success: Self = Self(0i32); pub const EmptyModelData: Self = Self(1i32); pub const UnsupportedFormat: Self = Self(2i32); pub const ConfigurationCurrentlyEnabled: Self = Self(3i32); pub const InvalidData: Self = Self(4i32); pub const SetModelDataNotSupported: Self = Self(5i32); pub const ConfigurationNotFound: Self = Self(6i32); pub const UnknownError: Self = Self(7i32); } impl ::core::marker::Copy for ActivationSignalDetectionConfigurationSetModelDataResult {} impl ::core::clone::Clone for ActivationSignalDetectionConfigurationSetModelDataResult { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ActivationSignalDetectionConfigurationStateChangeResult(pub i32); impl ActivationSignalDetectionConfigurationStateChangeResult { pub const Success: Self = Self(0i32); pub const NoModelData: Self = Self(1i32); pub const ConfigurationNotFound: Self = Self(2i32); } impl ::core::marker::Copy for ActivationSignalDetectionConfigurationStateChangeResult {} impl ::core::clone::Clone for ActivationSignalDetectionConfigurationStateChangeResult { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ActivationSignalDetectionTrainingDataFormat(pub i32); impl ActivationSignalDetectionTrainingDataFormat { pub const Voice8kHz8BitMono: Self = Self(0i32); pub const Voice8kHz16BitMono: Self = Self(1i32); pub const Voice16kHz8BitMono: Self = Self(2i32); pub const Voice16kHz16BitMono: Self = Self(3i32); pub const VoiceOEMDefined: Self = Self(4i32); pub const Audio44kHz8BitMono: Self = Self(5i32); pub const Audio44kHz16BitMono: Self = Self(6i32); pub const Audio48kHz8BitMono: Self = Self(7i32); pub const Audio48kHz16BitMono: Self = Self(8i32); pub const AudioOEMDefined: Self = Self(9i32); pub const OtherOEMDefined: Self = Self(10i32); } impl ::core::marker::Copy for ActivationSignalDetectionTrainingDataFormat {} impl ::core::clone::Clone for ActivationSignalDetectionTrainingDataFormat { fn clone(&self) -> Self { *self } } pub type ActivationSignalDetector = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ActivationSignalDetectorKind(pub i32); impl ActivationSignalDetectorKind { pub const AudioPattern: Self = Self(0i32); pub const AudioImpulse: Self = Self(1i32); pub const HardwareEvent: Self = Self(2i32); } impl ::core::marker::Copy for ActivationSignalDetectorKind {} impl ::core::clone::Clone for ActivationSignalDetectorKind { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ActivationSignalDetectorPowerState(pub i32); impl ActivationSignalDetectorPowerState { pub const HighPower: Self = Self(0i32); pub const ConnectedLowPower: Self = Self(1i32); pub const DisconnectedLowPower: Self = Self(2i32); } impl ::core::marker::Copy for ActivationSignalDetectorPowerState {} impl ::core::clone::Clone for ActivationSignalDetectorPowerState { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ConversationalAgentActivationKind(pub i32); impl ConversationalAgentActivationKind { pub const VoiceActivationPreview: Self = Self(0i32); pub const Foreground: Self = Self(1i32); } impl ::core::marker::Copy for ConversationalAgentActivationKind {} impl ::core::clone::Clone for ConversationalAgentActivationKind { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ConversationalAgentActivationResult(pub i32); impl ConversationalAgentActivationResult { pub const Success: Self = Self(0i32); pub const AgentInactive: Self = Self(1i32); pub const ScreenNotAvailable: Self = Self(2i32); pub const AgentInterrupted: Self = Self(3i32); } impl ::core::marker::Copy for ConversationalAgentActivationResult {} impl ::core::clone::Clone for ConversationalAgentActivationResult { fn clone(&self) -> Self { *self } } pub type ConversationalAgentDetectorManager = *mut ::core::ffi::c_void; pub type ConversationalAgentSession = *mut ::core::ffi::c_void; pub type ConversationalAgentSessionInterruptedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ConversationalAgentSessionUpdateResponse(pub i32); impl ConversationalAgentSessionUpdateResponse { pub const Success: Self = Self(0i32); pub const Failed: Self = Self(1i32); } impl ::core::marker::Copy for ConversationalAgentSessionUpdateResponse {} impl ::core::clone::Clone for ConversationalAgentSessionUpdateResponse { fn clone(&self) -> Self { *self } } pub type ConversationalAgentSignal = *mut ::core::ffi::c_void; pub type ConversationalAgentSignalDetectedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ConversationalAgentState(pub i32); impl ConversationalAgentState { pub const Inactive: Self = Self(0i32); pub const Detecting: Self = Self(1i32); pub const Listening: Self = Self(2i32); pub const Working: Self = Self(3i32); pub const Speaking: Self = Self(4i32); pub const ListeningAndSpeaking: Self = Self(5i32); } impl ::core::marker::Copy for ConversationalAgentState {} impl ::core::clone::Clone for ConversationalAgentState { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct ConversationalAgentSystemStateChangeType(pub i32); impl ConversationalAgentSystemStateChangeType { pub const UserAuthentication: Self = Self(0i32); pub const ScreenAvailability: Self = Self(1i32); pub const IndicatorLightAvailability: Self = Self(2i32); pub const VoiceActivationAvailability: Self = Self(3i32); } impl ::core::marker::Copy for ConversationalAgentSystemStateChangeType {} impl ::core::clone::Clone for ConversationalAgentSystemStateChangeType { fn clone(&self) -> Self { *self } } pub type ConversationalAgentSystemStateChangedEventArgs = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct ConversationalAgentVoiceActivationPrerequisiteKind(pub i32); impl ConversationalAgentVoiceActivationPrerequisiteKind { pub const MicrophonePermission: Self = Self(0i32); pub const KnownAgents: Self = Self(1i32); pub const AgentAllowed: Self = Self(2i32); pub const AppCapability: Self = Self(3i32); pub const BackgroundTaskRegistration: Self = Self(4i32); pub const PolicyPermission: Self = Self(5i32); } impl ::core::marker::Copy for ConversationalAgentVoiceActivationPrerequisiteKind {} impl ::core::clone::Clone for ConversationalAgentVoiceActivationPrerequisiteKind { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct DetectionConfigurationAvailabilityChangeKind(pub i32); impl DetectionConfigurationAvailabilityChangeKind { pub const SystemResourceAccess: Self = Self(0i32); pub const Permission: Self = Self(1i32); pub const LockScreenPermission: Self = Self(2i32); } impl ::core::marker::Copy for DetectionConfigurationAvailabilityChangeKind {} impl ::core::clone::Clone for DetectionConfigurationAvailabilityChangeKind { fn clone(&self) -> Self { *self } } pub type DetectionConfigurationAvailabilityChangedEventArgs = *mut ::core::ffi::c_void; pub type DetectionConfigurationAvailabilityInfo = *mut ::core::ffi::c_void; #[repr(transparent)] pub struct DetectionConfigurationTrainingStatus(pub i32); impl DetectionConfigurationTrainingStatus { pub const Success: Self = Self(0i32); pub const FormatNotSupported: Self = Self(1i32); pub const VoiceTooQuiet: Self = Self(2i32); pub const VoiceTooLoud: Self = Self(3i32); pub const VoiceTooFast: Self = Self(4i32); pub const VoiceTooSlow: Self = Self(5i32); pub const VoiceQualityProblem: Self = Self(6i32); pub const TrainingSystemInternalError: Self = Self(7i32); pub const TrainingTimedOut: Self = Self(8i32); pub const ConfigurationNotFound: Self = Self(9i32); } impl ::core::marker::Copy for DetectionConfigurationTrainingStatus {} impl ::core::clone::Clone for DetectionConfigurationTrainingStatus { fn clone(&self) -> Self { *self } } #[repr(transparent)] pub struct SignalDetectorResourceKind(pub i32); impl SignalDetectorResourceKind { pub const ParallelModelSupport: Self = Self(0i32); pub const ParallelModelSupportForAgent: Self = Self(1i32); pub const ParallelSignalSupport: Self = Self(2i32); pub const ParallelSignalSupportForAgent: Self = Self(3i32); pub const DisplayOffSupport: Self = Self(4i32); pub const PluggedInPower: Self = Self(5i32); pub const Detector: Self = Self(6i32); pub const SupportedSleepState: Self = Self(7i32); pub const SupportedBatterySaverState: Self = Self(8i32); pub const ScreenAvailability: Self = Self(9i32); pub const InputHardware: Self = Self(10i32); pub const AcousticEchoCancellation: Self = Self(11i32); pub const ModelIdSupport: Self = Self(12i32); pub const DataChannel: Self = Self(13i32); } impl ::core::marker::Copy for SignalDetectorResourceKind {} impl ::core::clone::Clone for SignalDetectorResourceKind { fn clone(&self) -> Self { *self } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" {} #[repr(transparent)] pub struct ApplicationProfileModes(pub u32); impl ApplicationProfileModes { pub const Default: Self = Self(0u32); pub const Alternate: Self = Self(1u32); } impl ::core::marker::Copy for ApplicationProfileModes {} impl ::core::clone::Clone for ApplicationProfileModes { fn clone(&self) -> Self { *self } }
extern crate log; use clap::{crate_version, App, Arg, ArgMatches}; use std::time::Duration; use unmoved_mover::daemon; fn get_arg_key(matches: &ArgMatches, name: &str) -> String { let key: String = matches .value_of(name) .expect(&*format!("Invalid {name}", name = name)) .to_string(); return key; } fn main() { env_logger::init(); let matches = App::new("unmoved-mover") .version(crate_version!()) .about("TODO") .arg( Arg::with_name("mod-key") .long("mod-key") .default_value("Mod1") // code: 64 .takes_value(true) .required(true), ) .arg( Arg::with_name("up-key") .long("up-key") .default_value("i") // code: 31 .takes_value(true) .required(true), ) .arg( Arg::with_name("down-key") .long("down-key") .default_value("k") // code: 44 .takes_value(true) .required(true), ) .arg( Arg::with_name("left-key") .long("left-key") .default_value("j") // code: 45 .takes_value(true) .required(true), ) .arg( Arg::with_name("right-key") .long("right-key") .default_value("l") // code: 46 .takes_value(true) .required(true), ) .arg( Arg::with_name("left-click-key") .long("left-click-key") .default_value("semicolon") // code 47 .takes_value(true) .required(true), ) .arg( Arg::with_name("right-click-key") .long("right-click-key") .default_value("apostrophe") // code: 48 .takes_value(true) .required(true), ) .arg( Arg::with_name("tick-interval-ms") .long("tick-interval-ms") .default_value("10") .takes_value(true) .required(true), ) .arg( Arg::with_name("velocity-px-per-s") .long("velocity-px-per-s") .default_value("500") .takes_value(true) .required(true), ) .get_matches(); let mod_key = get_arg_key(&matches, "mod-key"); let left_key = get_arg_key(&matches, "left-key"); let right_key = get_arg_key(&matches, "right-key"); let up_key = get_arg_key(&matches, "up-key"); let down_key = get_arg_key(&matches, "down-key"); let left_click_key = get_arg_key(&matches, "left-click-key"); let right_click_key = get_arg_key(&matches, "right-click-key"); let tick_interval = matches .value_of("tick-interval-ms") .and_then(|x| x.parse::<u64>().ok()) .map(|x| Duration::from_millis(x)) .expect("Invalid tick-interval-ms"); let velocity_px_per_s = matches .value_of("velocity-px-per-s") .and_then(|x| x.parse::<u32>().ok()) .expect("Invalid velocity-px-per-s"); let config = daemon::Config { mod_key, left_key, right_key, up_key, down_key, left_click_key, right_click_key, tick_interval: tick_interval, velocity_px_per_s: velocity_px_per_s, }; daemon::run(&config).expect("Unable to start daemon"); }
#[macro_use] extern crate horrorshow; extern crate hyper; extern crate iron; extern crate mount; extern crate staticfile; use horrorshow::prelude::*; use iron::headers::ContentType; use iron::modifiers::Header; use iron::prelude::*; use iron::status; use mount::Mount; use staticfile::Static; use std::path::Path; fn main() { let mut mount = Mount::new(); mount.mount("/", Static::new(Path::new("target/static/index.html"))); Iron::new(mount).http("localhost:3000").unwrap(); println!("On 3000"); }
mod entry; use crate::entry::{*, Error, print_entries}; use std::{io::{stdout, Write}, iter::{Cycle, Enumerate}, thread::sleep, time::Duration}; use rand::Rng; use clap::{App, load_yaml}; use crossterm::{cursor::{Hide, Show}, execute, style::Color}; const COLORS: [Color; 8] = [Color::Blue, Color::Red, Color::Cyan, Color::Grey, Color::Green, Color::White, Color::Yellow, Color::Magenta]; const QUICK_MOTION_NS: u64 = 50_000_000; const SLOW_MOTION_NS: u64 = 100_000_000; const ULTRA_SLOW_MOTION_NS: u64 = 250_000_000; macro_rules! spin_for { ( $total_time_ns:expr, $spin_duration_ns:expr, $ratio:expr, $callback:expr ) => { { let num_spins = $total_time_ns / ($ratio * $spin_duration_ns); let sleep_duration = Duration::new(0, $spin_duration_ns as u32); for _ in 0..num_spins { sleep(sleep_duration); $callback; } } }; ( $num_spins:expr, $spin_duration_ns:expr, $callback:expr ) => { { let sleep_duration = Duration::new(0, $spin_duration_ns as u32); for _ in 0..$num_spins { sleep(sleep_duration); $callback; } } }; } fn prev_cycle(it: &mut Cycle::<Enumerate::<std::slice::Iter<Entry>>>, entries: &Vec<Entry>) { for _ in 0.. entries.len()-1 { it.next(); } } fn select_entry(it: &mut Cycle::<Enumerate::<std::slice::Iter<Entry>>>, entries: &Vec::<Entry>) -> Result<()> { prev_cycle(it, entries); match it.next() { Some((i, e)) => {print_clear_entry(e, i, entries.len()).map_err(|_| Error::Display)?; Ok(())}, None => Err(Error::Logic), }?; match it.next() { Some((i, e)) => {print_selected_entry(&e, i, entries.len()).map_err(|_| Error::Display)?; Ok(())}, None => Err(Error::Logic), }?; Ok(()) } fn create_entries(args: Vec<String>) -> Vec<Entry> { // Assign a color to each entry let mut color = COLORS.iter().cycle(); return args.iter().map(|x| Entry::new(x.clone(), color.next().unwrap().clone()) ).collect(); } struct CursorVisibility {} impl CursorVisibility { fn new() -> CursorVisibility { match execute!(stdout(), Hide) { Ok(()) => (), Err(_) => println!("Failed to hide cursor"), }; return CursorVisibility{}; } } impl Drop for CursorVisibility { fn drop(&mut self) { match execute!(stdout(), Show) { Ok(()) => (), Err(_) => println!("Failed to set cursor back"), }; } } fn get_args() -> Result<(u64, Vec<String>)> { let yaml = load_yaml!("cli.yaml"); let matches = App::from(yaml).get_matches(); let args_input : Vec<String> = match matches.values_of_t("ENTRIES") { Ok(inputs) => Ok(inputs), Err(_) => Err(Error::Args) }?; let total_time_sec : u64 = match matches.value_of("spin-time") { Some(time) => Ok(time.parse::<u64>().unwrap_or(6)), None => Err(Error::Args), }?; return Ok((total_time_sec, args_input)); } fn main() -> Result<()> { let (total_time_sec, args_input) = get_args()?; let entries = create_entries(args_input); let total_time_ns : u64 = total_time_sec * 1_000_000_000; let mut selected_entry_it = entries.iter().enumerate().cycle(); let mut rng = rand::thread_rng(); let _cursor = CursorVisibility::new(); print_entries(&entries)?; let winner : u64 = rng.gen_range(0..entries.len()) as u64; spin_for!(total_time_ns, QUICK_MOTION_NS, 2, select_entry(&mut selected_entry_it, &entries)?); spin_for!(total_time_ns, SLOW_MOTION_NS, 4, select_entry(&mut selected_entry_it, &entries)?); spin_for!(total_time_ns, ULTRA_SLOW_MOTION_NS, 4, select_entry(&mut selected_entry_it, &entries)?); spin_for!(winner, ULTRA_SLOW_MOTION_NS, select_entry(&mut selected_entry_it, &entries)?); Ok(()) }
use maud::{html, Markup}; use crate::models::shop::Shop; use crate::views; pub fn list(entries:Vec<(String, Shop)>) -> Markup { let content = html! { div class="row" { div class="col s12 l6" { div class="card" { div class="card-image" { a href="/shops/0" class="btn-floating halfway-fab blue darken-3" { i class="material-icons" {"add"} } } div class="card-content" { ul class="collection with-header" { li class="collection-header" { h4 {"Liste des magasins"} } @for entry in entries { li class="collection-item" { div { (entry.1.name) a href={"/shops/"(entry.0)} class="secondary-content" { i class="material-icons" {"edit"} } } }} } } } } } }; views::main::page(content) } pub fn detail(id:String, shop:Shop, title:&str, route:&str) -> Markup { let form = views::main::item_detail(&id, &shop, title, route); views::main::page(form) }
#![allow(unused_imports)] #![allow(dead_code)] #![allow(non_snake_case)] use std::fs; use std::process; use std::env; use std::path::PathBuf; use anyhow::Result; use serde_json; use super::system::*; impl System { // pub fn Make() -> System { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/21 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/system_test.rs#L69 complexity : difficult stage : mid */ Self::new() } // pub fn MakePersistant() -> System { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/12 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/system_test.rs#L96 complexity : easy stage : mid */ let sys = Self::new(); sys.store(); sys } // pub fn StorePathDefault() -> PathBuf { PathBuf::new() /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/16 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/system_test.rs#L124 complexity : mid stage : early */ } // pub fn Load() -> Result< System > { let path = Self::StorePathDefault(); Self::LoadFromFile( &path ) } // pub fn LoadFromFile( _path : &PathBuf ) -> Result< System > { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/13 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/system_test.rs#L191 complexity : mid stage : mid */ Ok( System::new() ) } // pub fn store( &self ) { self.store_to( &self.store_path ); } // pub fn store_to( &self, _path : &PathBuf ) { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/11 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/system_test.rs#L256 complexity : mid stage : mid */ } }
use crate::lib::{default_sub_command, file_to_string, Command}; use anyhow::Error; use clap::{value_t_or_exit, App, Arg, ArgMatches, SubCommand}; use nom::{ branch::alt, bytes::complete::{tag, take, take_till1, take_until}, combinator::{map, map_parser}, multi::{fold_many1, separated_list0, separated_list1}, }; use simple_error::SimpleError; use std::collections::HashSet; use strum::VariantNames; use strum_macros::{EnumString, EnumVariantNames}; pub const CUSTOM_CUSTOMS: Command = Command::new(sub_command, "custom-customs", run); #[derive(Debug)] struct CustomCustomsArgs { file: String, strategy: CustomsCountStrategy, } #[derive(Debug, EnumString, EnumVariantNames)] #[strum(serialize_all = "kebab_case")] enum CustomsCountStrategy { CountUniquePerGroup, CountIntersectionPerGroup, } fn sub_command() -> App<'static, 'static> { default_sub_command(&CUSTOM_CUSTOMS, "Takes a file with customs questions groups and cacluates the sum of unique per group questions", "Path to the input file. Groups are separated by a blank line, people within a group are \ separated by a newline.") .arg( Arg::with_name("strategy") .short("s") .help("Counting strategy for each group. The strategies are as follows:\n\n\ count-unique-per-group: Counts the number of unqiue anwers within a group\n\n\ count-intersection-per-group: Count the number of questions that all members \ of a group answered.\n") .takes_value(true) .possible_values(&CustomsCountStrategy::VARIANTS) .required(true), ) .subcommand( SubCommand::with_name("part1") .about("Finds the sum of unique group answers with the default input") .version("1.0.0"), ) .subcommand( SubCommand::with_name("part2") .about("Finds the sum of answers all group members completed with the default input") .version("1.0.0"), ) } fn run(arguments: &ArgMatches) -> Result<(), Error> { let custom_customs_arguments = match arguments.subcommand_name() { Some("part1") => CustomCustomsArgs { file: "day6/input.txt".to_string(), strategy: CustomsCountStrategy::CountUniquePerGroup, }, Some("part2") => CustomCustomsArgs { file: "day6/input.txt".to_string(), strategy: CustomsCountStrategy::CountIntersectionPerGroup, }, _ => CustomCustomsArgs { file: value_t_or_exit!(arguments.value_of("file"), String), strategy: value_t_or_exit!(arguments.value_of("strategy"), CustomsCountStrategy), }, }; process_customs_forms(&custom_customs_arguments) .map(|result| { println!("{:#?}", result); }) .map(|_| ()) } fn process_customs_forms(custom_customs_arguments: &CustomCustomsArgs) -> Result<usize, Error> { file_to_string(&custom_customs_arguments.file) .and_then(|file| parse_customs_forms(&file)) .map(|customs_forms| match custom_customs_arguments.strategy { CustomsCountStrategy::CountUniquePerGroup => { count_unique_answers_per_group(customs_forms) } CustomsCountStrategy::CountIntersectionPerGroup => { count_answers_all_group_members_answered(customs_forms) } }) } fn count_unique_answers_per_group(customs_forms: Vec<Vec<HashSet<char>>>) -> usize { customs_forms .into_iter() .map(|group| { group .into_iter() .fold(HashSet::new(), |mut acc: HashSet<char>, person| { acc.extend(&person); acc }) .len() }) .fold(0, |acc, answers| acc + answers) } fn count_answers_all_group_members_answered(customs_forms: Vec<Vec<HashSet<char>>>) -> usize { customs_forms .into_iter() .map(|group| { group .into_iter() .fold_first(|acc: HashSet<char>, person| { acc.into_iter() .filter(|answer| person.contains(answer)) .collect() }) .map(|questions| questions.len()) .unwrap_or(0) }) .fold(0, |acc, answers| acc + answers) } fn parse_customs_forms(file: &String) -> Result<Vec<Vec<HashSet<char>>>, Error> { separated_list0( tag("\n\n"), map_parser( alt((take_until("\n\n"), take_till1(|_| false))), separated_list1( tag("\n"), map_parser( alt((take_until("\n"), take_till1(|_| false))), map( fold_many1(take(1usize), String::new(), |mut acc: String, item| { acc.push_str(item); acc }), |answers| { let mut unique_answers = HashSet::new(); answers.chars().for_each(|character| { unique_answers.insert(character); }); unique_answers }, ), ), ), ), )(file.as_str()) .map_err(|_: nom::Err<nom::error::Error<&str>>| SimpleError::new("Parse Error").into()) .map(|(_, custom_forms)| custom_forms) }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // 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 alloc::collections::btree_map::BTreeMap; use spin::Mutex; use super::super::super::qlib::linux_def::*; use super::super::super::qlib::range::*; pub struct Mapping { pub addr: u64, pub writeable: bool, } const CHUNK_SHIFT: u64 = MemoryDef::HUGE_PAGE_SHIFT; const CHUNK_SIZE: u64 = 1 << CHUNK_SHIFT; const CHUNK_MASK: u64 = CHUNK_SIZE - 1; fn PagesInChunk(mr: &Range, chunkStart: u64) -> i32 { return (mr.Intersect(&Range::New(chunkStart, CHUNK_SIZE)).Len() / MemoryDef::PAGE_SIZE) as i32 } pub struct HostFileMapper { pub refs: Mutex<BTreeMap<u64, i32>>, pub mappings: Mutex<BTreeMap<u64, Mapping>>, } impl HostFileMapper { pub fn New() -> Self { return Self { refs: Mutex::new(BTreeMap::new()), mappings: Mutex::new(BTreeMap::new()), } } } impl HostFileMapper { // IncRefOn increments the reference count on all offsets in mr. pub fn IncRefOn(&self, mr: &Range) { let mut refs = self.refs.lock(); let mut chunkStart = mr.Start() & !CHUNK_MASK; while chunkStart < mr.End() { let refcnt = match refs.get(&chunkStart) { None => 0, Some(v) => *v, }; let pgs = PagesInChunk(mr, chunkStart); if refcnt + pgs < refcnt { // Would overflow. panic!("HostFileMapper.IncRefOn({:?}): adding {} page references to chunk {:x}, which has {} page references", &mr, pgs, chunkStart, refcnt) } refs.insert(chunkStart, refcnt + pgs); chunkStart += CHUNK_SIZE; } } // DecRefOn decrements the reference count on all offsets in mr. /*pub fn DecRefOn(&self, mr: &Range) { let refs = self.refs.lock(); let mut chunkStart = mr.Start() & !CHUNK_MASK; } // MapInternal returns a mapping of offsets in fr from fd. The returned // safemem.BlockSeq is valid as long as at least one reference is held on all // offsets in fr or until the next call to UnmapAll. // // Preconditions: The caller must hold a reference on all offsets in fr. pub fn MapInternal(&self, mr: &Range, fd: i32, write: bool) -> Result<Vec<Range>> { return Err(Error::NoData) }*/ }
mod test_utils; use async_std::prelude::*; use async_std::sync; use async_std::task; use std::time::Duration; use tide::{JobContext, Request}; #[test] fn jobs() -> Result<(), http_types::Error> { #[derive(Default)] struct Counter { count: sync::Mutex<i32>, } task::block_on(async { let port = test_utils::find_port().await; let server = task::spawn(async move { let mut app = tide::with_state(Counter::default()); app.at("/").get(|req: Request<Counter>| async move { Ok(req.state().count.lock().await.to_string()) }); app.spawn(|ctx: JobContext<Counter>| async move { *ctx.state().count.lock().await += 1; }); app.listen(("localhost", port)).await?; Result::<(), http_types::Error>::Ok(()) }); let client = task::spawn(async move { task::sleep(Duration::from_millis(200)).await; let string = surf::get(format!("http://localhost:{}", port)) .recv_string() .await .unwrap(); assert_eq!(string, "1".to_string()); Ok(()) }); server.race(client).await }) }
mod battery; mod iterator; mod manager; mod state; mod technology; pub use self::battery::Battery; pub use self::iterator::Batteries; pub use self::manager::Manager; pub use self::state::State; pub use self::technology::Technology;
mod bar; mod canvas; mod color_button; mod note;
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const CDB_REPORT_BITS: u32 = 0u32; pub const CDB_REPORT_BYTES: u32 = 1u32; pub const COMDB_MAX_PORTS_ARBITRATED: u32 = 4096u32; pub const COMDB_MIN_PORTS_ARBITRATED: u32 = 256u32; #[inline] pub unsafe fn ComDBClaimNextFreePort<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>>(hcomdb: Param0, comnumber: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBClaimNextFreePort(hcomdb: HCOMDB, comnumber: *mut u32) -> i32; } ::core::mem::transmute(ComDBClaimNextFreePort(hcomdb.into_param().abi(), ::core::mem::transmute(comnumber))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn ComDBClaimPort<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(hcomdb: Param0, comnumber: u32, forceclaim: Param2, forced: *mut super::super::Foundation::BOOL) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBClaimPort(hcomdb: HCOMDB, comnumber: u32, forceclaim: super::super::Foundation::BOOL, forced: *mut super::super::Foundation::BOOL) -> i32; } ::core::mem::transmute(ComDBClaimPort(hcomdb.into_param().abi(), ::core::mem::transmute(comnumber), forceclaim.into_param().abi(), ::core::mem::transmute(forced))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ComDBClose<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>>(hcomdb: Param0) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBClose(hcomdb: HCOMDB) -> i32; } ::core::mem::transmute(ComDBClose(hcomdb.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ComDBGetCurrentPortUsage<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>>(hcomdb: Param0, buffer: *mut u8, buffersize: u32, reporttype: u32, maxportsreported: *mut u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBGetCurrentPortUsage(hcomdb: HCOMDB, buffer: *mut u8, buffersize: u32, reporttype: u32, maxportsreported: *mut u32) -> i32; } ::core::mem::transmute(ComDBGetCurrentPortUsage(hcomdb.into_param().abi(), ::core::mem::transmute(buffer), ::core::mem::transmute(buffersize), ::core::mem::transmute(reporttype), ::core::mem::transmute(maxportsreported))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ComDBOpen(phcomdb: *mut isize) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBOpen(phcomdb: *mut isize) -> i32; } ::core::mem::transmute(ComDBOpen(::core::mem::transmute(phcomdb))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ComDBReleasePort<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>>(hcomdb: Param0, comnumber: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBReleasePort(hcomdb: HCOMDB, comnumber: u32) -> i32; } ::core::mem::transmute(ComDBReleasePort(hcomdb.into_param().abi(), ::core::mem::transmute(comnumber))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn ComDBResizeDatabase<'a, Param0: ::windows::core::IntoParam<'a, HCOMDB>>(hcomdb: Param0, newsize: u32) -> i32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn ComDBResizeDatabase(hcomdb: HCOMDB, newsize: u32) -> i32; } ::core::mem::transmute(ComDBResizeDatabase(hcomdb.into_param().abi(), ::core::mem::transmute(newsize))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq)] #[repr(transparent)] pub struct HCOMDB(pub isize); impl ::core::default::Default for HCOMDB { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } unsafe impl ::windows::core::Handle for HCOMDB {} unsafe impl ::windows::core::Abi for HCOMDB { type Abi = Self; }
use crate::prelude::*; use std::os::raw::c_void; use std::ptr; #[repr(C)] #[derive(Debug)] pub struct VkWaylandSurfaceCreateInfoKHR { pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkWaylandSurfaceCreateFlagBitsKHR, pub display: *mut c_void, pub surface: *mut c_void, } impl VkWaylandSurfaceCreateInfoKHR { pub fn new<T, U, V>(flags: T, display: &mut U, surface: &mut V) -> Self where T: Into<VkWaylandSurfaceCreateFlagBitsKHR>, { VkWaylandSurfaceCreateInfoKHR { sType: VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR, pNext: ptr::null(), flags: flags.into(), display: display as *mut U as *mut c_void, surface: surface as *mut V as *mut c_void, } } }
use std::{ fs::{self, File, OpenOptions}, io::Write, path::{Path, PathBuf}, }; use rand::{thread_rng, Rng}; use tempfile::TempDir; pub struct TestDir(TempDir); const RAND_BYTES: usize = 512; impl TestDir { pub fn new() -> TestDir { let tempdir = tempfile::Builder::new() .prefix(env!("CARGO_PKG_NAME")) .tempdir() .expect("Failed to create tempdir for the test dir"); TestDir(tempdir) } pub fn close(self) { self.0 .close() .unwrap_or_else(|_| panic!("Failed to close test dir")) } pub fn path(&self) -> &Path { self.0.path() } /// Return a path joined to the path to this directory. pub fn join<P: AsRef<Path>>(&self, path: P) -> PathBuf { self.path().join(path) } /// Return a path joined to the path to this directory. Panics if it is already there pub fn join_check<P: AsRef<Path>>(&self, path: P) -> PathBuf { let path = path.as_ref(); if !path.starts_with(self.path()) { self.path().join(path) } else { panic!( "The path {} cannot be join to the tempdir with path {}", path.display(), self.path().display() ); } } /// Create a directory at the given path, while creating all intermediate /// directories as needed. pub fn mkdirp<P: AsRef<Path>>(&self, path: P) { let path = path.as_ref(); fs::create_dir_all(&path) .map_err(|e| err!("failed to create directory {}: {}", path.display(), e)) .unwrap(); } /// Create an empty file at the given path. All ancestor directories must /// already exists. pub fn touch<P: AsRef<Path>>(&self, path: P) { as_ref_all!(path); File::create(&path) .map_err(|e| err!("failed to create file {}: {}", path.display(), e)) .unwrap(); } /// Create empty files at the given paths. All ancestor directories must /// already exists. pub fn touch_all<P: AsRef<Path>>(&self, paths: &[P]) { for p in paths { self.touch(p); } } pub fn touch_with_contents<P: AsRef<Path>>(&self, path: P) { as_ref_all!(path); let mut open_opt = OpenOptions::new(); open_opt.create_new(true).write(true); let mut file = open_opt .open(&path) .map_err(|e| err!("failed to create file {}: {}", path.display(), e)) .unwrap(); file.write_all(&random_bytes()) .expect("Failed to write random bytes to the file"); file.sync_all() .expect("Failed to sync file before dropping"); } /// Create empty files at the given paths. All ancestor directories must /// already exists. pub fn touch_all_with_contents<P: AsRef<Path>>(&self, paths: &[P]) { for p in paths { self.touch_with_contents(p); } } } /// returns an array of random bytes fn random_bytes() -> [u8; RAND_BYTES] { let mut rng = thread_rng(); let mut buf = [0u8; RAND_BYTES]; rng.fill(&mut buf); buf }
use std::collections::hash_map::RandomState; use std::collections::HashMap; use std::hash::{BuildHasher, Hash}; use bumpalo::Bump; use crate::util::{GridDomain, IndexDomain}; use crate::{Cell, Owner, SearchNode}; use super::NodePool; pub struct HashPool<V, S = RandomState> { map: Cell<HashMap<V, *const Cell<SearchNode<V>>, S>>, arena: Bump, } // require V: Copy so that we don't have any drop glue, otherwise we might leak memory. impl<V: Hash + Eq + Copy, S: BuildHasher> NodePool<V> for HashPool<V, S> { fn reset(&mut self, owner: &mut Owner) { owner.rw(&self.map).clear(); self.arena.reset(); } fn generate(&self, id: V, owner: &mut Owner) -> &Cell<SearchNode<V>> { let map = owner.rw(&self.map); let &mut node_ptr = map.entry(id).or_insert_with(|| { self.arena.alloc(Cell::new(SearchNode { search_num: 0, pqueue_location: 0, expansions: 0, id, parent: None, g: f64::INFINITY, lb: f64::INFINITY, })) }); unsafe { // SAFETY: The pointer points into our arena. The pointer can only dangle if the arena // is reset, which requires a mutable reference to self. This means that, since // we return data living as long as &self, any references must be gone when this // happens. Additionally, the pointers in this map cannot be stale as the map is // emptied whenever the arena is reset. &*node_ptr } } } impl<V, S> HashPool<V, S> { pub fn with_hasher(hash_builder: S) -> Self { HashPool { map: Cell::new(HashMap::with_hasher(hash_builder)), arena: Bump::new(), } } pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> Self { HashPool { map: Cell::new(HashMap::with_capacity_and_hasher(capacity, hash_builder)), arena: Bump::with_capacity(capacity * std::mem::size_of::<Cell<SearchNode<V>>>()), } } } impl<V> HashPool<V, RandomState> { pub fn new() -> Self { Default::default() } pub fn with_capacity(capacity: usize) -> Self { Self::with_capacity_and_hasher(capacity, Default::default()) } } impl<V, S: Default> Default for HashPool<V, S> { fn default() -> Self { HashPool { map: Cell::new(HashMap::default()), arena: Bump::new(), } } } // SAFETY: the pointers we hold that prevent this type from auto-implementing Send are basically // just self-references, so we don't care what thread we're on. unsafe impl<V: Send, S: Send> Send for HashPool<V, S> {} // SAFETY: all ids are in-bounds, so obviously the required invariant holds. unsafe impl<S> GridDomain for HashPool<(i32, i32), S> { fn width(&self) -> i32 { i32::MAX } fn height(&self) -> i32 { i32::MAX } } // SAFETY: all ids are in-bounds, so obviously the required invariant holds. unsafe impl<S> IndexDomain for HashPool<usize, S> { fn len(&self) -> usize { usize::MAX } }
/* * Christopher Piraino * * An implementation of the Fibonacci Heap * for use in network algorithms. */ extern crate collections = "collections#0.11-pre"; use collections::dlist::DList; use collections::deque::Deque; use std::option::Option; use std::cast; pub type FibEntry<K,V> = *mut FibNode<K,V>; trait HeapEntry<K, V> { fn key(&self) -> K; fn value(&self) -> V; fn mark(&self) -> bool; fn parent(&self) -> Option<Self>; fn rank(&self) -> uint; fn link(&self, child: Self); } #[deriving(Clone)] struct FibNode<K, V> { parent: Option<FibEntry<K,V>>, children: DList<FibEntry<K,V>>, marked: bool, key: K, value: V } pub struct FHeap<K, V> { // Minimum node is the first node in the first tree. trees: DList<FibEntry<K, V>> } // Private Methods on FibEntry. impl<K: std::fmt::Show+Eq+Clone, V: Clone> HeapEntry<K,V> for FibEntry<K,V> { fn key(&self) -> K { unsafe { (**self).key.clone() } } fn value(&self) -> V { unsafe { (**self).value.clone() } } fn mark(&self) -> bool { unsafe { (**self).marked } } fn parent(&self) -> Option<FibEntry<K,V>> { unsafe { (**self).parent.clone() } } fn rank(&self) -> uint { unsafe { (**self).rank() } } fn link(&self, child: FibEntry<K,V>) { unsafe { (*child).marked = false; (*child).parent = Some(*self); (**self).children.push_back(child); } } } // Private Methods on Node values. impl<K: std::fmt::Show+Eq+Clone ,V: Clone> FibNode<K,V> { fn remove_child(&mut self, key: K) { for _ in range(0, self.children.len()) { print!("Child key: {}\n", self.children.front().unwrap().key()); if self.children.front().unwrap().key().eq(&key) { self.children.pop_front(); return; } self.children.rotate_backward(); } fail!("Failed to remove child with key: {}\n", key); } fn rank(&self) -> uint { self.children.len() } } // Private methods on FHeap. impl<K: std::fmt::Show+Eq+Clone,V: Clone> FHeap<K,V> { fn remove_child(&mut self, node: FibEntry<K,V>, key: K) { print!("FHeap.remove_child({}, {})\n", node, key); unsafe { (*node).remove_child(key); } if node.parent().is_some() { if node.mark() { print!("start cascading cut\n"); self.cascading_cut(node); } else { print!("first removed node, mark node\n"); unsafe { (*node).marked = true; } } } } fn cascading_cut(&mut self, node: FibEntry<K,V>) { self.remove_child(node.parent().unwrap(), node.key()); self.trees.push_back(node) } fn same_rank(&mut self) -> Option<(FibEntry<K,V>, FibEntry<K,V>)> { // Only a single tree, no linking step. if self.trees.len() == 1 { return None; } print!("Looking for roots of same rank\n"); let mut same = false; for i in range(0, self.trees.len()) { print!("On {}th iteration of self.trees loop\n", i); { let front = self.trees.front().unwrap(); let back = self.trees.back().unwrap(); if front.rank() == back.rank() { same = true; } } if same { return Some((self.trees.pop_front().unwrap(), self.trees.pop_back().unwrap())); } self.trees.rotate_backward(); print!("End of {}th iteration\n", i); } return None; } } impl<K: Clone + Sub<K,K> + Ord + std::fmt::Show, V: Clone> FHeap<K, V> { pub fn new() -> FHeap<K, V> { FHeap { trees: DList::new() } } /* In order to ensure O(1) time for delete(node) and decrease_key(node, delta), * we need O(1) access to the element in the heap. Thus, insert returns a pointer * to the Entry. */ pub fn insert(&mut self, k: K, val: V) -> FibEntry<K,V> { let node = ~FibNode { parent: None, children: DList::new(), marked: false, key: k, value: val }; let ptr: *mut FibNode<K,V> = unsafe { cast::transmute(node) }; let ret = ptr.clone(); let mut tree = DList::new(); tree.push_front(ptr); let singleton = FHeap { trees: tree }; self.meld(singleton); ret } // Returns a copy of the minimum key and value. pub fn find_min(& self) -> (K, V) { match self.trees.front() { Some(n) => { (n.key(), n.value()) }, None => fail!("Fibonacci heap is empty") } } pub fn delete_min(&mut self) -> (K, V) { let min_tree = self.trees.pop_front().unwrap(); let value = min_tree.value(); let key = min_tree.key(); print!("Setting parent of children to None\n"); unsafe { for n in (*min_tree).children.mut_iter() { (**n).parent = None; } print!("Appending children to root list\n"); self.trees.append((*min_tree).children.clone()); } //let mut dlist = DList::new(); // Explicit closure scope. { // Closure to find to trees with the same rank. let mut link = self.same_rank(); while link.is_some() { print!("merging roots of same rank\n"); let (a, b) = link.unwrap(); if a.key().lt(&b.key()) { print!("less: {} more: {}\n", a.key(), b.key()); a.link(b); self.trees.push_front(a); } else { print!("less: {} more: {}\n", b.key(), a.key()); b.link(a); self.trees.push_front(b); } link = self.same_rank(); } } // Append all newly formed roots to list of roots. //self.trees.append(dlist); // Find the minimum node and put the tree first. print!("Finding minimum node and putting at front\n"); let mut min_node = self.trees.pop_front().unwrap(); print!("min node: {}, self.trees.len(): {}\n", min_node.key(), self.trees.len()); for _ in range(0, self.trees.len()) { print!("min_node: {} tree.front: {}\n", min_node.key(), self.trees.front().unwrap().key()); if self.trees.front().unwrap().key().lt(&min_node.key()) { self.trees.push_back(min_node); min_node = self.trees.pop_front().unwrap(); } else { self.trees.rotate_backward(); } } self.trees.push_front(min_node); // Drop ptr and return the minimum value. unsafe { drop(cast::transmute::<_, ~FibNode<K,V>>(min_tree)); } (key, value) } pub fn meld(&mut self, other: FHeap<K, V>) { if self.trees.is_empty() { self.trees.append(other.trees); } else if self.find_min().val0() <= other.find_min().val0() { self.trees.append(other.trees); } else { self.trees.prepend(other.trees); } } pub fn decrease_key(&mut self, node: FibEntry<K,V>, delta: K) { unsafe { (*node).key = (*node).key - delta; } if node.parent().is_none() { print!("node: {} has no parent\n", node.key()); return } print!("parent is Some\n"); print!("parent: {}\n", node.parent()); let parent = node.parent().unwrap(); self.remove_child(parent, node.key()); if self.find_min().val0().lt(&node.key()) { self.trees.push_back(node.clone()); } else { self.trees.push_front(node.clone()); } } pub fn delete(&mut self, node: FibEntry<K,V>) -> (K, V) { if self.find_min().val0() == node.key() { return self.delete_min() } else if node.parent().is_none() { let key = node.key(); for _ in range(0, self.trees.len()) { if self.trees.front().unwrap().key().eq(&key) { self.trees.pop_front(); break; } self.trees.rotate_backward(); } let value = node.value(); unsafe { self.trees.append((*node).children.clone()); drop(cast::transmute::<_, ~FibNode<K,V>>(node)); } (key, value) } else { let key = node.key(); let value = node.value(); self.remove_child(node.parent().unwrap(), node.key()); unsafe { self.trees.append((*node).children.clone()); drop(cast::transmute::<_, ~FibNode<K,V>>(node)); } (key, value) } } } /* * * Test Functions * */ #[test] fn test_fheap_meld() { let node = ~FibNode { parent: None, children: DList::new(), marked: false, key: 0, value: 0 }; let new_node = ~FibNode { parent: None, children: DList::new(), marked: false, key: 1, value: 1 }; unsafe { let mut ptr = cast::transmute(node); let mut tree = DList::new(); tree.push_front(ptr); let singleton = FHeap { trees: tree }; tree = DList::new(); ptr = cast::transmute(new_node); let child1 = cast::transmute(~FibNode { parent: Some(ptr.clone()), children: DList::new(), marked: false, key: 3, value: 3 }); let child2 = cast::transmute(~FibNode { parent: Some(ptr.clone()), children: DList::new(), marked: false, key: 9, value: 9 }); (*ptr).children.push_front(child1); (*ptr).children.push_front(child2); tree.push_front(ptr); let mut fheap = FHeap { trees: tree }; fheap.meld(singleton); assert_eq!(fheap.find_min(), (0,0)); } } #[test] fn test_fheap_insert() { let mut fheap = FHeap::new(); fheap.insert(1, ~"one"); fheap.insert(4, ~"four"); assert_eq!(fheap.find_min(), (1, ~"one")); fheap.insert(0, ~"zero"); assert_eq!(fheap.find_min(), (0, ~"zero")); } #[test] fn test_fheap_delete_min() { let mut fheap = FHeap::new(); fheap.insert(1, ~"1"); fheap.insert(4, ~"4"); fheap.insert(0, ~"0"); fheap.insert(5, ~"5"); assert_eq!(fheap.trees.len(), 4); fheap.delete_min(); assert_eq!(fheap.find_min(), (1, ~"1")); assert_eq!(fheap.trees.len(), 2); assert_eq!(fheap.delete_min(), (1, ~"1")); assert_eq!(fheap.find_min(), (4,~"4")); assert_eq!(fheap.trees.len(), 1); } #[test] fn test_fheap_decrease_key() { let mut fheap = FHeap::new(); fheap.insert(1, ~"1"); let four = fheap.insert(4, ~"4"); fheap.insert(0, ~"0"); let five = fheap.insert(5, ~"5"); fheap.delete_min(); fheap.decrease_key(four, 2); assert_eq!(four.key(), 2); assert!(four.parent().is_none()); assert_eq!(fheap.trees.len(), 2); fheap.decrease_key(five, 5); assert_eq!(fheap.trees.len(), 3); assert_eq!(fheap.find_min(), (0, ~"5")) } #[test] fn test_fheap_delete() { let mut fheap = FHeap::new(); let one = fheap.insert(1, ~"1"); let four = fheap.insert(4, ~"4"); fheap.insert(0, ~"0"); fheap.insert(5, ~"5"); fheap.delete_min(); let (kfour, _) = fheap.delete(four.clone()); assert_eq!(kfour, 4); assert_eq!(fheap.trees.len(), 1); fheap.delete(one); assert_eq!(fheap.trees.len(), 1); assert_eq!(fheap.find_min(), (5, ~"5")) } #[test] fn test_fheap_cascading_cut() { let mut fheap = FHeap::new(); fheap.insert(1, "1"); fheap.insert(4, "4"); fheap.insert(0, "0"); fheap.insert(5, "5"); fheap.insert(2, "2"); let h3 = fheap.insert(3, "3"); let h6 = fheap.insert(6, "6"); fheap.insert(7, "7"); fheap.insert(18, "18"); fheap.insert(9, "9"); fheap.insert(11, "11"); fheap.insert(15, "15"); fheap.delete_min(); assert_eq!(fheap.find_min(), (1, "1")); assert_eq!(fheap.trees.len(), 3); fheap.decrease_key(h6, 2); fheap.decrease_key(h3, 3); assert_eq!(fheap.trees.len(), 6); }
use futures_core::Stream; use std::future::Future; use std::mem::take; use std::{ pin::Pin, sync::{Arc, Mutex}, task::{Context, Poll}, }; struct YielderState<T: Unpin> { value: Option<T>, } pub struct YielderFuture<T: Unpin> { state: Arc<Mutex<YielderState<T>>>, } impl<T: Unpin> Future for YielderFuture<T> { type Output = (); fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> { if self.state.lock().unwrap().value.is_some() { Poll::Pending } else { Poll::Ready(()) } } } pub struct Yielder<T: Unpin> { state: Arc<Mutex<YielderState<T>>>, } impl<T: Unpin> Yielder<T> { pub fn put(&mut self, x: T) -> YielderFuture<T> { let mut locked = self.state.lock().unwrap(); if locked.value.is_some() { panic!("cannot yield more than once without awaiting the previous result"); } locked.value = Some(x); YielderFuture { state: self.state.clone(), } } } pub struct YielderStream<T: Unpin, Fut: Future> { future: Pin<Box<Fut>>, future_done: bool, state: Arc<Mutex<YielderState<T>>>, } impl<T: Unpin, Fut: Future> Stream for YielderStream<T, Fut> { type Item = T; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { { // It is possible the Yielder was moved outside of the // future and yield was called on it externally. let mut locked = self.state.lock().unwrap(); if let Some(x) = take(&mut locked.value) { return Poll::Ready(Some(x)); } } if self.future_done { return Poll::Ready(None); } else if let Poll::Ready(_) = self.future.as_mut().poll(cx) { self.future_done = true; } let mut locked = self.state.lock().unwrap(); if let Some(x) = take(&mut locked.value) { Poll::Ready(Some(x)) } else { if self.future_done { Poll::Ready(None) } else { Poll::Pending } } } } // Call this with a closure that takes a single argument, a yielder. // The closure may act like a normal async function, and can call other // async methods. // To yield a value to the stream, call yielder.put(value).await. pub fn make_stream<T: Unpin, F, Fut: Future<Output = ()>>(f: F) -> YielderStream<T, Fut> where F: FnOnce(Yielder<T>) -> Fut, { let state = Arc::new(Mutex::new(YielderState { value: None })); let yielder = Yielder { state: state.clone(), }; YielderStream { future: Box::pin(f(yielder)), future_done: false, state: state, } }
use crate::Error; use cavalier_contours::polyline::{PlineCreation, PlineSource, PlineSourceMut, Polyline}; use geo::{Densify, EuclideanLength, Winding}; use geo_types::{Line, LineString, Polygon, Rect}; use h3ron::collections::HashSet; use h3ron::{H3Cell, ToCoordinate, ToH3Cells, ToPolygon}; use ordered_float::OrderedFloat; /// find the cells located directly within the exterior ring of the given polygon /// /// The border cells are not guaranteed to be exactly one cell wide. Due to grid orientation /// the line may be two cells wide at some places. /// /// `width`: Width of the border in (approx.) number of cells. Default: 1 pub fn border_cells( poly: &Polygon, h3_resolution: u8, width: Option<u32>, ) -> Result<HashSet<H3Cell>, Error> { let ext_ring = { let mut ext_ring = poly.exterior().clone(); ext_ring.make_ccw_winding(); // make coord order deterministic so the offset direction is correct ext_ring }; let cell_radius = max_cell_radius(&ext_ring, h3_resolution)?; let buffer_offset = cell_radius * 1.5 * (width.unwrap_or(1) as f64); // small rects -> smaller grid_disks for H3 to generate let densification = cell_radius * 10.0; let mut out_cells = HashSet::default(); for ext_line_segment in ext_ring.0.windows(2) { let line = Line::new(ext_line_segment[0], ext_line_segment[1]); let line_with_offset = { let mut pline = Polyline::with_capacity(2, false); pline.add(line.start.x, line.start.y, 0.0); pline.add(line.end.x, line.end.y, 0.0); let offsetted = pline.parallel_offset(buffer_offset); if offsetted.is_empty() { continue; } let offsetted_pline = &offsetted[0]; if offsetted_pline.vertex_data.len() < 2 { continue; } let l = offsetted_pline.vertex_data.len(); Line::new( ( offsetted_pline.vertex_data[0].x, offsetted_pline.vertex_data[0].y, ), ( offsetted_pline.vertex_data[l - 1].x, offsetted_pline.vertex_data[l - 1].y, ), ) }; let line_with_offset = line_with_offset.densify(densification); let line = line.densify(densification); for (line_window, line_with_offset_window) in line.0.windows(2).zip(line_with_offset.0.windows(2)) { out_cells.extend( Rect::new(line_window[0], line_with_offset_window[1]) .to_h3_cells(h3_resolution)? .iter(), ); } } Ok(out_cells) } fn max_cell_radius(ls: &LineString, h3_resolution: u8) -> Result<f64, Error> { let lengths = ls.0.iter() .map(|c| { H3Cell::from_coordinate(*c, h3_resolution) .map_err(Error::from) .and_then(|cell| cell_radius(cell).map(OrderedFloat::from)) }) .collect::<Result<Vec<_>, _>>()?; Ok(*lengths .iter() .copied() .max() .unwrap_or_else(|| OrderedFloat::from(0.0))) } fn cell_radius(cell: H3Cell) -> Result<f64, Error> { let center = cell.to_coordinate()?; let poly = cell.to_polygon()?; Ok(Line::new(center, poly.exterior().0[0]) .euclidean_length() .abs()) } #[cfg(test)] mod tests { use crate::geom::border_cells; use geo_types::Rect; use h3ron::collections::HashSet; use h3ron::ToH3Cells; #[test] fn border_cells_within_rect() { let rect = Rect::new((30.0, 30.0), (50.0, 50.0)); let h3_resolution = 7; let filled_cells = HashSet::from_iter(rect.to_h3_cells(h3_resolution).unwrap().iter()); let border = border_cells(&rect.to_polygon(), h3_resolution, Some(1)).unwrap(); dbg!(filled_cells.len(), border.len()); assert!(border.len() > 100); // write geojson for visual inspection /* { use geo_types::{GeometryCollection, Point, Geometry}; use h3ron::{ToCoordinate, ToPolygon}; let mut geoms: Vec<Geometry> = vec![rect.into()]; for bc in border.iter() { geoms.push(Point::from(bc.to_coordinate().unwrap()).into()); geoms.push(bc.to_polygon().unwrap().into()); } let gc = GeometryCollection::from(geoms); let fc = geojson::FeatureCollection::from(&gc); std::fs::write("/tmp/border.geojson", fc.to_string()).unwrap(); } */ let n_cells_contained = border.iter().fold(0, |mut acc, bc| { if filled_cells.contains(bc) { acc += 1; } acc }); dbg!(n_cells_contained); assert!(border.len() <= n_cells_contained); } }
use crate::load_function_ptrs; use crate::prelude::*; use std::os::raw::c_void; load_function_ptrs!(DeviceWSIFunctions, { vkQueuePresentKHR(queue: VkQueue, pPresentInfo: *const VkPresentInfoKHR) -> VkResult, vkCreateSwapchainKHR( device: VkDevice, pCreateInfo: *const VkSwapchainCreateInfoKHR, pAllocator: *const VkAllocationCallbacks, pSwapchain: *mut VkSwapchainKHR ) -> VkResult, vkDestroySwapchainKHR( device: VkDevice, swapchain: VkSwapchainKHR, pAllocator: *const VkAllocationCallbacks ) -> (), vkGetSwapchainImagesKHR( device: VkDevice, swapchain: VkSwapchainKHR, pSwapchainImageCount: *mut u32, pSwapchainImages: *mut VkImage ) -> VkResult, vkAcquireNextImageKHR( device: VkDevice, swapchain: VkSwapchainKHR, timeout: u64, semaphore: VkSemaphore, fence: VkFence, pImageIndex: *mut u32 ) -> VkResult, });
use std::collections::{hash_map::Entry, HashMap}; use std::path::{Path, PathBuf}; use crate::fs::LllDirList; use crate::sort; pub trait DirectoryHistory { fn populate_to_root( &mut self, pathbuf: &PathBuf, sort_option: &sort::SortOption, ) -> std::io::Result<()>; fn pop_or_create( &mut self, path: &Path, sort_option: &sort::SortOption, ) -> std::io::Result<LllDirList>; fn get_mut_or_create( &mut self, path: &Path, sort_option: &sort::SortOption, ) -> std::io::Result<&mut LllDirList>; fn depreciate_all_entries(&mut self); } pub type LllHistory = HashMap<PathBuf, LllDirList>; impl DirectoryHistory for LllHistory { fn populate_to_root( &mut self, pathbuf: &PathBuf, sort_option: &sort::SortOption, ) -> std::io::Result<()> { let mut ancestors = pathbuf.ancestors(); match ancestors.next() { None => {} Some(mut ancestor) => { for curr in ancestors { let mut dirlist = LllDirList::new(curr.to_path_buf().clone(), sort_option)?; let index = dirlist.contents.iter().enumerate().find_map(|(i, dir)| { if dir.file_path() == ancestor { Some(i) } else { None } }); if let Some(i) = index { dirlist.index = Some(i); } self.insert(curr.to_path_buf(), dirlist); ancestor = curr; } } } Ok(()) } fn pop_or_create( &mut self, path: &Path, sort_option: &sort::SortOption, ) -> std::io::Result<LllDirList> { match self.remove(&path.to_path_buf()) { Some(mut dirlist) => { if dirlist.need_update() { dirlist.update_contents(&sort_option)? } else { let metadata = std::fs::symlink_metadata(dirlist.file_path())?; let modified = metadata.modified()?; if modified > dirlist.metadata.modified { dirlist.update_contents(&sort_option)? } } Ok(dirlist) } None => { let path_clone = path.to_path_buf(); LllDirList::new(path_clone, &sort_option) } } } fn get_mut_or_create( &mut self, path: &Path, sort_option: &sort::SortOption, ) -> std::io::Result<&mut LllDirList> { match self.entry(path.to_path_buf().clone()) { Entry::Occupied(entry) => Ok(entry.into_mut()), Entry::Vacant(entry) => { let s = LllDirList::new(path.to_path_buf(), &sort_option)?; Ok(entry.insert(s)) } } } fn depreciate_all_entries(&mut self) { self.iter_mut().for_each(|(_, v)| v.depreciate()); } }
//! Display an interactive selector of a single value from a range of values. //! //! A [`Slider`] has some local [`State`]. //! //! [`Slider`]: struct.Slider.html //! [`State`]: struct.State.html use crate::{style, Bus, Element, Length, Widget}; use dodrio::bumpalo; use std::{ops::RangeInclusive, rc::Rc}; /// An horizontal bar and a handle that selects a single value from a range of /// values. /// /// A [`Slider`] will try to fill the horizontal space of its container. /// /// [`Slider`]: struct.Slider.html /// /// # Example /// ``` /// # use iced_web::{slider, Slider}; /// # /// pub enum Message { /// SliderChanged(f32), /// } /// /// let state = &mut slider::State::new(); /// let value = 50.0; /// /// Slider::new(state, 0.0..=100.0, value, Message::SliderChanged); /// ``` /// /// ![Slider drawn by Coffee's renderer](https://github.com/hecrj/coffee/blob/bda9818f823dfcb8a7ad0ff4940b4d4b387b5208/images/ui/slider.png?raw=true) #[allow(missing_debug_implementations)] pub struct Slider<'a, Message> { _state: &'a mut State, range: RangeInclusive<f32>, value: f32, on_change: Rc<Box<dyn Fn(f32) -> Message>>, width: Length, } impl<'a, Message> Slider<'a, Message> { /// Creates a new [`Slider`]. /// /// It expects: /// * the local [`State`] of the [`Slider`] /// * an inclusive range of possible values /// * the current value of the [`Slider`] /// * a function that will be called when the [`Slider`] is dragged. /// It receives the new value of the [`Slider`] and must produce a /// `Message`. /// /// [`Slider`]: struct.Slider.html /// [`State`]: struct.State.html pub fn new<F>( state: &'a mut State, range: RangeInclusive<f32>, value: f32, on_change: F, ) -> Self where F: 'static + Fn(f32) -> Message, { Slider { _state: state, value: value.max(*range.start()).min(*range.end()), range, on_change: Rc::new(Box::new(on_change)), width: Length::Fill, } } /// Sets the width of the [`Slider`]. /// /// [`Slider`]: struct.Slider.html pub fn width(mut self, width: Length) -> Self { self.width = width; self } } impl<'a, Message> Widget<Message> for Slider<'a, Message> where Message: 'static + Clone, { fn node<'b>( &self, bump: &'b bumpalo::Bump, bus: &Bus<Message>, _style_sheet: &mut style::Sheet<'b>, ) -> dodrio::Node<'b> { use dodrio::builder::*; use wasm_bindgen::JsCast; let (start, end) = self.range.clone().into_inner(); let min = bumpalo::format!(in bump, "{}", start); let max = bumpalo::format!(in bump, "{}", end); let value = bumpalo::format!(in bump, "{}", self.value); let on_change = self.on_change.clone(); let event_bus = bus.clone(); // TODO: Make `step` configurable // TODO: Complete styling input(bump) .attr("type", "range") .attr("step", "0.01") .attr("min", min.into_bump_str()) .attr("max", max.into_bump_str()) .attr("value", value.into_bump_str()) .attr("style", "width: 100%") .on("input", move |root, vdom, event| { let slider = match event.target().and_then(|t| { t.dyn_into::<web_sys::HtmlInputElement>().ok() }) { None => return, Some(slider) => slider, }; if let Ok(value) = slider.value().parse::<f32>() { event_bus.publish(on_change(value), root); vdom.schedule_render(); } }) .finish() } } impl<'a, Message> From<Slider<'a, Message>> for Element<'a, Message> where Message: 'static + Clone, { fn from(slider: Slider<'a, Message>) -> Element<'a, Message> { Element::new(slider) } } /// The local state of a [`Slider`]. /// /// [`Slider`]: struct.Slider.html #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct State; impl State { /// Creates a new [`State`]. /// /// [`State`]: struct.State.html pub fn new() -> Self { Self } }
//! RPC interface for the transaction payment module. use jsonrpc_core::{Error as RpcError, ErrorCode, Result}; use jsonrpc_derive::rpc; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; use std::sync::Arc; use massbit_runtime_api::MassbitApi as MassbitRuntimeApi; use frame_support::Parameter; #[rpc] pub trait MassbitApi<BlockHash,WorkerIndex,AccountId,JobProposalIndex> { #[rpc(name = "massbit_getWorkers")] fn get_workers(&self, at: Option<BlockHash>) -> Result<Vec<(WorkerIndex,Vec<u8>,AccountId, bool, JobProposalIndex)>>; #[rpc(name = "massbit_getJobReports")] fn get_job_reports(&self, at: Option<BlockHash>) -> Result<Vec<(u32,Vec<u8>,Vec<u8>)>>; #[rpc(name = "massbit_getJobProposals")] fn get_job_proposals(&self, at: Option<BlockHash>) -> Result<Vec<(JobProposalIndex, AccountId, Vec<u8>, u64, Vec<u8>, Vec<u8>)>>; } /// A struct that implements the `MassbitApi`. pub struct Massbit<C, M> { // If you have more generics, no need to Massbit<C, M, N, P, ...> // just use a tuple like Massbit<C, (M, N, P, ...)> client: Arc<C>, _marker: std::marker::PhantomData<M>, } impl<C, M> Massbit<C, M> { /// Create new `Massbit` instance with the given reference to the client. pub fn new(client: Arc<C>) -> Self { Self { client, _marker: Default::default(), } } } /// Error type of this RPC api. // pub enum Error { // /// The transaction was not decodable. // DecodeError, // /// The call to runtime failed. // RuntimeError, // } // // impl From<Error> for i64 { // fn from(e: Error) -> i64 { // match e { // Error::RuntimeError => 1, // Error::DecodeError => 2, // } // } // } impl<C, Block, WorkerIndex, AccountId, JobProposalIndex> MassbitApi<<Block as BlockT>::Hash, WorkerIndex, AccountId, JobProposalIndex> for Massbit<C, Block> where Block: BlockT, AccountId: Parameter, WorkerIndex: Parameter, JobProposalIndex: Parameter, C: Send + Sync + 'static, C: ProvideRuntimeApi<Block>, C: HeaderBackend<Block>, C::Api: MassbitRuntimeApi<Block, AccountId,WorkerIndex,JobProposalIndex>, { fn get_workers(&self, at: Option<<Block as BlockT>::Hash>) -> Result<Vec<(WorkerIndex,Vec<u8>,AccountId, bool, JobProposalIndex)>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); let runtime_api_result = api.get_workers(&at); runtime_api_result.map_err(|e| RpcError { code: ErrorCode::ServerError(1000), // No real reason for this value message: "Something wrong with get_workers".into(), data: Some(format!("{:?}", e).into()), }) } fn get_job_reports(&self, at: Option<<Block as BlockT>::Hash>) -> Result<Vec<(u32,Vec<u8>,Vec<u8>)>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); let runtime_api_result = api.get_job_reports(&at); runtime_api_result.map_err(|e| RpcError { code: ErrorCode::ServerError(2000), // No real reason for this value message: "Something wrong with get_job_reports".into(), data: Some(format!("{:?}", e).into()), }) } fn get_job_proposals(&self, at: Option<<Block as BlockT>::Hash>) -> Result<Vec<(JobProposalIndex, AccountId, Vec<u8>, u64, Vec<u8>, Vec<u8>)>> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| // If the block hash is not supplied assume the best block. self.client.info().best_hash)); let runtime_api_result = api.get_job_proposals(&at); runtime_api_result.map_err(|e| RpcError { code: ErrorCode::ServerError(3000), // No real reason for this value message: "Something wrong qith get_job_proposals".into(), data: Some(format!("{:?}", e).into()), }) } }
fn main() { let n = { let mut s = String::new(); // バッファを確保 std::io::stdin().read_line(&mut s).unwrap(); // 一行読む。失敗を無視 s.trim_end().to_owned() // 改行コードが末尾にくっついてくるので削る }; let n: i32 = n.parse().unwrap(); println!("{}", n * 2); }
// 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. // force-host #![feature(plugin_registrar, rustc_private)] #![feature(box_syntax)] #![feature(macro_vis_matcher)] #![feature(macro_at_most_once_rep)] #[macro_use] extern crate rustc; extern crate rustc_plugin; extern crate syntax; use rustc::lint::{LateContext, LintContext, LintPass, LateLintPass, LateLintPassObject, LintArray}; use rustc_plugin::Registry; use rustc::hir; use syntax::attr; macro_rules! fake_lint_pass { ($struct:ident, $lints:expr, $($attr:expr),*) => { struct $struct; impl LintPass for $struct { fn get_lints(&self) -> LintArray { $lints } } impl<'a, 'tcx> LateLintPass<'a, 'tcx> for $struct { fn check_crate(&mut self, cx: &LateContext, krate: &hir::Crate) { $( if !attr::contains_name(&krate.attrs, $attr) { cx.span_lint(CRATE_NOT_OKAY, krate.span, &format!("crate is not marked with #![{}]", $attr)); } )* } } } } declare_lint!(CRATE_NOT_OKAY, Warn, "crate not marked with #![crate_okay]"); declare_lint!(CRATE_NOT_RED, Warn, "crate not marked with #![crate_red]"); declare_lint!(CRATE_NOT_BLUE, Warn, "crate not marked with #![crate_blue]"); declare_lint!(CRATE_NOT_GREY, Warn, "crate not marked with #![crate_grey]"); declare_lint!(CRATE_NOT_GREEN, Warn, "crate not marked with #![crate_green]"); fake_lint_pass! { PassOkay, lint_array!(CRATE_NOT_OKAY), // Single lint "rustc_crate_okay" } fake_lint_pass! { PassRedBlue, lint_array!(CRATE_NOT_RED, CRATE_NOT_BLUE), // Multiple lints "rustc_crate_red", "rustc_crate_blue" } fake_lint_pass! { PassGreyGreen, lint_array!(CRATE_NOT_GREY, CRATE_NOT_GREEN, ), // Trailing comma "rustc_crate_grey", "rustc_crate_green" } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_late_lint_pass(box PassOkay); reg.register_late_lint_pass(box PassRedBlue); reg.register_late_lint_pass(box PassGreyGreen); }
//! Day 7 use std::{ collections::{HashMap, HashSet}, hash::Hash, }; trait Solution { fn part_1(&self) -> usize; fn part_2(&self) -> usize; } impl Solution for str { fn part_1(&self) -> usize { bfs( "shiny gold", &build_containee_map(&parsers::input(self).expect("Failed to parse the input")), ) .len() } fn part_2(&self) -> usize { count_nesting( "shiny gold", &build_container_map(&parsers::input(self).expect("Failed to parse the input")), ) } } fn build_containee_map<K1, K2, V>(data: &[(K1, impl AsRef<[(K2, V)]>)]) -> HashMap<K2, Vec<K1>> where K1: Eq + Hash + Clone, K2: Eq + Hash + Clone, { let mut result = HashMap::<_, Vec<_>>::new(); for (container, containees) in data.iter() { for (containee, _) in containees.as_ref().iter() { result .entry(containee.clone()) .or_default() .push(container.clone()) } } result } fn bfs<'a, T>(start: T, data: &'a HashMap<T, Vec<T>>) -> HashSet<&'a T> where T: Eq + Hash, { let mut all_children = HashSet::new(); let mut to_visit = vec![&start]; while let Some(next) = to_visit.pop() { if let Some(children) = data.get(next) { for child in children { if !all_children.contains(child) { to_visit.push(child); all_children.insert(child); } } } } all_children } fn build_container_map<K1, K2, V>(data: &[(K1, Vec<(K2, V)>)]) -> HashMap<K1, HashMap<K2, V>> where K1: Eq + Hash + Clone, K2: Eq + Hash + Clone, V: Clone, { data.iter() .map(|(container, containees)| (container.clone(), containees.iter().cloned().collect())) .collect() } fn count_nesting<T>(end: T, data: &HashMap<T, HashMap<T, usize>>) -> usize where T: Eq + Hash, { let mut sums = HashMap::<&T, usize>::new(); let mut to_visit = vec![&end]; while let Some(next) = to_visit.last() { let entries = data.get(next).unwrap(); if entries.iter().all(|(e, _)| sums.contains_key(e)) { sums.insert( next, entries.iter().map(|(e, &mul)| mul * (1 + sums[e])).sum(), ); to_visit.pop().unwrap(); } else { to_visit.extend(entries.iter().filter_map(|(e, _)| { if !sums.contains_key(e) { Some(e) } else { None } })); } } sums[&end] } mod parsers { use nom::{ branch::alt, bytes::complete::tag, character::complete::{alpha1, char, line_ending, space1}, combinator::{map, opt, recognize, value}, error::Error, multi::separated_list1, sequence::{pair, separated_pair, terminated}, IResult, }; use crate::parsers::{finished_parser, integer}; pub fn input(s: &str) -> Result<Vec<(&str, Vec<(&str, usize)>)>, Error<&str>> { finished_parser(separated_list1(line_ending, line))(s) } fn line(s: &str) -> IResult<&str, (&str, Vec<(&str, usize)>)> { separated_pair( color, tag(" bags contain "), terminated( alt(( separated_list1(tag(", "), quantified_bag), value(Vec::new(), tag("no other bags")), )), char('.'), ), )(s) } fn color(s: &str) -> IResult<&str, &str> { recognize(separated_pair(alpha1, char(' '), alpha1))(s) } fn quantified_bag(s: &str) -> IResult<&str, (&str, usize)> { terminated( map(separated_pair(integer, space1, color), |(num, color)| { (color, num) }), pair(tag(" bag"), opt(char('s'))), )(s) } } #[cfg(test)] mod tests { use super::*; #[test] fn example_input() { assert_eq!( parsers::input( "\ light red bags contain 1 bright white bag, 2 muted yellow bags. dark orange bags contain 3 bright white bags, 4 muted yellow bags. bright white bags contain 1 shiny gold bag. muted yellow bags contain 2 shiny gold bags, 9 faded blue bags. shiny gold bags contain 1 dark olive bag, 2 vibrant plum bags. dark olive bags contain 3 faded blue bags, 4 dotted black bags. vibrant plum bags contain 5 faded blue bags, 6 dotted black bags. faded blue bags contain no other bags. dotted black bags contain no other bags." ), Ok(vec![ ("light red", vec![("bright white", 1), ("muted yellow", 2)]), ( "dark orange", vec![("bright white", 3), ("muted yellow", 4)] ), ("bright white", vec![("shiny gold", 1)]), ("muted yellow", vec![("shiny gold", 2), ("faded blue", 9)]), ("shiny gold", vec![("dark olive", 1), ("vibrant plum", 2)]), ("dark olive", vec![("faded blue", 3), ("dotted black", 4)]), ("vibrant plum", vec![("faded blue", 5), ("dotted black", 6)]), ("faded blue", vec![]), ("dotted black", vec![]), ]) ); } #[test] fn example_1() { assert_eq!( bfs( "shiny gold", &build_containee_map(&[ ("light red", vec![("bright white", 1), ("muted yellow", 2)]), ( "dark orange", vec![("bright white", 3), ("muted yellow", 4)] ), ("bright white", vec![("shiny gold", 1)]), ("muted yellow", vec![("shiny gold", 2), ("faded blue", 9)]), ("shiny gold", vec![("dark olive", 1), ("vibrant plum", 2)]), ("dark olive", vec![("faded blue", 3), ("dotted black", 4)]), ("vibrant plum", vec![("faded blue", 5), ("dotted black", 6)]), ("faded blue", vec![]), ("dotted black", vec![]), ]) ), ["bright white", "muted yellow", "dark orange", "light red"] .iter() .collect() ); } #[test] fn part_1() { assert_eq!(include_str!("inputs/day_7").part_1(), 142); } #[test] fn example_2() { assert_eq!( count_nesting( "shiny gold", &build_container_map(&[ ("light red", vec![("bright white", 1), ("muted yellow", 2)]), ( "dark orange", vec![("bright white", 3), ("muted yellow", 4)] ), ("bright white", vec![("shiny gold", 1)]), ("muted yellow", vec![("shiny gold", 2), ("faded blue", 9)]), ("shiny gold", vec![("dark olive", 1), ("vibrant plum", 2)]), ("dark olive", vec![("faded blue", 3), ("dotted black", 4)]), ("vibrant plum", vec![("faded blue", 5), ("dotted black", 6)]), ("faded blue", vec![]), ("dotted black", vec![]), ]) ), 32 ); } #[test] fn example_3() { assert_eq!( count_nesting( "shiny gold", &build_container_map( &parsers::input( "\ shiny gold bags contain 2 dark red bags. dark red bags contain 2 dark orange bags. dark orange bags contain 2 dark yellow bags. dark yellow bags contain 2 dark green bags. dark green bags contain 2 dark blue bags. dark blue bags contain 2 dark violet bags. dark violet bags contain no other bags." ) .unwrap() ) ), 126 ); } #[test] fn part_2() { assert_eq!(include_str!("inputs/day_7").part_2(), 10219); } }
use point::Point; pub struct Apple { pub location: Point, } impl Apple { pub fn new(x: i32, y: i32) -> Apple { Apple { location: Point { x: x, y: y } } } }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn D3DCompile(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, psourcename: super::super::super::Foundation::PSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, pentrypoint: super::super::super::Foundation::PSTR, ptarget: super::super::super::Foundation::PSTR, flags1: u32, flags2: u32, ppcode: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DCompile2( psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, psourcename: super::super::super::Foundation::PSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, pentrypoint: super::super::super::Foundation::PSTR, ptarget: super::super::super::Foundation::PSTR, flags1: u32, flags2: u32, secondarydataflags: u32, psecondarydata: *const ::core::ffi::c_void, secondarydatasize: usize, ppcode: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob, ) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DCompileFromFile(pfilename: super::super::super::Foundation::PWSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, pentrypoint: super::super::super::Foundation::PSTR, ptarget: super::super::super::Foundation::PSTR, flags1: u32, flags2: u32, ppcode: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DCompressShaders(unumshaders: u32, pshaderdata: *const D3D_SHADER_DATA, uflags: u32, ppcompresseddata: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DCreateBlob(size: usize, ppblob: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Graphics_Direct3D11")] pub fn D3DCreateFunctionLinkingGraph(uflags: u32, ppfunctionlinkinggraph: *mut super::super::Direct3D11::ID3D11FunctionLinkingGraph) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Graphics_Direct3D11")] pub fn D3DCreateLinker(pplinker: *mut super::super::Direct3D11::ID3D11Linker) -> ::windows_sys::core::HRESULT; pub fn D3DDecompressShaders(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, unumshaders: u32, ustartindex: u32, pindices: *const u32, uflags: u32, ppshaders: *mut super::ID3DBlob, ptotalshaders: *mut u32) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DDisassemble(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, flags: u32, szcomments: super::super::super::Foundation::PSTR, ppdisassembly: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Graphics_Direct3D10")] pub fn D3DDisassemble10Effect(peffect: super::super::Direct3D10::ID3D10Effect, flags: u32, ppdisassembly: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DDisassembleRegion(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, flags: u32, szcomments: super::super::super::Foundation::PSTR, startbyteoffset: usize, numinsts: usize, pfinishbyteoffset: *mut usize, ppdisassembly: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetBlobPart(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, part: D3D_BLOB_PART, flags: u32, pppart: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetDebugInfo(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, ppdebuginfo: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetInputAndOutputSignatureBlob(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, ppsignatureblob: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetInputSignatureBlob(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, ppsignatureblob: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetOutputSignatureBlob(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, ppsignatureblob: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DGetTraceInstructionOffsets(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, flags: u32, startinstindex: usize, numinsts: usize, poffsets: *mut usize, ptotalinsts: *mut usize) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Graphics_Direct3D11")] pub fn D3DLoadModule(psrcdata: *const ::core::ffi::c_void, cbsrcdatasize: usize, ppmodule: *mut super::super::Direct3D11::ID3D11Module) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DPreprocess(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, psourcename: super::super::super::Foundation::PSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, ppcodetext: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DReadFileToBlob(pfilename: super::super::super::Foundation::PWSTR, ppcontents: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DReflect(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, pinterface: *const ::windows_sys::core::GUID, ppreflector: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn D3DReflectLibrary(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, riid: *const ::windows_sys::core::GUID, ppreflector: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; pub fn D3DSetBlobPart(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, part: D3D_BLOB_PART, flags: u32, ppart: *const ::core::ffi::c_void, partsize: usize, ppnewshader: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; pub fn D3DStripShader(pshaderbytecode: *const ::core::ffi::c_void, bytecodelength: usize, ustripflags: u32, ppstrippedblob: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn D3DWriteBlobToFile(pblob: super::ID3DBlob, pfilename: super::super::super::Foundation::PWSTR, boverwrite: super::super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; } pub type D3DCOMPILER_STRIP_FLAGS = i32; pub const D3DCOMPILER_STRIP_REFLECTION_DATA: D3DCOMPILER_STRIP_FLAGS = 1i32; pub const D3DCOMPILER_STRIP_DEBUG_INFO: D3DCOMPILER_STRIP_FLAGS = 2i32; pub const D3DCOMPILER_STRIP_TEST_BLOBS: D3DCOMPILER_STRIP_FLAGS = 4i32; pub const D3DCOMPILER_STRIP_PRIVATE_DATA: D3DCOMPILER_STRIP_FLAGS = 8i32; pub const D3DCOMPILER_STRIP_ROOT_SIGNATURE: D3DCOMPILER_STRIP_FLAGS = 16i32; pub const D3DCOMPILER_STRIP_FORCE_DWORD: D3DCOMPILER_STRIP_FLAGS = 2147483647i32; pub const D3DCOMPILE_ALL_RESOURCES_BOUND: u32 = 2097152u32; pub const D3DCOMPILE_AVOID_FLOW_CONTROL: u32 = 512u32; pub const D3DCOMPILE_DEBUG: u32 = 1u32; pub const D3DCOMPILE_DEBUG_NAME_FOR_BINARY: u32 = 8388608u32; pub const D3DCOMPILE_DEBUG_NAME_FOR_SOURCE: u32 = 4194304u32; pub const D3DCOMPILE_EFFECT_ALLOW_SLOW_OPS: u32 = 2u32; pub const D3DCOMPILE_EFFECT_CHILD_EFFECT: u32 = 1u32; pub const D3DCOMPILE_ENABLE_BACKWARDS_COMPATIBILITY: u32 = 4096u32; pub const D3DCOMPILE_ENABLE_STRICTNESS: u32 = 2048u32; pub const D3DCOMPILE_ENABLE_UNBOUNDED_DESCRIPTOR_TABLES: u32 = 1048576u32; pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_0: u32 = 16u32; pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_1_1: u32 = 32u32; pub const D3DCOMPILE_FLAGS2_FORCE_ROOT_SIGNATURE_LATEST: u32 = 0u32; pub const D3DCOMPILE_FORCE_PS_SOFTWARE_NO_OPT: u32 = 128u32; pub const D3DCOMPILE_FORCE_VS_SOFTWARE_NO_OPT: u32 = 64u32; pub const D3DCOMPILE_IEEE_STRICTNESS: u32 = 8192u32; pub const D3DCOMPILE_NO_PRESHADER: u32 = 256u32; pub const D3DCOMPILE_OPTIMIZATION_LEVEL0: u32 = 16384u32; pub const D3DCOMPILE_OPTIMIZATION_LEVEL1: u32 = 0u32; pub const D3DCOMPILE_OPTIMIZATION_LEVEL3: u32 = 32768u32; pub const D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR: u32 = 16u32; pub const D3DCOMPILE_PACK_MATRIX_ROW_MAJOR: u32 = 8u32; pub const D3DCOMPILE_PARTIAL_PRECISION: u32 = 32u32; pub const D3DCOMPILE_PREFER_FLOW_CONTROL: u32 = 1024u32; pub const D3DCOMPILE_RESERVED16: u32 = 65536u32; pub const D3DCOMPILE_RESERVED17: u32 = 131072u32; pub const D3DCOMPILE_RESOURCES_MAY_ALIAS: u32 = 524288u32; pub const D3DCOMPILE_SECDATA_MERGE_UAV_SLOTS: u32 = 1u32; pub const D3DCOMPILE_SECDATA_PRESERVE_TEMPLATE_SLOTS: u32 = 2u32; pub const D3DCOMPILE_SECDATA_REQUIRE_TEMPLATE_MATCH: u32 = 4u32; pub const D3DCOMPILE_SKIP_OPTIMIZATION: u32 = 4u32; pub const D3DCOMPILE_SKIP_VALIDATION: u32 = 2u32; pub const D3DCOMPILE_WARNINGS_ARE_ERRORS: u32 = 262144u32; pub type D3D_BLOB_PART = i32; pub const D3D_BLOB_INPUT_SIGNATURE_BLOB: D3D_BLOB_PART = 0i32; pub const D3D_BLOB_OUTPUT_SIGNATURE_BLOB: D3D_BLOB_PART = 1i32; pub const D3D_BLOB_INPUT_AND_OUTPUT_SIGNATURE_BLOB: D3D_BLOB_PART = 2i32; pub const D3D_BLOB_PATCH_CONSTANT_SIGNATURE_BLOB: D3D_BLOB_PART = 3i32; pub const D3D_BLOB_ALL_SIGNATURE_BLOB: D3D_BLOB_PART = 4i32; pub const D3D_BLOB_DEBUG_INFO: D3D_BLOB_PART = 5i32; pub const D3D_BLOB_LEGACY_SHADER: D3D_BLOB_PART = 6i32; pub const D3D_BLOB_XNA_PREPASS_SHADER: D3D_BLOB_PART = 7i32; pub const D3D_BLOB_XNA_SHADER: D3D_BLOB_PART = 8i32; pub const D3D_BLOB_PDB: D3D_BLOB_PART = 9i32; pub const D3D_BLOB_PRIVATE_DATA: D3D_BLOB_PART = 10i32; pub const D3D_BLOB_ROOT_SIGNATURE: D3D_BLOB_PART = 11i32; pub const D3D_BLOB_DEBUG_NAME: D3D_BLOB_PART = 12i32; pub const D3D_BLOB_TEST_ALTERNATE_SHADER: D3D_BLOB_PART = 32768i32; pub const D3D_BLOB_TEST_COMPILE_DETAILS: D3D_BLOB_PART = 32769i32; pub const D3D_BLOB_TEST_COMPILE_PERF: D3D_BLOB_PART = 32770i32; pub const D3D_BLOB_TEST_COMPILE_REPORT: D3D_BLOB_PART = 32771i32; pub const D3D_COMPILER_VERSION: u32 = 47u32; pub const D3D_COMPRESS_SHADER_KEEP_ALL_PARTS: u32 = 1u32; pub const D3D_DISASM_DISABLE_DEBUG_INFO: u32 = 16u32; pub const D3D_DISASM_ENABLE_COLOR_CODE: u32 = 1u32; pub const D3D_DISASM_ENABLE_DEFAULT_VALUE_PRINTS: u32 = 2u32; pub const D3D_DISASM_ENABLE_INSTRUCTION_CYCLE: u32 = 8u32; pub const D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING: u32 = 4u32; pub const D3D_DISASM_ENABLE_INSTRUCTION_OFFSET: u32 = 32u32; pub const D3D_DISASM_INSTRUCTION_ONLY: u32 = 64u32; pub const D3D_DISASM_PRINT_HEX_LITERALS: u32 = 128u32; pub const D3D_GET_INST_OFFSETS_INCLUDE_NON_EXECUTABLE: u32 = 1u32; #[repr(C)] pub struct D3D_SHADER_DATA { pub pBytecode: *mut ::core::ffi::c_void, pub BytecodeLength: usize, } impl ::core::marker::Copy for D3D_SHADER_DATA {} impl ::core::clone::Clone for D3D_SHADER_DATA { fn clone(&self) -> Self { *self } } #[cfg(feature = "Win32_Foundation")] pub type pD3DCompile = ::core::option::Option<unsafe extern "system" fn(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, pfilename: super::super::super::Foundation::PSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, pentrypoint: super::super::super::Foundation::PSTR, ptarget: super::super::super::Foundation::PSTR, flags1: u32, flags2: u32, ppcode: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT>; #[cfg(feature = "Win32_Foundation")] pub type pD3DDisassemble = ::core::option::Option<unsafe extern "system" fn(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, flags: u32, szcomments: super::super::super::Foundation::PSTR, ppdisassembly: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT>; #[cfg(feature = "Win32_Foundation")] pub type pD3DPreprocess = ::core::option::Option<unsafe extern "system" fn(psrcdata: *const ::core::ffi::c_void, srcdatasize: usize, pfilename: super::super::super::Foundation::PSTR, pdefines: *const super::D3D_SHADER_MACRO, pinclude: super::ID3DInclude, ppcodetext: *mut super::ID3DBlob, pperrormsgs: *mut super::ID3DBlob) -> ::windows_sys::core::HRESULT>;
//! Type aliases for using `deadpool-diesel` with PostgreSQL. /// Connection which is returned by the PostgreSQL pool pub type Connection = crate::Connection<diesel::PgConnection>; /// Manager which is used to create PostgreSQL connections pub type Manager = crate::manager::Manager<diesel::PgConnection>; /// Pool for using `deadpool-diesel` with PostgreSQL pub type Pool = deadpool::managed::Pool<Manager>;
#[macro_use] extern crate criterion; extern crate geo; use criterion::Criterion; use geo::prelude::*; use geo::simplifyvw::SimplifyVWPreserve; use geo::LineString; fn criterion_benchmark(c: &mut Criterion) { c.bench_function("simplify vw simple f32", |bencher| { let points = include!("../src/algorithm/test_fixtures/norway_main.rs"); let ls: LineString<f32> = points.into(); bencher.iter(|| { let _ = ls.simplifyvw(&0.0005); }); }); c.bench_function("simplify vw simple f64", |bencher| { let points = include!("../src/algorithm/test_fixtures/norway_main.rs"); let ls: LineString<f64> = points.into(); bencher.iter(|| { let _ = ls.simplifyvw(&0.0005); }); }); c.bench_function("simplify vwp f32", |bencher| { let points = include!("../src/algorithm/test_fixtures/norway_main.rs"); let ls: LineString<f32> = points.into(); bencher.iter(|| { let _ = ls.simplifyvw_preserve(&0.0005); }); }); } criterion_group!(benches, criterion_benchmark); criterion_main!(benches);
// Copyright 2021 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::backtrace::Backtrace; use std::panic::PanicInfo; use common_base::runtime::LimitMemGuard; use tracing::error; pub fn set_panic_hook() { // Set a panic hook that records the panic as a `tracing` event at the // `ERROR` verbosity level. // // If we are currently in a span when the panic occurred, the logged event // will include the current span, allowing the context in which the panic // occurred to be recorded. std::panic::set_hook(Box::new(|panic| { let _guard = LimitMemGuard::enter_unlimited(); log_panic(panic); })); } pub fn log_panic(panic: &PanicInfo) { let backtrace = Backtrace::force_capture(); let backtrace_str = format!("{:?}", backtrace); eprintln!("{}", panic); eprintln!("{}", backtrace); if let Some(location) = panic.location() { error!( message = %panic, backtrace = %backtrace_str, panic.file = location.file(), panic.line = location.line(), panic.column = location.column(), ); } else { error!(message = %panic, backtrace = %backtrace_str); } }
use nalgebra_glm as glm; use petgraph::{prelude::*, visit::Dfs}; use sepia::app::*; use sepia::{camera::*, gltf::*, shaderprogram::*, skybox::*}; use std::ptr; // TODO: Eventually remove default derivations where not necessary #[derive(Default)] struct MainState { shader_program: ShaderProgram, lamp_program: ShaderProgram, solid_color_program: ShaderProgram, camera: Camera, skybox: Skybox, asset: Option<GltfAsset>, animation_time: f32, } impl State for MainState { fn initialize(&mut self) { self.shader_program = ShaderProgram::new(); self.shader_program .vertex_shader_file("assets/shaders/gltf/gltf.vs.glsl") .fragment_shader_file("assets/shaders/gltf/lit.fs.glsl") .link(); self.solid_color_program = ShaderProgram::new(); self.solid_color_program .vertex_shader_file("assets/shaders/gltf/outline.vs.glsl") .fragment_shader_file("assets/shaders/gltf/outline.fs.glsl") .link(); self.lamp_program = ShaderProgram::new(); self.lamp_program .vertex_shader_file("assets/shaders/gltf/lamp.vs.glsl") .fragment_shader_file("assets/shaders/gltf/lamp.fs.glsl") .link(); self.skybox = Skybox::new(&[ "assets/textures/skyboxes/bluemountains/right.jpg".to_string(), "assets/textures/skyboxes/bluemountains/left.jpg".to_string(), "assets/textures/skyboxes/bluemountains/top.jpg".to_string(), "assets/textures/skyboxes/bluemountains/bottom.jpg".to_string(), "assets/textures/skyboxes/bluemountains/back.jpg".to_string(), "assets/textures/skyboxes/bluemountains/front.jpg".to_string(), ]); // self.asset = Some(GltfAsset::from_file("assets/models/RiggedSimple.glb")); self.asset = Some(GltfAsset::from_file("assets/models/Duck/Duck.gltf")); unsafe { gl::Enable(gl::CULL_FACE); gl::Enable(gl::DEPTH_TEST); gl::DepthFunc(gl::LEQUAL); gl::Enable(gl::STENCIL_TEST); gl::StencilOp(gl::KEEP, gl::KEEP, gl::REPLACE); } } fn handle_events(&mut self, state_data: &mut StateData, event: &glfw::WindowEvent) { match *event { WindowEvent::Key(Key::Escape, _, Action::Press, _) => { state_data.window.set_should_close(true); } WindowEvent::CursorPos(cursor_x, cursor_y) => { let (window_width, window_height) = state_data.window.get_size(); self.camera.process_mouse_movement( (window_width as f32 / 2.0) - cursor_x as f32, (window_height as f32 / 2.0) - cursor_y as f32, ); } _ => (), } } fn update(&mut self, state_data: &mut StateData) { // Update animation transforms // let seconds = state_data.current_time; let asset = self.asset.as_mut().unwrap(); if !asset.animations.is_empty() { self.asset.as_mut().unwrap().animate(self.animation_time); } if state_data.window.get_key(glfw::Key::Left) == glfw::Action::Press { self.animation_time -= 0.01; if self.animation_time < 0.0 { self.animation_time = 0.0; } } if state_data.window.get_key(glfw::Key::Right) == glfw::Action::Press { self.animation_time += 0.01; } if state_data.window.get_key(glfw::Key::W) == glfw::Action::Press { self.camera .translate(CameraDirection::Forward, state_data.delta_time); } if state_data.window.get_key(glfw::Key::A) == glfw::Action::Press { self.camera .translate(CameraDirection::Left, state_data.delta_time); } if state_data.window.get_key(glfw::Key::S) == glfw::Action::Press { self.camera .translate(CameraDirection::Backward, state_data.delta_time); } if state_data.window.get_key(glfw::Key::D) == glfw::Action::Press { self.camera .translate(CameraDirection::Right, state_data.delta_time); } let (window_width, window_height) = state_data.window.get_size(); state_data.window.set_cursor_pos( f64::from(window_width) / 2.0, f64::from(window_height) / 2.0, ); state_data.window.set_cursor_mode(CursorMode::Disabled); } // TODO: Create a shader cache and retrieve the shader to use from there. // Need pbr shaders and need basic shaders fn render(&mut self, state_data: &mut StateData) { let projection = glm::perspective( state_data.aspect_ratio, 90_f32.to_radians(), 0.1_f32, 100000_f32, ); unsafe { gl::StencilMask(0xFF); gl::Clear(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT | gl::STENCIL_BUFFER_BIT); } let view = self.camera.view_matrix(); // Render the asset's scene graphs let asset = self.asset.as_mut().expect("Couldn't get asset!"); for scene in asset.scenes.iter() { for graph in scene.node_graphs.iter() { let mut dfs = Dfs::new(&graph, NodeIndex::new(0)); while let Some(node_index) = dfs.next(&graph) { let global_transform = calculate_global_transform(node_index, graph); // Skinning if let Some(skin) = graph[node_index].skin.as_ref() { for (index, joint) in skin.joints.iter().enumerate() { let joint_global_transform = calculate_global_transform(NodeIndex::new(joint.index), &graph); let parent_global_transform = calculate_global_transform(node_index, &graph); // TODO: This must not be correct, fix it let joint_matrix = // Inverse transform of the node the mesh is attached to // glm::inverse(&parent_global_transform) * // Current global transform of the joint node // joint_global_transform * // Transform of the joint's inverse bind matrix // joint.inverse_bind_matrix; glm::Mat4::identity(); self.shader_program.set_uniform_matrix4x4( &format!("u_jointMatrix[{}]", index), joint_matrix.as_slice(), ); } } // Render with the given transform if let Some(mesh) = graph[node_index].mesh.as_ref() { for primitive_info in mesh.primitives.iter() { if let Some(material_index) = primitive_info.material_index { let material = asset.lookup_material(material_index); let pbr = material.pbr_metallic_roughness(); //let base_color = glm::Vec4::from(pbr.base_color_factor()).xyz(); if !asset.texture_ids.is_empty() { let base_color_index = pbr .base_color_texture() .expect("Couldn't get base color texture!") .texture() .index(); unsafe { gl::BindTexture( gl::TEXTURE_2D, asset.texture_ids[base_color_index], ); } }; self.shader_program .set_uniform_int("material.diffuse_texture", 0); self.shader_program .set_uniform_float("material.shininess", 32.0); } // Flashlight settings self.shader_program.set_uniform_vec3( "spotlight.position", &self.camera.position.as_slice(), ); self.shader_program.set_uniform_vec3( "spotlight.direction", &self.camera.front.as_slice(), ); self.shader_program .set_uniform_float("spotlight.cutOff", 12.5_f32.to_radians().cos()); self.shader_program.set_uniform_float( "spotlight.outerCutOff", 17.5_f32.to_radians().cos(), ); self.shader_program .set_uniform_float("spotlight.constant", 1.0); self.shader_program .set_uniform_float("spotlight.linear", 0.007); self.shader_program .set_uniform_float("spotlight.quadratic", 0.0002); self.shader_program.set_uniform_vec3( "spotlight.ambient", &glm::vec3(0.3, 0.24, 0.14).as_slice(), ); self.shader_program.set_uniform_vec3( "spotlight.diffuse", &glm::vec3(0.7, 0.42, 0.26).as_slice(), ); self.shader_program.set_uniform_vec3( "spotlight.specular", &glm::vec3(0.5, 0.5, 0.5).as_slice(), ); // Directional Light self.shader_program.set_uniform_vec3( "directional_light.direction", &glm::vec3(-0.2, -1.0, -0.3).as_slice(), ); self.shader_program.set_uniform_vec3( "directional_light.ambient", &glm::vec3(0.3, 0.24, 0.14).as_slice(), ); self.shader_program.set_uniform_vec3( "directional_light.diffuse", &glm::vec3(0.7, 0.42, 0.26).as_slice(), ); self.shader_program.set_uniform_vec3( "directional_light.specular", &glm::vec3(0.5, 0.5, 0.5).as_slice(), ); // Point light 1 let point_light_pos1 = glm::vec3(10.0, 15.0, 45.0); let point_light_color1 = glm::vec3(0.0, 1.0, 0.5); let point_light_color1_ambient = point_light_color1 * 0.1; self.shader_program.set_uniform_vec3( "point_lights[0].position", &point_light_pos1.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[0].ambient", &point_light_color1_ambient.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[0].diffuse", &point_light_color1.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[0].specular", &point_light_color1.as_slice(), ); self.shader_program .set_uniform_float("point_lights[0].constant", 1.0); self.shader_program .set_uniform_float("point_lights[0].linear", 0.007); self.shader_program .set_uniform_float("point_lights[0].quadratic", 0.0002); // Point light 2 let point_light_pos2 = glm::vec3(-10.3, 15.3, -10.0); let point_light_color2 = glm::vec3(1.0, 0.0, 0.0); let point_light_color2_ambient = point_light_color2 * 0.1; self.shader_program.set_uniform_vec3( "point_lights[1].position", &point_light_pos2.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[1].ambient", &point_light_color2_ambient.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[1].diffuse", &point_light_color2.as_slice(), ); self.shader_program.set_uniform_vec3( "point_lights[1].specular", &point_light_color2.as_slice(), ); self.shader_program .set_uniform_float("point_lights[1].constant", 1.0); self.shader_program .set_uniform_float("point_lights[1].linear", 0.007); self.shader_program .set_uniform_float("point_lights[1].quadratic", 0.0002); self.shader_program .set_uniform_vec3("view_pos", &self.camera.position.as_slice()); self.shader_program .set_uniform_matrix4x4("view", view.as_slice()); self.shader_program .set_uniform_matrix4x4("projection", projection.as_slice()); self.solid_color_program .set_uniform_matrix4x4("view", view.as_slice()); self.solid_color_program .set_uniform_matrix4x4("projection", projection.as_slice()); unsafe { gl::StencilFunc(gl::ALWAYS, 1, 0xFF); // all fragments should update the stencil buffer gl::StencilMask(0xFF); // enable writing to the stencil buffer } self.shader_program.activate(); for row in 0..10 { for column in 0..10 { self.shader_program.set_uniform_matrix4x4( "model", (glm::translate( &glm::Mat4::identity(), &glm::vec3( row as f32 * -10.0, 0.0, column as f32 * 10.0, ), ) * glm::scale( &glm::Mat4::identity(), &glm::vec3(6.0, 6.0, 6.0), ) * global_transform) .as_slice(), ); self.shader_program.activate(); primitive_info.vao.bind(); unsafe { gl::DrawElements( gl::TRIANGLES, primitive_info.num_indices, gl::UNSIGNED_INT, ptr::null(), ); } } } unsafe { gl::StencilFunc(gl::NOTEQUAL, 1, 0xFF); gl::StencilMask(0x00); gl::Disable(gl::DEPTH_TEST); } self.solid_color_program.activate(); self.solid_color_program.set_uniform_vec3( "highlight", glm::vec3(0.04, 0.28, 0.26).as_slice(), ); for row in 0..10 { for column in 0..10 { self.solid_color_program.set_uniform_matrix4x4( "model", (glm::translate( &glm::Mat4::identity(), &glm::vec3( row as f32 * -10.0, 0.0, column as f32 * 10.0, ), ) * glm::scale( &glm::Mat4::identity(), &glm::vec3(6.0, 6.0, 6.0), ) * global_transform) .as_slice(), ); self.solid_color_program.activate(); primitive_info.vao.bind(); unsafe { gl::DrawElements( gl::TRIANGLES, primitive_info.num_indices, gl::UNSIGNED_INT, ptr::null(), ); } } } unsafe { gl::StencilMask(0xFF); gl::Enable(gl::DEPTH_TEST); } // Lamp 1 let lamp_mvp = projection * view * glm::translate(&glm::Mat4::identity(), &point_light_pos1.xyz()) * glm::scale(&glm::Mat4::identity(), &glm::vec3(2.0, 2.0, 2.0)) * global_transform; self.lamp_program.activate(); self.lamp_program .set_uniform_vec3("lamp_color", &point_light_color1.as_slice()); self.lamp_program .set_uniform_matrix4x4("mvp_matrix", lamp_mvp.as_slice()); primitive_info.vao.bind(); unsafe { gl::DrawElements( gl::TRIANGLES, primitive_info.num_indices, gl::UNSIGNED_INT, ptr::null(), ); } // Lamp 2 let lamp_mvp = projection * view * glm::translate(&glm::Mat4::identity(), &point_light_pos2.xyz()) * glm::scale(&glm::Mat4::identity(), &glm::vec3(2.0, 2.0, 2.0)) * global_transform; self.lamp_program.activate(); self.lamp_program .set_uniform_vec3("lamp_color", &point_light_color2.as_slice()); self.lamp_program .set_uniform_matrix4x4("mvp_matrix", lamp_mvp.as_slice()); primitive_info.vao.bind(); unsafe { gl::DrawElements( gl::TRIANGLES, primitive_info.num_indices, gl::UNSIGNED_INT, ptr::null(), ); } } } } } } } } fn main() { let mut state = MainState::default(); let mut state_machine: Vec<&mut dyn State> = Vec::new(); state_machine.push(&mut state); App::new(state_machine).run(); }
use serde::Deserialize; #[derive(Debug, Deserialize, PartialEq)] pub(crate) struct Element { #[serde(rename = "Element")] pub(crate) name: String, #[serde(rename = "Symbol")] pub(crate) symbol: String, #[serde(rename = "AtomicNumber")] pub(crate) atomic_num: u8, #[serde(rename = "AtomicMass")] pub(crate) mass_per_mole: f64, #[serde(rename = "NumberofNeutrons")] pub(crate) number_neutrons: u8, #[serde(rename = "NumberofProtons")] pub(crate) number_protons: u8, #[serde(rename = "NumberofElectrons")] pub(crate) number_electrons: u8, #[serde(rename = "Period")] pub(crate) period: u8, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "Group")] pub(crate) group: Option<u8>, #[serde(rename = "Phase")] pub(crate) phase: String, #[serde(rename = "Radioactive")] pub(crate)radioactive: String, #[serde(rename = "Natural")] pub(crate) natural: String, #[serde(rename = "Metal")] pub(crate) metal: String, #[serde(rename = "Nonmetal")] pub(crate) nonmetal: String, #[serde(rename = "Metalloid")] pub(crate) metalloid: String, #[serde(rename = "Type")] pub(crate) elem_type: String, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "AtomicRadius")] pub(crate) atomic_radius: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "Electronegativity")] pub(crate)electronegativity: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "FirstIonization")] pub(crate) first_ionization: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "Density")] pub(crate) density: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "MeltingPoint")] pub(crate) melting: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "BoilingPoint")] pub(crate) boiling: Option<f64>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "NumberOfIsotopes")] pub(crate) number_isotopes: Option<u8>, #[serde(rename = "Discoverer")] pub(crate)discoverer: String, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "Year")] pub(crate)year: Option<u16>, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "SpecificHeat")] pub(crate)specific_heat: Option<f64>, #[serde(rename = "NumberofShells")] pub(crate)number_shells: u8, #[serde(deserialize_with = "csv::invalid_option")] #[serde(rename = "NumberofValence")] pub(crate) number_valence: Option<u8>, }
use crate::il; use crate::translator::aarch64::{ register::{get_register, AArch64Register}, unsupported, UnsupportedError, }; type Result<T> = std::result::Result<T, UnsupportedError>; /// Get the scalar for a well-known register. macro_rules! scalar { ("x30") => { // the link register il::scalar("x30", 64) }; ("n") => { il::scalar("n", 1) }; ("z") => { il::scalar("z", 1) }; ("c") => { il::scalar("c", 1) }; ("v") => { il::scalar("v", 1) }; ($x:literal) => { compile_error!(concat!($x, " is not a well-known register")) }; } /// Get the expression representing a well-known register's value. macro_rules! expr { ($x:tt) => { il::Expression::Scalar(scalar!($x)) }; } /// A convenience function for turning unhandled instructions into intrinsics pub(super) fn unhandled_intrinsic( bytes: &[u8], control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) { let block_index = { let block = control_flow_graph.new_block().unwrap(); block.intrinsic(il::Intrinsic::new( instruction.op().to_string(), instruction.to_string(), Vec::new(), None, None, bytes.to_vec(), )); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); } /// A convenience function for turning undefined instructions into intrinsics pub(super) fn undefined_intrinsic(bytes: u32, control_flow_graph: &mut il::ControlFlowGraph) { let block_index = { let block = control_flow_graph.new_block().unwrap(); block.intrinsic(il::Intrinsic::new( ".word", format!(".word {:#x}", bytes), Vec::new(), None, None, bytes.to_le_bytes().to_vec(), )); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); } /// Only supports non-memory operands. /// `out_bits` is only used for zero/sign-extension modifier. fn operand_load( _block: &mut il::Block, opr: &bad64::Operand, out_bits: usize, ) -> Result<il::Expression> { match opr { bad64::Operand::Reg { reg, arrspec: None } => Ok(get_register(*reg)?.get()), bad64::Operand::Reg { reg, arrspec: Some(arrspec), } => { let reg = get_register(*reg)?; let reg_value = reg.get(); assert_eq!(reg.bits(), 128); let (shift, width) = arr_spec_offset_width(arrspec); let value = il::Expression::shr(reg_value, il::expr_const(shift as u64, reg.bits())).unwrap(); Ok(resize_zext(width, value)) } bad64::Operand::Imm32 { imm, shift } => maybe_shift( il::expr_const(imm_to_u64(imm) as u32 as u64, 32), shift.as_ref(), out_bits, ), bad64::Operand::Imm64 { imm, shift } => maybe_shift( il::expr_const(imm_to_u64(imm), 64), shift.as_ref(), out_bits, ), bad64::Operand::ShiftReg { reg, shift: shift_ } => { shift(get_register(*reg)?.get(), shift_, out_bits) } bad64::Operand::Label(imm) => Ok(il::expr_const(imm_to_u64(imm), 64)), bad64::Operand::FImm32(_) | bad64::Operand::SmeTile { .. } | bad64::Operand::AccumArray { .. } | bad64::Operand::IndexedElement { .. } | bad64::Operand::QualReg { .. } | bad64::Operand::MultiReg { .. } | bad64::Operand::SysReg(_) | bad64::Operand::ImplSpec { .. } | bad64::Operand::Cond(_) | bad64::Operand::Name(_) | bad64::Operand::StrImm { .. } => Err(unsupported()), bad64::Operand::MemReg(_) | bad64::Operand::MemOffset { .. } | bad64::Operand::MemPreIdx { .. } | bad64::Operand::MemPostIdxReg(_) | bad64::Operand::MemPostIdxImm { .. } | bad64::Operand::MemExt { .. } => unreachable!("Memory operand is unexpected here"), } } /// Get an immediate operand of type `u64`. Will panic if it's not an immediate /// operand. A signed immediate is bit-cast to an unsigned one. /// /// **Shifted immediates aren't supported.** fn operand_imm_u64(opr: &bad64::Operand) -> u64 { match opr { bad64::Operand::Imm32 { imm, shift: None } | bad64::Operand::Imm64 { imm, shift: None } => { imm_to_u64(imm) } bad64::Operand::Imm32 { shift: Some(_), .. } | bad64::Operand::Imm64 { shift: Some(_), .. } => { unreachable!("unshifted immediate expected") } bad64::Operand::Reg { .. } | bad64::Operand::SmeTile { .. } | bad64::Operand::AccumArray { .. } | bad64::Operand::IndexedElement { .. } | bad64::Operand::ShiftReg { .. } | bad64::Operand::FImm32(_) | bad64::Operand::QualReg { .. } | bad64::Operand::MultiReg { .. } | bad64::Operand::SysReg(_) | bad64::Operand::MemReg(_) | bad64::Operand::MemOffset { .. } | bad64::Operand::MemPreIdx { .. } | bad64::Operand::MemPostIdxReg(_) | bad64::Operand::MemPostIdxImm { .. } | bad64::Operand::MemExt { .. } | bad64::Operand::Label(_) | bad64::Operand::ImplSpec { .. } | bad64::Operand::Cond(_) | bad64::Operand::Name(_) | bad64::Operand::StrImm { .. } => unreachable!("immediate expected"), } } fn operand_store(block: &mut il::Block, opr: &bad64::Operand, value: il::Expression) -> Result<()> { match opr { bad64::Operand::Reg { reg, arrspec: None } => get_register(*reg)?.set(block, value), bad64::Operand::Reg { reg, arrspec: Some(arrspec), } => { let reg = get_register(*reg)?; assert_eq!(reg.bits(), 128); let (shift, width) = arr_spec_offset_width(arrspec); let is_indexed = is_arr_spec_indexed(arrspec); if is_indexed { // Replace only the selected element. First mask the unselected // bits of the old value... let masked_lower = if shift > 0 { assert!(shift < reg.bits()); Some( il::Expression::zext( reg.bits(), il::Expression::trun(shift, reg.get()).unwrap(), ) .unwrap(), ) } else { None }; let masked_upper = if shift + width < reg.bits() { Some( il::Expression::shl( il::Expression::shr( reg.get(), il::expr_const((shift + width) as u64, reg.bits()), ) .unwrap(), il::expr_const((shift + width) as u64, reg.bits()), ) .unwrap(), ) } else { None }; let masked = match (masked_lower, masked_upper) { (Some(x), Some(y)) => il::Expression::or(x, y).unwrap(), (Some(x), None) | (None, Some(x)) => x, (None, None) => { reg.set(block, resize_zext(reg.bits(), value)); return Ok(()); } }; // Shift the new value into the desired place... let replacement = if value.bits() <= width { value } else { il::Expression::trun(width, value).unwrap() }; let replacement = il::Expression::shl( resize_zext(reg.bits(), replacement), il::expr_const(shift as u64, reg.bits()), ) .unwrap(); // And construct the final value. reg.set(block, il::Expression::or(masked, replacement).unwrap()); } else { // Replace the whole with zero extension reg.set(block, resize_zext(reg.bits(), value)); } } bad64::Operand::ShiftReg { .. } | bad64::Operand::Imm32 { .. } | bad64::Operand::Imm64 { .. } | bad64::Operand::FImm32(_) => { panic!("Can't store to operand `{}`", opr) } bad64::Operand::QualReg { .. } | bad64::Operand::MultiReg { .. } | bad64::Operand::SysReg(_) | bad64::Operand::MemReg(_) | bad64::Operand::MemOffset { .. } | bad64::Operand::MemPreIdx { .. } | bad64::Operand::MemPostIdxReg(_) | bad64::Operand::MemPostIdxImm { .. } | bad64::Operand::MemExt { .. } | bad64::Operand::Label(_) | bad64::Operand::ImplSpec { .. } | bad64::Operand::Cond(_) | bad64::Operand::Name(_) | bad64::Operand::StrImm { .. } | bad64::Operand::SmeTile { .. } | bad64::Operand::AccumArray { .. } | bad64::Operand::IndexedElement { .. } => return Err(unsupported()), } Ok(()) } /// Only supports non-memory operands. /// `out_bits` is only used for zero/sign-extension modifier. fn mem_operand_address(opr: &bad64::Operand) -> Result<(il::Expression, MemOperandSideeffect)> { let (address_expr, sideeffect) = match opr { bad64::Operand::MemReg(reg) => (get_register(*reg)?.get(), MemOperandSideeffect::None), bad64::Operand::MemOffset { reg, offset, mul_vl: false, arrspec: None, } => { let reg = get_register(*reg)?; let offset = il::expr_const(imm_to_u64(offset), 64); let indexed_address = il::Expression::add(reg.get(), offset).unwrap(); (indexed_address, MemOperandSideeffect::None) } bad64::Operand::MemPreIdx { reg, imm } => { let reg = get_register(*reg)?; let imm = il::expr_const(imm_to_u64(imm), 64); let indexed_address = il::Expression::add(reg.get(), imm).unwrap(); ( indexed_address.clone(), MemOperandSideeffect::Assign(reg, indexed_address), ) } bad64::Operand::MemPostIdxReg([reg, reg_offset]) => { // TODO: Test this using `LD1R` let reg = get_register(*reg)?; let reg_offset = get_register(*reg_offset)?.get(); let indexed_address = il::Expression::add(reg.get(), reg_offset).unwrap(); ( reg.get(), MemOperandSideeffect::Assign(reg, indexed_address), ) } bad64::Operand::MemPostIdxImm { reg, imm } => { let reg = get_register(*reg)?; let imm = il::expr_const(imm_to_u64(imm), 64); let indexed_address = il::Expression::add(reg.get(), imm).unwrap(); ( reg.get(), MemOperandSideeffect::Assign(reg, indexed_address), ) } bad64::Operand::MemExt { regs: [reg, reg_offset], shift: shift_, arrspec: None, } => { let reg = get_register(*reg)?.get(); let reg_offset = if let Some(shift_) = shift_ { shift(get_register(*reg_offset)?.get(), shift_, 64)? } else { get_register(*reg_offset)?.get() }; let indexed_address = il::Expression::add(reg, reg_offset).unwrap(); (indexed_address, MemOperandSideeffect::None) } bad64::Operand::MemOffset { mul_vl: true, .. } | bad64::Operand::SmeTile { .. } | bad64::Operand::AccumArray { .. } | bad64::Operand::IndexedElement { .. } | bad64::Operand::MemOffset { arrspec: Some(_), .. } | bad64::Operand::MemExt { arrspec: Some(_), .. } => return Err(unsupported()), bad64::Operand::Reg { .. } | bad64::Operand::Imm32 { .. } | bad64::Operand::Imm64 { .. } | bad64::Operand::ShiftReg { .. } | bad64::Operand::FImm32(_) | bad64::Operand::QualReg { .. } | bad64::Operand::MultiReg { .. } | bad64::Operand::SysReg(_) | bad64::Operand::ImplSpec { .. } | bad64::Operand::Cond(_) | bad64::Operand::Label(_) | bad64::Operand::Name(_) | bad64::Operand::StrImm { .. } => unreachable!("Memory operand is expected here"), }; Ok((address_expr, sideeffect)) } #[must_use] enum MemOperandSideeffect { None, Assign(&'static AArch64Register, il::Expression), } impl MemOperandSideeffect { fn apply(self, block: &mut il::Block) { if let MemOperandSideeffect::Assign(scalar, value) = self { scalar.set(block, value); } } } fn operand_storing_width(opr: &bad64::Operand) -> Result<usize> { match opr { bad64::Operand::Reg { reg, arrspec: None } => Ok(get_register(*reg)?.bits()), bad64::Operand::Reg { reg, arrspec: Some(arr_spec), } => match arr_spec { bad64::ArrSpec::Full(_) => Ok(get_register(*reg)?.bits()), bad64::ArrSpec::TwoDoubles(_) | bad64::ArrSpec::OneDouble(_) => Ok(64), bad64::ArrSpec::FourSingles(_) | bad64::ArrSpec::TwoSingles(_) | bad64::ArrSpec::OneSingle(_) => Ok(32), bad64::ArrSpec::EightHalves(_) | bad64::ArrSpec::FourHalves(_) | bad64::ArrSpec::TwoHalves(_) | bad64::ArrSpec::OneHalf(_) => Ok(16), bad64::ArrSpec::SixteenBytes(_) | bad64::ArrSpec::EightBytes(_) | bad64::ArrSpec::FourBytes(_) | bad64::ArrSpec::OneByte(_) => Ok(8), }, bad64::Operand::ShiftReg { .. } | bad64::Operand::Imm32 { .. } | bad64::Operand::Imm64 { .. } | bad64::Operand::FImm32(_) => { panic!("Can't store to operand `{}`", opr) } bad64::Operand::QualReg { .. } | bad64::Operand::MultiReg { .. } | bad64::Operand::SysReg(_) | bad64::Operand::MemReg(_) | bad64::Operand::MemOffset { .. } | bad64::Operand::MemPreIdx { .. } | bad64::Operand::MemPostIdxReg(_) | bad64::Operand::MemPostIdxImm { .. } | bad64::Operand::MemExt { .. } | bad64::Operand::Label(_) | bad64::Operand::ImplSpec { .. } | bad64::Operand::Cond(_) | bad64::Operand::Name(_) | bad64::Operand::StrImm { .. } | bad64::Operand::SmeTile { .. } | bad64::Operand::AccumArray { .. } | bad64::Operand::IndexedElement { .. } => Err(unsupported()), } } fn is_arr_spec_indexed(bad64_arrspec: &bad64::ArrSpec) -> bool { match bad64_arrspec { bad64::ArrSpec::Full(i) | bad64::ArrSpec::TwoDoubles(i) | bad64::ArrSpec::FourSingles(i) | bad64::ArrSpec::EightHalves(i) | bad64::ArrSpec::SixteenBytes(i) | bad64::ArrSpec::OneDouble(i) | bad64::ArrSpec::TwoSingles(i) | bad64::ArrSpec::FourHalves(i) | bad64::ArrSpec::EightBytes(i) | bad64::ArrSpec::OneSingle(i) | bad64::ArrSpec::TwoHalves(i) | bad64::ArrSpec::FourBytes(i) | bad64::ArrSpec::OneHalf(i) | bad64::ArrSpec::OneByte(i) => i.is_some(), } } fn arr_spec_offset_width(bad64_arrspec: &bad64::ArrSpec) -> (usize, usize) { match *bad64_arrspec { bad64::ArrSpec::Full(_) | bad64::ArrSpec::TwoDoubles(None) | bad64::ArrSpec::FourSingles(None) | bad64::ArrSpec::EightHalves(None) | bad64::ArrSpec::SixteenBytes(None) => (0, 128), bad64::ArrSpec::OneDouble(None) | bad64::ArrSpec::TwoSingles(None) | bad64::ArrSpec::FourHalves(None) | bad64::ArrSpec::EightBytes(None) => (0, 64), bad64::ArrSpec::OneSingle(None) | bad64::ArrSpec::TwoHalves(None) | bad64::ArrSpec::FourBytes(None) => (0, 32), bad64::ArrSpec::OneHalf(None) => (0, 16), bad64::ArrSpec::OneByte(None) => (0, 8), bad64::ArrSpec::TwoDoubles(Some(i)) | bad64::ArrSpec::OneDouble(Some(i)) => { (i as usize * 64, 64) } bad64::ArrSpec::FourSingles(Some(i)) | bad64::ArrSpec::TwoSingles(Some(i)) | bad64::ArrSpec::OneSingle(Some(i)) => (i as usize * 32, 32), bad64::ArrSpec::EightHalves(Some(i)) | bad64::ArrSpec::FourHalves(Some(i)) | bad64::ArrSpec::TwoHalves(Some(i)) | bad64::ArrSpec::OneHalf(Some(i)) => (i as usize * 16, 16), bad64::ArrSpec::SixteenBytes(Some(i)) | bad64::ArrSpec::EightBytes(Some(i)) | bad64::ArrSpec::FourBytes(Some(i)) | bad64::ArrSpec::OneByte(Some(i)) => (i as usize * 8, 8), } } fn resize_zext(bits: usize, value: il::Expression) -> il::Expression { match bits.cmp(&value.bits()) { std::cmp::Ordering::Equal => value, std::cmp::Ordering::Greater => il::Expression::zext(bits, value).unwrap(), std::cmp::Ordering::Less => il::Expression::trun(bits, value).unwrap(), } } fn maybe_shift( value: il::Expression, bad64_shift: Option<&bad64::Shift>, out_bits: usize, ) -> Result<il::Expression> { if let Some(bad64_shift) = bad64_shift { shift(value, bad64_shift, out_bits) } else { Ok(value) } } fn shift( value: il::Expression, bad64_shift: &bad64::Shift, out_bits: usize, ) -> Result<il::Expression> { let (unsigned, len, shift_amount) = match *bad64_shift { // ShiftReg bad64::Shift::LSL(amount) => { return Ok(lsl(value, il::expr_const(amount.into(), out_bits))) } bad64::Shift::LSR(amount) => { return Ok(lsr(value, il::expr_const(amount.into(), out_bits))) } bad64::Shift::ASR(amount) => { return Ok(asr(value, il::expr_const(amount.into(), out_bits))) } bad64::Shift::ROR(amount) => { return Ok(ror(value, il::expr_const(amount.into(), out_bits))) } // AdvSIMDExpandImm with `op == 0 && cmode == 110x` bad64::Shift::MSL(_amount) => return Err(unsupported()), // ExtendReg bad64::Shift::SXTB(amount) => (false, 8, amount), bad64::Shift::SXTH(amount) => (false, 16, amount), bad64::Shift::SXTW(amount) => (false, 32, amount), bad64::Shift::SXTX(amount) => (false, 64, amount), bad64::Shift::UXTB(amount) => (true, 8, amount), bad64::Shift::UXTH(amount) => (true, 16, amount), bad64::Shift::UXTW(amount) => (true, 32, amount), bad64::Shift::UXTX(amount) => (true, 64, amount), }; let extended = if len < value.bits() { il::Expression::trun(len, value).unwrap() } else { value }; let extended = if len < out_bits { if unsigned { il::Expression::zext(out_bits, extended).unwrap() } else { il::Expression::sext(out_bits, extended).unwrap() } } else { extended }; Ok(il::Expression::shl(extended, il::expr_const(shift_amount.into(), out_bits)).unwrap()) } /// Logical shift left fn lsl(value: il::Expression, shift: il::Expression) -> il::Expression { il::Expression::shl(value, shift).unwrap() } /// Logical shift right fn lsr(value: il::Expression, shift: il::Expression) -> il::Expression { il::Expression::shr(value, shift).unwrap() } /// Arithmetic shift right fn asr(value: il::Expression, shift: il::Expression) -> il::Expression { il::Expression::sra(value, shift).unwrap() } /// Rotate right fn ror(value: il::Expression, shift: il::Expression) -> il::Expression { let shift_right_bits = shift; let shift_left_bits = il::Expression::sub( il::expr_const(value.bits() as u64, value.bits()), shift_right_bits.clone(), ) .unwrap(); il::Expression::or( il::Expression::shl(value.clone(), shift_left_bits).unwrap(), il::Expression::shr(value, shift_right_bits).unwrap(), ) .unwrap() } fn imm_to_u64(imm: &bad64::Imm) -> u64 { match *imm { bad64::Imm::Signed(x) => x as u64, bad64::Imm::Unsigned(x) => x, } } pub(super) fn add( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let lhs = operand_load(block, &instruction.operands()[1], bits)?; let rhs = operand_load(block, &instruction.operands()[2], bits)?; // perform operation let src = il::Expression::add(lhs, rhs).unwrap(); // store result operand_store(block, &instruction.operands()[0], src)?; block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn adds( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let lhs = operand_load(block, &instruction.operands()[1], bits)?; let rhs = operand_load(block, &instruction.operands()[2], bits)?; // perform operation let result = il::Expression::add(lhs.clone(), rhs.clone()).unwrap(); let unsigned_sum = il::Expression::add( il::Expression::zext(72, lhs.clone()).unwrap(), il::Expression::zext(72, rhs.clone()).unwrap(), ) .unwrap(); let signed_sum = il::Expression::add( il::Expression::sext(72, lhs).unwrap(), il::Expression::sext(72, rhs).unwrap(), ) .unwrap(); let n = il::Expression::cmplts(result.clone(), il::expr_const(0, bits)).unwrap(); let z = il::Expression::cmpeq(result.clone(), il::expr_const(0, bits)).unwrap(); let c = il::Expression::cmpneq( il::Expression::zext(72, result.clone()).unwrap(), unsigned_sum, ) .unwrap(); let v = il::Expression::cmpneq( il::Expression::sext(72, result.clone()).unwrap(), signed_sum, ) .unwrap(); // store result operand_store(block, &instruction.operands()[0], result)?; block.assign(scalar!("n"), n); block.assign(scalar!("z"), z); block.assign(scalar!("c"), c); block.assign(scalar!("v"), v); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn b( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, ) -> Result<()> { let dst; let block_index = { let block = instruction_graph.new_block().unwrap(); // get operands dst = operand_load(block, &instruction.operands()[0], 64)? .get_constant() .expect("branch target is not constant") .value_u64() .expect("branch target does not fit in 64 bits"); block.index() }; instruction_graph.set_entry(block_index).unwrap(); instruction_graph.set_exit(block_index).unwrap(); successors.push((dst, None)); Ok(()) } pub(super) fn b_cc( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, cond: u8, ) -> Result<()> { let (dst, cond_true_false); if (cond & 0b1110) == 0b1110 { return b(instruction_graph, successors, instruction); } let block_index = { let block = instruction_graph.new_block().unwrap(); // get operands dst = operand_load(block, &instruction.operands()[0], 64)? .get_constant() .expect("branch target is not constant") .value_u64() .expect("branch target does not fit in 64 bits"); // condition let cond_true = match (cond & 0b1110) >> 1 { 0b000 => expr!("z"), 0b001 => expr!("c"), 0b010 => expr!("n"), 0b011 => expr!("v"), 0b100 => il::Expression::and( expr!("c"), il::Expression::cmpneq(expr!("z"), il::expr_const(1, 1)).unwrap(), ) .unwrap(), 0b101 => il::Expression::cmpeq(expr!("n"), expr!("v")).unwrap(), 0b110 => il::Expression::and( il::Expression::cmpeq(expr!("n"), expr!("v")).unwrap(), il::Expression::cmpneq(expr!("z"), il::expr_const(1, 1)).unwrap(), ) .unwrap(), 0b111 => unreachable!(), // handled above _ => unreachable!(), }; let cond_false = il::Expression::cmpneq(cond_true.clone(), il::expr_const(1, 1)).unwrap(); cond_true_false = if (cond & 1) != 0 && cond != 0b1111 { (cond_false, cond_true) } else { (cond_true, cond_false) }; block.index() }; instruction_graph.set_entry(block_index).unwrap(); instruction_graph.set_exit(block_index).unwrap(); let (cond_true, cond_false) = cond_true_false; successors.push((dst, Some(cond_true))); successors.push((instruction.address() + 4, Some(cond_false))); Ok(()) } pub(super) fn br( instruction_graph: &mut il::ControlFlowGraph, _successors: &mut [(u64, Option<il::Expression>)], instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = instruction_graph.new_block().unwrap(); // get operands let dst = operand_load(block, &instruction.operands()[0], 64)?; block.branch(dst); block.index() }; instruction_graph.set_entry(block_index).unwrap(); instruction_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn bl( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let dst = operand_load(block, &instruction.operands()[0], 64)?; block.assign( scalar!("x30"), il::expr_const(instruction.address().wrapping_add(4), 64), ); block.branch(dst); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) use bl as blr; fn cbz_cbnz_tbz_tbnz( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, branch_if_zero: bool, test_bit: bool, ) -> Result<()> { let (dst, mut cond_true, mut cond_false); let opr_value = 0; let opr_bit = test_bit.then_some(1); let opr_target = [1, 2][test_bit as usize]; let block_index = { let block = instruction_graph.new_block().unwrap(); // get operands dst = operand_load(block, &instruction.operands()[opr_target], 64)? .get_constant() .expect("branch target is not constant") .value_u64() .expect("branch target does not fit in 64 bits"); let bits = operand_storing_width(&instruction.operands()[opr_value])?; let value = operand_load(block, &instruction.operands()[opr_value], bits)?; let value = if let Some(opr_bit) = opr_bit { // specific bit let bit = operand_imm_u64(&instruction.operands()[opr_bit]); assert!(bit < bits as u64); il::Expression::and(value, il::expr_const(1 << bit, bits)).unwrap() } else { // any bit set value }; cond_true = il::Expression::cmpneq(value.clone(), il::expr_const(0, bits)).unwrap(); cond_false = il::Expression::cmpeq(value, il::expr_const(0, bits)).unwrap(); if branch_if_zero { std::mem::swap(&mut cond_true, &mut cond_false); } block.index() }; instruction_graph.set_entry(block_index).unwrap(); instruction_graph.set_exit(block_index).unwrap(); successors.push((dst, Some(cond_true))); successors.push((instruction.address() + 4, Some(cond_false))); Ok(()) } pub(super) fn cbnz( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, ) -> Result<()> { cbz_cbnz_tbz_tbnz(instruction_graph, successors, instruction, false, false) } pub(super) fn cbz( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, ) -> Result<()> { cbz_cbnz_tbz_tbnz(instruction_graph, successors, instruction, true, false) } fn temp0(instruction: &bad64::Instruction, bits: usize) -> il::Scalar { il::Scalar::temp(instruction.address(), bits) } fn temp1(instruction: &bad64::Instruction, bits: usize) -> il::Scalar { il::Scalar::temp(instruction.address() + 1, bits) } pub(super) fn ldp( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let (address, sideeffect) = mem_operand_address(&instruction.operands()[2])?; // perform operation let bits = operand_storing_width(&instruction.operands()[0])?; let temp0 = temp0(instruction, bits); let temp1 = temp1(instruction, bits); block.load(temp0.clone(), address.clone()); block.load( temp1.clone(), il::Expression::add(address, il::expr_const(bits as u64 / 8, 64)).unwrap(), ); // store result operand_store( block, &instruction.operands()[0], il::Expression::Scalar(temp0), )?; operand_store( block, &instruction.operands()[1], il::Expression::Scalar(temp1), )?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldpsw( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let (address, sideeffect) = mem_operand_address(&instruction.operands()[2])?; // perform operation let temp0 = temp0(instruction, 32); let temp1 = temp1(instruction, 32); block.load(temp0.clone(), address.clone()); block.load( temp1.clone(), il::Expression::add(address, il::expr_const(4, 64)).unwrap(), ); // store result operand_store( block, &instruction.operands()[0], il::Expression::sext(64, il::Expression::Scalar(temp0)).unwrap(), )?; operand_store( block, &instruction.operands()[1], il::Expression::sext(64, il::Expression::Scalar(temp1)).unwrap(), )?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } // TODO: Cache hint pub(super) use ldp as ldnp; // TODO: Memory ordering pub(super) use { ldr as ldar, ldr as ldlar, ldrb as ldarb, ldrb as ldlarb, ldrh as ldarh, ldrh as ldlarh, }; pub(super) fn ldr( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let bits = operand_storing_width(&instruction.operands()[0])?; let temp = temp0(instruction, bits); block.load(temp.clone(), address); // store result operand_store( block, &instruction.operands()[0], il::Expression::Scalar(temp), )?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldrb( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let temp = temp0(instruction, 8); block.load(temp.clone(), address); // store result operand_store( block, &instruction.operands()[0], il::Expression::Scalar(temp), )?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldrh( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let temp = temp0(instruction, 16); block.load(temp.clone(), address); // store result operand_store( block, &instruction.operands()[0], il::Expression::Scalar(temp), )?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldrsb( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let bits = operand_storing_width(&instruction.operands()[0])?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let temp = temp0(instruction, 8); block.load(temp.clone(), address); let extended = il::Expression::sext(bits, il::Expression::Scalar(temp)).unwrap(); // store result operand_store(block, &instruction.operands()[0], extended)?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldrsh( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let bits = operand_storing_width(&instruction.operands()[0])?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let temp = temp0(instruction, 16); block.load(temp.clone(), address); let extended = il::Expression::sext(bits, il::Expression::Scalar(temp)).unwrap(); // store result operand_store(block, &instruction.operands()[0], extended)?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ldrsw( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operand let bits = operand_storing_width(&instruction.operands()[0])?; assert_eq!(bits, 64); let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation let temp = temp0(instruction, 32); block.load(temp.clone(), address); let extended = il::Expression::sext(bits, il::Expression::Scalar(temp)).unwrap(); // store result operand_store(block, &instruction.operands()[0], extended)?; // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn mov( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let rhs = operand_load(block, &instruction.operands()[1], bits)?; // store result operand_store(block, &instruction.operands()[0], rhs)?; block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn nop( control_flow_graph: &mut il::ControlFlowGraph, _instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); block.nop(); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn ret( instruction_graph: &mut il::ControlFlowGraph, _successors: &mut [(u64, Option<il::Expression>)], _instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = instruction_graph.new_block().unwrap(); block.branch(expr!("x30")); block.index() }; instruction_graph.set_entry(block_index).unwrap(); instruction_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn stp( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let value0 = operand_load(block, &instruction.operands()[0], bits)?; let value1 = operand_load(block, &instruction.operands()[1], bits)?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[2])?; // perform operation block.store(address.clone(), value0); block.store( il::Expression::add(address, il::expr_const(bits as u64 / 8, 64)).unwrap(), value1, ); // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } // TODO: Cache hint pub(super) use stp as stnp; // TODO: Memory ordering pub(super) use { str as stlr, str as stllr, strb as stlrb, strb as stllrb, strh as stlrh, strh as stllrh, }; pub(super) fn str( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let value = operand_load(block, &instruction.operands()[0], bits)?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation block.store(address, value); // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn strb( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let value = operand_load(block, &instruction.operands()[0], 32)?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation block.store(address, il::Expression::trun(8, value).unwrap()); // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn strh( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let value = operand_load(block, &instruction.operands()[0], 32)?; let (address, sideeffect) = mem_operand_address(&instruction.operands()[1])?; // perform operation block.store(address, il::Expression::trun(16, value).unwrap()); // write-back sideeffect.apply(block); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn sub( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let lhs = operand_load(block, &instruction.operands()[1], bits)?; let rhs = operand_load(block, &instruction.operands()[2], bits)?; // perform operation let src = il::Expression::sub(lhs, rhs).unwrap(); // store result operand_store(block, &instruction.operands()[0], src)?; block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn subs( control_flow_graph: &mut il::ControlFlowGraph, instruction: &bad64::Instruction, ) -> Result<()> { let block_index = { let block = control_flow_graph.new_block().unwrap(); // get operands let bits = operand_storing_width(&instruction.operands()[0])?; let lhs = operand_load(block, &instruction.operands()[1], bits)?; let rhs = operand_load(block, &instruction.operands()[2], bits)?; // perform operation let result = il::Expression::sub(lhs.clone(), rhs.clone()).unwrap(); let unsigned_sum = il::Expression::sub( il::Expression::zext(72, lhs.clone()).unwrap(), il::Expression::zext(72, rhs.clone()).unwrap(), ) .unwrap(); let signed_sum = il::Expression::sub( il::Expression::sext(72, lhs).unwrap(), il::Expression::sext(72, rhs).unwrap(), ) .unwrap(); let n = il::Expression::cmplts(result.clone(), il::expr_const(0, bits)).unwrap(); let z = il::Expression::cmpeq(result.clone(), il::expr_const(0, bits)).unwrap(); let c = il::Expression::cmpneq( il::Expression::zext(72, result.clone()).unwrap(), unsigned_sum, ) .unwrap(); let v = il::Expression::cmpneq( il::Expression::sext(72, result.clone()).unwrap(), signed_sum, ) .unwrap(); // store result operand_store(block, &instruction.operands()[0], result)?; block.assign(scalar!("n"), n); block.assign(scalar!("z"), z); block.assign(scalar!("c"), c); block.assign(scalar!("v"), v); block.index() }; control_flow_graph.set_entry(block_index).unwrap(); control_flow_graph.set_exit(block_index).unwrap(); Ok(()) } pub(super) fn tbnz( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, ) -> Result<()> { cbz_cbnz_tbz_tbnz(instruction_graph, successors, instruction, false, true) } pub(super) fn tbz( instruction_graph: &mut il::ControlFlowGraph, successors: &mut Vec<(u64, Option<il::Expression>)>, instruction: &bad64::Instruction, ) -> Result<()> { cbz_cbnz_tbz_tbnz(instruction_graph, successors, instruction, true, true) } // TODO: Rest of the owl
pub mod steps; pub mod tp;
// Copyright 2021 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::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::sync::Arc; use common_base::base::tokio::sync::Mutex; use common_meta_raft_store::config::RaftConfig; use common_meta_raft_store::state_machine::StateMachine; pub use common_meta_sled_store::init_temp_sled_db; use common_meta_stoerr::MetaStorageError; use common_meta_types::anyerror::AnyError; use once_cell::sync::Lazy; use tracing::warn; /// Local storage that provides the API defined by `kvapi::KVApi+SchemaApi`. /// /// It is just a wrapped `StateMachine`, which is the same one used by raft driven metasrv. /// For a local kv, there is no distributed WAL involved, /// thus it just bypasses the raft log and operate directly on the `StateMachine`. /// /// Since `StateMachine` is backed with sled::Tree, this impl has the same limitation as metasrv: /// - A sled::Db has to be a singleton, according to sled doc. /// - Every unit test has to generate a unique sled::Tree name to create a `MetaEmbedded`. #[derive(Clone)] pub struct MetaEmbedded { pub(crate) inner: Arc<Mutex<StateMachine>>, } static GLOBAL_META_EMBEDDED: Lazy<Arc<Mutex<Option<Arc<MetaEmbedded>>>>> = Lazy::new(|| Arc::new(Mutex::new(None))); impl MetaEmbedded { /// Creates a kvapi::KVApi impl backed with a `StateMachine`. /// /// A MetaEmbedded is identified by the `name`. /// Caveat: Two instances with the same `name` reference to the same underlying sled::Tree. /// /// One of the following has to be called to initialize a process-wise sled::Db, /// before using `MetaEmbedded`: /// - `common_meta_sled_store::init_sled_db` /// - `common_meta_sled_store::init_temp_sled_db` pub async fn new(name: &str) -> Result<MetaEmbedded, MetaStorageError> { let mut config = RaftConfig { sled_tree_prefix: format!("{}-local-kv", name), ..Default::default() }; if cfg!(target_os = "macos") { warn!("Disabled fsync for meta data tests. fsync on mac is quite slow"); config.no_sync = true; } let sm = StateMachine::open(&config, 0).await?; Ok(MetaEmbedded { inner: Arc::new(Mutex::new(sm)), }) } /// Creates a kvapi::KVApi impl with a random and unique name. pub async fn new_temp() -> Result<MetaEmbedded, MetaStorageError> { let temp_dir = tempfile::tempdir().map_err(|e| MetaStorageError::SledError(AnyError::new(&e)))?; init_temp_sled_db(temp_dir); // generate a unique id as part of the name of sled::Tree static GLOBAL_SEQ: AtomicUsize = AtomicUsize::new(0); let x = GLOBAL_SEQ.fetch_add(1, Ordering::SeqCst); let id = 29000_u64 + (x as u64); let name = format!("temp-{}", id); let m = Self::new(&name).await?; Ok(m) } /// Initialize a sled db to store embedded meta data. /// Initialize a global embedded meta store. /// The data in `path` won't be removed after program exit. pub async fn init_global_meta_store(path: String) -> Result<(), MetaStorageError> { common_meta_sled_store::init_sled_db(path); { let mut m = GLOBAL_META_EMBEDDED.as_ref().lock().await; let r = m.as_ref(); if r.is_none() { let meta = MetaEmbedded::new("global").await?; let meta = Arc::new(meta); *m = Some(meta); return Ok(()); } } panic!("global meta store can not init twice"); } /// If global meta store is initialized, return it(production use). /// Otherwise, return a meta store backed with temp dir for test. pub async fn get_meta() -> Result<Arc<MetaEmbedded>, MetaStorageError> { { let m = GLOBAL_META_EMBEDDED.as_ref().lock().await; let r = m.as_ref(); if let Some(x) = r { return Ok(x.clone()); } } let meta = MetaEmbedded::new_temp().await?; let meta = Arc::new(meta); Ok(meta) } }
// ignore-compare-mode-nll // revisions: base nll // [nll]compile-flags: -Zborrowck=mir // edition:2018 fn require_static<T: 'static>(val: T) -> T { //[base]~^ NOTE 'static` lifetime requirement introduced by this bound val } struct Problem; impl Problem { pub async fn start(&self) { //[base]~^ ERROR E0759 //[base]~| NOTE this data with an anonymous lifetime `'_` //[base]~| NOTE in this expansion of desugaring of `async` block or function //[nll]~^^^^ NOTE let's call //[nll]~| NOTE `self` is a reference require_static(async move { //[base]~^ NOTE ...and is required to live as long as `'static` here //[nll]~^^ ERROR borrowed data escapes //[nll]~| NOTE `self` escapes //[nll]~| NOTE argument requires &self; //[base]~ NOTE ...is used here... }); } } fn main() {}
//! Tests auto-converted from "sass-spec/spec/values" //! version 0f59164a, 2019-02-01 17:21:13 -0800. //! See <https://github.com/sass/sass-spec> for source material.\n //! The following tests are excluded from conversion: //! ["ids", "numbers/units/multiple"] extern crate rsass; use rsass::{compile_scss, OutputStyle}; mod colors; mod identifiers; // Ignoring "ids", not expected to work yet. mod lists; mod maps; mod numbers; fn rsass(input: &str) -> Result<String, String> { compile_scss(input.as_bytes(), OutputStyle::Expanded) .map_err(|e| format!("rsass failed: {}", e)) .and_then(|s| String::from_utf8(s).map_err(|e| format!("{:?}", e))) }
//! Contains the ffi-safe equivalent of `std::boxed::Box`. use std::{ borrow::{Borrow, BorrowMut}, error::Error as StdError, future::Future, hash::Hasher, io::{self, BufRead, IoSlice, IoSliceMut, Read, Seek, Write}, iter::FusedIterator, marker::{PhantomData, Unpin}, mem::ManuallyDrop, ops::DerefMut, pin::Pin, ptr::{self, NonNull}, task::{Context, Poll}, }; #[allow(unused_imports)] use core_extensions::SelfOps; use crate::{ marker_type::NonOwningPhantom, pointer_trait::{ AsMutPtr, AsPtr, CallReferentDrop, CanTransmuteElement, Deallocate, GetPointerKind, OwnedPointer, PK_SmartPointer, }, prefix_type::WithMetadata, sabi_types::MovePtr, std_types::utypeid::{new_utypeid, UTypeId}, traits::IntoReprRust, }; // #[cfg(test)] #[cfg(all(test, not(feature = "only_new_tests")))] mod test; mod private { use super::*; /// Ffi-safe equivalent of `std::box::Box`. /// /// # Example /// /// Declaring a recursive datatype. /// /// ``` /// use abi_stable::{ /// std_types::{RBox, RString}, /// StableAbi, /// }; /// /// #[repr(u8)] /// #[derive(StableAbi)] /// enum Command { /// SendProduct { /// id: u64, /// }, /// GoProtest { /// cause: RString, /// place: RString, /// }, /// SendComplaint { /// cause: RString, /// website: RString, /// }, /// WithMetadata { /// command: RBox<Command>, /// metadata: RString, /// }, /// } /// /// ``` /// #[repr(C)] #[derive(StableAbi)] pub struct RBox<T> { data: NonNull<T>, vtable: BoxVtable_Ref<T>, _marker: PhantomData<T>, } impl<T> RBox<T> { /// Constucts an `RBox<T>` from a value. /// /// # Example /// /// ``` /// use abi_stable::std_types::RBox; /// /// let baux = RBox::new(100); /// assert_eq!(*baux, 100); /// /// ``` pub fn new(value: T) -> Self { Box::new(value).piped(RBox::from_box) } /// Constructs a `Pin<RBox<T>>`. /// pub fn pin(value: T) -> Pin<RBox<T>> { RBox::new(value).into_pin() } /// Converts a `Box<T>` to an `RBox<T>`, reusing its heap allocation. /// /// # Example /// /// ``` /// use abi_stable::std_types::RBox; /// /// let baux = Box::new(200); /// let baux = RBox::from_box(baux); /// assert_eq!(*baux, 200); /// /// ``` pub fn from_box(p: Box<T>) -> RBox<T> { RBox { data: unsafe { NonNull::new_unchecked(Box::into_raw(p)) }, vtable: VTableGetter::<T>::LIB_VTABLE, _marker: PhantomData, } } /// Constructs a `Box<T>` from a `MovePtr<'_, T>`. /// /// # Example /// /// ``` /// use std::mem::ManuallyDrop; /// /// use abi_stable::{ /// pointer_trait::OwnedPointer, /// sabi_types::RSmallBox, /// std_types::RBox, /// }; /// /// let b = RSmallBox::<_, [u8; 1]>::new(77u8); /// let rbox: RBox<_> = b.in_move_ptr(|x| RBox::from_move_ptr(x)); /// /// assert_eq!(*rbox, 77); /// /// ``` pub fn from_move_ptr(p: MovePtr<'_, T>) -> RBox<T> { MovePtr::into_rbox(p) } #[inline(always)] pub(super) const fn data(&self) -> *mut T { self.data.as_ptr() } #[inline(always)] pub(super) fn data_mut(&mut self) -> *mut T { self.data.as_ptr() } #[inline(always)] pub(super) const fn vtable(&self) -> BoxVtable_Ref<T> { self.vtable } #[allow(dead_code)] #[cfg(test)] pub(super) fn set_vtable_for_testing(&mut self) { self.vtable = VTableGetter::<T>::LIB_VTABLE_FOR_TESTING; } } unsafe impl<T> AsPtr for RBox<T> { #[inline(always)] fn as_ptr(&self) -> *const T { self.data.as_ptr() } } unsafe impl<T> AsMutPtr for RBox<T> { #[inline(always)] fn as_mut_ptr(&mut self) -> *mut T { self.data.as_ptr() } } } pub use self::private::RBox; unsafe impl<T> GetPointerKind for RBox<T> { type Kind = PK_SmartPointer; type PtrTarget = T; } unsafe impl<T, O> CanTransmuteElement<O> for RBox<T> { type TransmutedPtr = RBox<O>; unsafe fn transmute_element_(self) -> Self::TransmutedPtr { unsafe { core_extensions::utils::transmute_ignore_size(self) } } } impl<T> RBox<T> { /// Converts this `RBox<T>` into a `Box<T>` /// /// # Allocation /// /// If this is invoked outside of the dynamic library/binary that created the `RBox<T>`, /// it will allocate a new `Box<T>` and move the data into it. /// /// # Example /// /// ``` /// use abi_stable::std_types::RBox; /// /// let baux: RBox<u32> = RBox::new(200); /// let baux: Box<u32> = RBox::into_box(baux); /// assert_eq!(*baux, 200); /// /// ``` pub fn into_box(this: Self) -> Box<T> { let this = ManuallyDrop::new(this); unsafe { let this_vtable = this.vtable(); let other_vtable = VTableGetter::LIB_VTABLE; if ::std::ptr::eq(this_vtable.0.to_raw_ptr(), other_vtable.0.to_raw_ptr()) || this_vtable.type_id()() == other_vtable.type_id()() { Box::from_raw(this.data()) } else { let ret = Box::new(this.data().read()); // Just deallocating the Box<_>. without dropping the inner value (this.vtable().destructor())( this.data() as *mut (), CallReferentDrop::No, Deallocate::Yes, ); ret } } } /// Unwraps this `Box<T>` into the value it owns on the heap. /// /// # Example /// /// ``` /// use abi_stable::std_types::RBox; /// /// let baux: RBox<u32> = RBox::new(200); /// let baux: u32 = RBox::into_inner(baux); /// assert_eq!(baux, 200); /// /// ``` pub fn into_inner(this: Self) -> T { unsafe { let value = this.data().read(); Self::drop_allocation(&mut ManuallyDrop::new(this)); value } } /// Wraps this `RBox` in a `Pin` /// pub fn into_pin(self) -> Pin<RBox<T>> { // safety: this is the same as what Box does. unsafe { Pin::new_unchecked(self) } } } impl<T> DerefMut for RBox<T> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { &mut *self.data() } } } ///////////////////////////////////////////////////////////////// unsafe impl<T> OwnedPointer for RBox<T> { #[inline] unsafe fn get_move_ptr(this: &mut ManuallyDrop<Self>) -> MovePtr<'_, T> { unsafe { MovePtr::from_raw(this.data_mut()) } } #[inline] unsafe fn drop_allocation(this: &mut ManuallyDrop<Self>) { let data: *mut T = this.data(); unsafe { (this.vtable().destructor())(data as *mut (), CallReferentDrop::No, Deallocate::Yes); } } } ///////////////////////////////////////////////////////////////// impl<T> Borrow<T> for RBox<T> { fn borrow(&self) -> &T { self } } impl<T> BorrowMut<T> for RBox<T> { fn borrow_mut(&mut self) -> &mut T { self } } impl<T> AsRef<T> for RBox<T> { fn as_ref(&self) -> &T { self } } impl<T> AsMut<T> for RBox<T> { fn as_mut(&mut self) -> &mut T { self } } ///////////////////////////////////////////////////////////////// impl_from_rust_repr! { impl[T] From<Box<T>> for RBox<T> { fn(this){ RBox::from_box(this) } } } impl<T> From<RBox<T>> for Pin<RBox<T>> { fn from(boxed: RBox<T>) -> Pin<RBox<T>> { boxed.into_pin() } } ///////////////////////////////////////////////////////////////// impl<T> IntoReprRust for RBox<T> { type ReprRust = Box<T>; fn into_rust(self) -> Self::ReprRust { Self::into_box(self) } } ///////////////////////////////////////////////////////////////// impl<T> Default for RBox<T> where T: Default, { fn default() -> Self { Self::new(T::default()) } } impl<T> Clone for RBox<T> where T: Clone, { fn clone(&self) -> Self { (**self).clone().piped(Box::new).into() } } shared_impls! {pointer mod = box_impls new_type = RBox[][T], original_type = Box, } unsafe impl<T: Send> Send for RBox<T> {} unsafe impl<T: Sync> Sync for RBox<T> {} impl<T> Unpin for RBox<T> {} /////////////////////////////////////////////////////////////// impl<I> Iterator for RBox<I> where I: Iterator, { type Item = I::Item; fn next(&mut self) -> Option<I::Item> { (**self).next() } fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() } fn nth(&mut self, n: usize) -> Option<I::Item> { (**self).nth(n) } fn last(self) -> Option<I::Item> { RBox::into_inner(self).last() } } impl<I> DoubleEndedIterator for RBox<I> where I: DoubleEndedIterator, { fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() } fn nth_back(&mut self, n: usize) -> Option<I::Item> { (**self).nth_back(n) } } impl<I> ExactSizeIterator for RBox<I> where I: ExactSizeIterator, { fn len(&self) -> usize { (**self).len() } } impl<I> FusedIterator for RBox<I> where I: FusedIterator {} /////////////////////////////////////////////////////////////// impl<F> Future for RBox<F> where F: Future + Unpin, { type Output = F::Output; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { F::poll(Pin::new(&mut *self), cx) } } /////////////////////////////////////////////////////////////// impl<T> StdError for RBox<T> where T: StdError, { #[allow(deprecated, deprecated_in_future)] fn description(&self) -> &str { StdError::description(&**self) } #[allow(deprecated)] fn cause(&self) -> Option<&dyn StdError> { StdError::cause(&**self) } fn source(&self) -> Option<&(dyn StdError + 'static)> { StdError::source(&**self) } } /////////////////////////////////////////////////////////////// impl<T> Read for RBox<T> where T: Read, { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { (**self).read(buf) } #[inline] fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> { (**self).read_vectored(bufs) } #[inline] fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_to_end(buf) } #[inline] fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_to_string(buf) } #[inline] fn read_exact(&mut self, buf: &mut [u8]) -> io::Result<()> { (**self).read_exact(buf) } } impl<T> Write for RBox<T> where T: Write, { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { (**self).write(buf) } #[inline] fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> { (**self).write_vectored(bufs) } #[inline] fn flush(&mut self) -> io::Result<()> { (**self).flush() } #[inline] fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { (**self).write_all(buf) } #[inline] fn write_fmt(&mut self, fmt: std::fmt::Arguments<'_>) -> io::Result<()> { (**self).write_fmt(fmt) } } impl<T> Seek for RBox<T> where T: Seek, { #[inline] fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> { (**self).seek(pos) } } impl<T> BufRead for RBox<T> where T: BufRead, { #[inline] fn fill_buf(&mut self) -> io::Result<&[u8]> { (**self).fill_buf() } #[inline] fn consume(&mut self, amt: usize) { (**self).consume(amt) } #[inline] fn read_until(&mut self, byte: u8, buf: &mut Vec<u8>) -> io::Result<usize> { (**self).read_until(byte, buf) } #[inline] fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { (**self).read_line(buf) } } /////////////////////////////////////////////////////////////// impl<T> Hasher for RBox<T> where T: Hasher, { fn finish(&self) -> u64 { (**self).finish() } fn write(&mut self, bytes: &[u8]) { (**self).write(bytes) } fn write_u8(&mut self, i: u8) { (**self).write_u8(i) } fn write_u16(&mut self, i: u16) { (**self).write_u16(i) } fn write_u32(&mut self, i: u32) { (**self).write_u32(i) } fn write_u64(&mut self, i: u64) { (**self).write_u64(i) } fn write_u128(&mut self, i: u128) { (**self).write_u128(i) } fn write_usize(&mut self, i: usize) { (**self).write_usize(i) } fn write_i8(&mut self, i: i8) { (**self).write_i8(i) } fn write_i16(&mut self, i: i16) { (**self).write_i16(i) } fn write_i32(&mut self, i: i32) { (**self).write_i32(i) } fn write_i64(&mut self, i: i64) { (**self).write_i64(i) } fn write_i128(&mut self, i: i128) { (**self).write_i128(i) } fn write_isize(&mut self, i: isize) { (**self).write_isize(i) } } /////////////////////////////////////////////////////////////// impl<T> Drop for RBox<T> { fn drop(&mut self) { unsafe { let data = self.data(); let dstr = RBox::vtable(self).destructor(); dstr(data as *mut (), CallReferentDrop::Yes, Deallocate::Yes); } } } /////////////////////////////////////////////////////////////// #[derive(StableAbi)] #[repr(C)] #[sabi(kind(Prefix))] #[sabi(missing_field(panic))] pub(crate) struct BoxVtable<T> { type_id: extern "C" fn() -> UTypeId, #[sabi(last_prefix_field)] destructor: unsafe extern "C" fn(*mut (), CallReferentDrop, Deallocate), _marker: NonOwningPhantom<T>, } struct VTableGetter<'a, T>(&'a T); impl<'a, T: 'a> VTableGetter<'a, T> { const DEFAULT_VTABLE: BoxVtable<T> = BoxVtable { type_id: new_utypeid::<RBox<()>>, destructor: destroy_box::<T>, _marker: NonOwningPhantom::NEW, }; staticref! { const WM_DEFAULT: WithMetadata<BoxVtable<T>> = WithMetadata::new(Self::DEFAULT_VTABLE); } // The VTABLE for this type in this executable/library const LIB_VTABLE: BoxVtable_Ref<T> = BoxVtable_Ref(Self::WM_DEFAULT.as_prefix()); #[cfg(test)] staticref! { const WM_FOR_TESTING: WithMetadata<BoxVtable<T>> = WithMetadata::new( BoxVtable { type_id: new_utypeid::<RBox<i32>>, ..Self::DEFAULT_VTABLE }, ) } #[allow(dead_code)] #[cfg(test)] const LIB_VTABLE_FOR_TESTING: BoxVtable_Ref<T> = BoxVtable_Ref(Self::WM_FOR_TESTING.as_prefix()); } unsafe extern "C" fn destroy_box<T>( ptr: *mut (), call_drop: CallReferentDrop, dealloc: Deallocate, ) { extern_fn_panic_handling! {no_early_return; let ptr = ptr as *mut T; if let CallReferentDrop::Yes = call_drop { unsafe { ptr::drop_in_place(ptr); } } if let Deallocate::Yes = dealloc { unsafe { drop(Box::from_raw(ptr as *mut ManuallyDrop<T>)); } } } } /////////////////////////////////////////////////////////////////
use helpers::{HelperDef}; use registry::{Registry}; use context::{Context, JsonTruthy}; use render::{Renderable, RenderContext, RenderError, render_error, Helper}; #[derive(Clone, Copy)] pub struct IfHelper { positive: bool } impl HelperDef for IfHelper{ fn call(&self, c: &Context, h: &Helper, r: &Registry, rc: &mut RenderContext) -> Result<(), RenderError> { let param = h.param(0); if param.is_none() { return Err(render_error("Param not found for helper \"if\"")); } let name = param.unwrap(); let mut value = if name.starts_with("@") { rc.get_local_var(name).is_truthy() } else { c.navigate(rc.get_path(), name).is_truthy() }; if !self.positive { value = !value; } let tmpl = if value { h.template() } else { h.inverse() }; match tmpl { Some(ref t) => t.render(c, r, rc), None => Ok(()) } } } pub static IF_HELPER: IfHelper = IfHelper { positive: true }; pub static UNLESS_HELPER: IfHelper = IfHelper { positive: false }; #[cfg(test)] mod test { use template::{Template}; use registry::{Registry}; #[test] fn test_if() { let t0 = Template::compile("{{#if this}}hello{{/if}}".to_string()).ok().unwrap(); let t1 = Template::compile("{{#unless this}}hello{{else}}world{{/unless}}".to_string()).ok().unwrap(); let mut handlebars = Registry::new(); handlebars.register_template("t0", t0); handlebars.register_template("t1", t1); let r0 = handlebars.render("t0", &true); assert_eq!(r0.ok().unwrap(), "hello".to_string()); let r1 = handlebars.render("t1", &true); assert_eq!(r1.ok().unwrap(), "world".to_string()); let r2 = handlebars.render("t0", &false); assert_eq!(r2.ok().unwrap(), "".to_string()); } }
//! Provides a seamless wrapper around OpenGL and WebGL, so that the rest of //! the code doesn't need to know which of the two it's running on. mod buffer; mod context; mod framebuffer; #[cfg(not(target_arch = "wasm32"))] pub mod opengl; pub mod shaders; mod texture; mod vertexbuffer; #[cfg(target_arch = "wasm32")] pub mod webgl; #[cfg(not(target_arch = "wasm32"))] pub use crate::opengl::GLContext as Context; #[cfg(target_arch = "wasm32")] pub use crate::webgl::WebGLContext as Context; pub use crate::buffer::Buffer; pub use crate::buffer::BufferType; pub use crate::context::Buffer as NativeBuffer; pub use crate::context::FrameBuffer as NativeFrameBuffer; pub use crate::context::Texture as NativeTexture; pub use crate::context::VertexArray as NativeVertexBuffer; pub use crate::context::{AbstractContext, GlPrimitive, Program, Shader, UniformLocation}; pub use crate::framebuffer::FrameBuffer; pub use crate::texture::Texture; pub use crate::texture::TextureFormat; pub use crate::vertexbuffer::VertexBuffer;
/// A match within a scan. #[derive(Debug)] pub struct Match { /// Offset of the match within the scanning area. pub offset: usize, /// Length of the file. Can be useful if the matcher string has not a fixed length. pub length: usize, /// Matched data. pub data: Vec<u8>, }
use Vector; use chrono::{DateTime, Duration, Utc}; use cpd::Rigid; use failure::Error; use las::Point; use std::collections::HashMap; use std::path::Path; use std::sync::{Arc, Mutex}; /// The velocity calculation did not converge. #[derive(Debug, Fail)] #[fail(display = "Did not converge")] pub struct DidNotConverge {} /// Calculate velocities over a large area using rigid cpd. #[derive(Debug)] pub struct Builder { after: Vec<Point>, before: Vec<Point>, datetime: DateTime<Utc>, duration: Duration, grid_size: i64, min_points: usize, ngrow: usize, } /// A grid of cells, used to calculate velocities. #[derive(Debug)] pub struct Grid { data: HashMap<(i64, i64), Cell>, datetime: DateTime<Utc>, duration: Duration, } /// A cell in a grid. #[derive(Debug)] pub struct Cell { after: Vec<Point>, before: Vec<Point>, coordinates: (i64, i64), grid_size: i64, } /// A velocity measurement. #[derive(Debug, Serialize, Deserialize)] pub struct Velocity { /// The number of points in the after matrix. pub after_points: usize, /// The number of points in the before matrix. pub before_points: usize, /// The center of gravity of the point. pub center_of_gravity: Vector, /// The date and time of this velocity measurement. pub datetime: DateTime<Utc>, /// The size of the grid of the cell used for this velocity. pub grid_size: i64, /// The number of iterations it took. pub iterations: usize, /// The mean displacement between the points, divided by the number of hours in between scans. pub velocity: Vector, /// The lower-left corner of the velocity cell, x. pub x: f64, /// The lower-left corner of the velocity cell, y. pub y: f64, } struct Worker { id: usize, } impl Builder { /// Create new velocities from two input las files. pub fn new<P: AsRef<Path>, Q: AsRef<Path>>( before: P, after: Q, grid_size: i64, ) -> Result<Builder, Error> { use las::Read; use las::Reader; let before_datetime = super::datetime_from_path(&before)?; let after_datetime = super::datetime_from_path(&after)?; let duration = after_datetime.signed_duration_since(before_datetime); let datetime = before_datetime + duration; let before = Reader::from_path(before)? .points() .collect::<Result<Vec<_>, _>>()?; let after = Reader::from_path(after)? .points() .collect::<Result<Vec<_>, _>>()?; Ok(Builder { after: after, before: before, datetime: datetime, duration: duration, grid_size: grid_size, min_points: 0, ngrow: 0, }) } /// Sets the number of times this grid should grow. pub fn ngrow(mut self, ngrow: usize) -> Builder { self.ngrow = ngrow; self } /// Sets the minimum number of points allowed in a cell. pub fn min_points(mut self, min_points: usize) -> Builder { self.min_points = min_points; self } /// Creates a grid from this builder. pub fn into_grid(self) -> Grid { let mut data: HashMap<(i64, i64), Cell> = HashMap::new(); let grid_size = self.grid_size; let min_points = self.min_points; let grid_coordinates = |point: &Point| (point.y as i64 / grid_size, point.x as i64 / grid_size); for point in self.before { let coordinates = grid_coordinates(&point); data.entry(coordinates) .or_insert_with(|| Cell::new(coordinates, grid_size)) .before .push(point); } for point in self.after { let coordinates = grid_coordinates(&point); data.entry(coordinates) .or_insert_with(|| Cell::new(coordinates, grid_size)) .after .push(point); } let mut grid = Grid { data: data, datetime: self.datetime, duration: self.duration, }; for _ in 0..self.ngrow { info!("Growing cells"); let n = grid.grow(min_points); info!("{} cells grown", n); } let before = grid.data.len(); grid.cull(min_points); let after = grid.data.len(); info!("{} cells accepted, {} cells culled", after, before - after); grid } } impl Grid { /// Grow any under-populated grid cells. pub fn grow(&mut self, min_points: usize) -> usize { let mut count = 0; for coordinate in self.coordinates() { if self.cell(coordinate) .map(|c| c.is_too_small(min_points)) .unwrap_or(false) { self.grow_cell(coordinate); count += 1; } } count } /// Calculates velocities for each cell in this grid. pub fn calculate_velocities<T: Into<Option<usize>>>( self, num_threads: T, rigid: Rigid, ) -> Vec<Result<Velocity, Error>> { use std::thread; let num_threads = num_threads.into().unwrap_or(1); assert!(num_threads > 0); let mut handles = Vec::new(); let grid = Arc::new(Mutex::new(self)); for i in 0..num_threads { let grid = grid.clone(); let rigid = rigid.clone(); let handle = thread::spawn(move || { let worker = Worker { id: i }; worker.start(grid, rigid) }); handles.push(handle); } let mut velocities = Vec::new(); for handle in handles { let v = handle.join().unwrap(); velocities.extend(v); } velocities } fn cull(&mut self, min_points: usize) { self.data.retain(|_, cell| !cell.is_too_small(min_points)) } fn cell(&self, coordinate: (i64, i64)) -> Option<&Cell> { self.data.get(&coordinate) } fn pop(&mut self) -> Option<Cell> { if let Some(&key) = self.data.keys().next() { self.data.remove(&key) } else { None } } fn len(&self) -> usize { self.data.len() } fn coordinates(&self) -> Vec<(i64, i64)> { let mut coordinates = self.data.keys().map(|&k| k).collect::<Vec<_>>(); coordinates.sort(); coordinates } fn grow_cell(&mut self, coordinate: (i64, i64)) { let mut cell = self.data.remove(&coordinate).expect( "grow_cell called but cell does not exist", ); cell.grid_size *= 2; let (r, c) = coordinate; for k in [(r + 1, c), (r, c + 1), (r + 1, c + 1)].into_iter() { while self.data .get(k) .map(|c| c.grid_size < cell.grid_size / 2) .unwrap_or(false) { self.grow_cell(*k); } if let Some(other) = self.data.remove(k) { cell.consume(other); } } self.data.insert(coordinate, cell); } } impl Cell { fn new(coordinates: (i64, i64), grid_size: i64) -> Cell { Cell { after: Vec::new(), before: Vec::new(), coordinates: coordinates, grid_size: grid_size, } } fn is_too_small(&self, min_points: usize) -> bool { self.before.len() < min_points || self.after.len() < min_points } fn consume(&mut self, other: Cell) { assert_eq!(self.grid_size, other.grid_size * 2); self.before.extend(other.before); self.after.extend(other.after); } fn calculate_velocity( &self, rigid: &Rigid, datetime: DateTime<Utc>, duration: Duration, ) -> Result<Velocity, Error> { let before = super::matrix_from_points(&self.before); let after = super::matrix_from_points(&self.after); let run = rigid.register(&after, &before)?; let displacement = run.moved - &before; if run.converged { Ok(Velocity { after_points: after.nrows(), before_points: before.nrows(), center_of_gravity: super::center_of_gravity(&before), datetime: datetime, grid_size: self.grid_size, iterations: run.iterations, x: (self.coordinates.0 * self.grid_size) as f64, y: (self.coordinates.1 * self.grid_size) as f64, velocity: super::center_of_gravity(&displacement) / duration.num_hours() as f64, }) } else { Err(DidNotConverge {}.into()) } } } impl Worker { fn start(&self, grid: Arc<Mutex<Grid>>, rigid: Rigid) -> Vec<Result<Velocity, Error>> { let (datetime, duration) = { let grid = grid.lock().unwrap(); (grid.datetime, grid.duration) }; let mut velocities = Vec::new(); while let Some((cell, remaining)) = { let mut grid = grid.lock().unwrap(); grid.pop().map(|cell| (cell, grid.len())) } { info!( "#{} [{} remaining]: Got cell ({}, {}), size: {}, before: {}, after: {}", self.id, remaining, cell.coordinates.0, cell.coordinates.1, cell.grid_size, cell.before.len(), cell.after.len(), ); velocities.push(cell.calculate_velocity(&rigid, datetime, duration)); } info!("#{} is done", self.id); velocities } }
use std::io::{Seek, SeekFrom, Write}; use assert_cmd::prelude::*; use predicates::str::contains; #[cfg(feature = "compression")] #[test] fn test_stdin_gz() { // Generated with `echo ">id1\nAGTCGTCA" | gzip -c | xxd -i` let input: &[u8] = &[ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xb3, 0xcb, 0x4c, 0x31, 0xe4, 0x72, 0x74, 0x0f, 0x71, 0x06, 0x22, 0x47, 0x2e, 0x00, 0x9e, 0x3a, 0x32, 0x8c, 0x0e, 0x00, 0x00, 0x00, ]; let mut file = tempfile::NamedTempFile::new().unwrap(); file.write_all(input).unwrap(); file.flush().unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); escargot::CargoBuild::new() .example("stdin_pipe") .current_release() .current_target() .run() .unwrap() .command() .stdin(file.into_file()) .assert() .success() .stdout(contains("There are 8 bases in your file")) .stdout(contains("There are 0 AAAAs in your file")); } #[cfg(feature = "compression")] #[test] fn test_stdin_xz() { // Generated with `echo ">id1\nAGTCGTCA" | xz -c | xxd -i` let input: &[u8] = &[ 0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00, 0x00, 0x04, 0xe6, 0xd6, 0xb4, 0x46, 0x02, 0x00, 0x21, 0x01, 0x16, 0x00, 0x00, 0x00, 0x74, 0x2f, 0xe5, 0xa3, 0x01, 0x00, 0x0d, 0x3e, 0x69, 0x64, 0x31, 0x0a, 0x41, 0x47, 0x54, 0x43, 0x47, 0x54, 0x43, 0x41, 0x0a, 0x00, 0x00, 0x00, 0x12, 0x0f, 0x91, 0x75, 0xef, 0x7b, 0x63, 0x17, 0x00, 0x01, 0x26, 0x0e, 0x08, 0x1b, 0xe0, 0x04, 0x1f, 0xb6, 0xf3, 0x7d, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x59, 0x5a, ]; let mut file = tempfile::NamedTempFile::new().unwrap(); file.write_all(input).unwrap(); file.flush().unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); escargot::CargoBuild::new() .example("stdin_pipe") .current_release() .current_target() .run() .unwrap() .command() .stdin(file.into_file()) .assert() .success() .stdout(contains("There are 8 bases in your file")) .stdout(contains("There are 0 AAAAs in your file")); } #[cfg(feature = "compression")] #[test] fn test_stdin_bzip() { // Generated with `echo ">id1\nAGTCGTCA" | bzip2 -c | xxd -i` let input: &[u8] = &[ 0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59, 0x9f, 0x9d, 0xf9, 0xa2, 0x00, 0x00, 0x01, 0xcf, 0x00, 0x00, 0x10, 0x20, 0x01, 0x28, 0x80, 0x04, 0x00, 0x04, 0x20, 0x20, 0x00, 0x22, 0x0c, 0x9a, 0x64, 0x20, 0xc9, 0x88, 0x21, 0x95, 0x8e, 0x82, 0x75, 0x27, 0x8b, 0xb9, 0x22, 0x9c, 0x28, 0x48, 0x4f, 0xce, 0xfc, 0xd1, 0x00, ]; let mut file = tempfile::NamedTempFile::new().unwrap(); file.write_all(input).unwrap(); file.flush().unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); escargot::CargoBuild::new() .example("stdin_pipe") .current_release() .current_target() .run() .unwrap() .command() .stdin(file.into_file()) .assert() .success() .stdout(contains("There are 8 bases in your file")) .stdout(contains("There are 0 AAAAs in your file")); } #[test] fn test_stdin_no_compression() { let input: &[u8] = b">id1\nAGTCGTCA"; let mut file = tempfile::NamedTempFile::new().unwrap(); file.write_all(input).unwrap(); file.flush().unwrap(); file.seek(SeekFrom::Start(0)).unwrap(); escargot::CargoBuild::new() .example("stdin_pipe") .current_release() .current_target() .run() .unwrap() .command() .stdin(file.into_file()) .assert() .success() .stdout(contains("There are 8 bases in your file")) .stdout(contains("There are 0 AAAAs in your file")); }
#[doc = "Writer for register OENR"] pub type W = crate::W<u32, super::OENR>; #[doc = "Register OENR `reset()`'s with value 0"] impl crate::ResetValue for super::OENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Timer E Output 2 Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TE2OEN_AW { #[doc = "1: Enable output"] ENABLE = 1, } impl From<TE2OEN_AW> for bool { #[inline(always)] fn from(variant: TE2OEN_AW) -> Self { variant as u8 != 0 } } #[doc = "Write proxy for field `TE2OEN`"] pub struct TE2OEN_W<'a> { w: &'a mut W, } impl<'a> TE2OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TE2OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer E Output 1 Enable"] pub type TE1OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TE1OEN`"] pub struct TE1OEN_W<'a> { w: &'a mut W, } impl<'a> TE1OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TE1OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer D Output 2 Enable"] pub type TD2OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TD2OEN`"] pub struct TD2OEN_W<'a> { w: &'a mut W, } impl<'a> TD2OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TD2OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Timer D Output 1 Enable"] pub type TD1OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TD1OEN`"] pub struct TD1OEN_W<'a> { w: &'a mut W, } impl<'a> TD1OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TD1OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer C Output 2 Enable"] pub type TC2OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TC2OEN`"] pub struct TC2OEN_W<'a> { w: &'a mut W, } impl<'a> TC2OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TC2OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer C Output 1 Enable"] pub type TC1OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TC1OEN`"] pub struct TC1OEN_W<'a> { w: &'a mut W, } impl<'a> TC1OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TC1OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer B Output 2 Enable"] pub type TB2OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TB2OEN`"] pub struct TB2OEN_W<'a> { w: &'a mut W, } impl<'a> TB2OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TB2OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer B Output 1 Enable"] pub type TB1OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TB1OEN`"] pub struct TB1OEN_W<'a> { w: &'a mut W, } impl<'a> TB1OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TB1OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer A Output 2 Enable"] pub type TA2OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TA2OEN`"] pub struct TA2OEN_W<'a> { w: &'a mut W, } impl<'a> TA2OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TA2OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 = "Timer A Output 1 Enable"] pub type TA1OEN_AW = TE2OEN_AW; #[doc = "Write proxy for field `TA1OEN`"] pub struct TA1OEN_W<'a> { w: &'a mut W, } impl<'a> TA1OEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TA1OEN_AW) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Enable output"] #[inline(always)] pub fn enable(self) -> &'a mut W { self.variant(TE2OEN_AW::ENABLE) } #[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 } } impl W { #[doc = "Bit 9 - Timer E Output 2 Enable"] #[inline(always)] pub fn te2oen(&mut self) -> TE2OEN_W { TE2OEN_W { w: self } } #[doc = "Bit 8 - Timer E Output 1 Enable"] #[inline(always)] pub fn te1oen(&mut self) -> TE1OEN_W { TE1OEN_W { w: self } } #[doc = "Bit 7 - Timer D Output 2 Enable"] #[inline(always)] pub fn td2oen(&mut self) -> TD2OEN_W { TD2OEN_W { w: self } } #[doc = "Bit 6 - Timer D Output 1 Enable"] #[inline(always)] pub fn td1oen(&mut self) -> TD1OEN_W { TD1OEN_W { w: self } } #[doc = "Bit 5 - Timer C Output 2 Enable"] #[inline(always)] pub fn tc2oen(&mut self) -> TC2OEN_W { TC2OEN_W { w: self } } #[doc = "Bit 4 - Timer C Output 1 Enable"] #[inline(always)] pub fn tc1oen(&mut self) -> TC1OEN_W { TC1OEN_W { w: self } } #[doc = "Bit 3 - Timer B Output 2 Enable"] #[inline(always)] pub fn tb2oen(&mut self) -> TB2OEN_W { TB2OEN_W { w: self } } #[doc = "Bit 2 - Timer B Output 1 Enable"] #[inline(always)] pub fn tb1oen(&mut self) -> TB1OEN_W { TB1OEN_W { w: self } } #[doc = "Bit 1 - Timer A Output 2 Enable"] #[inline(always)] pub fn ta2oen(&mut self) -> TA2OEN_W { TA2OEN_W { w: self } } #[doc = "Bit 0 - Timer A Output 1 Enable"] #[inline(always)] pub fn ta1oen(&mut self) -> TA1OEN_W { TA1OEN_W { w: self } } }
use super::display::Display; use crossterm::{ execute, queue }; use std::io::{Write, stdout}; const pixel: &'static str = "█"; pub fn redraw(display: &Display) -> crossterm::Result<()> { let mut stdout = stdout(); execute!( stdout, crossterm::terminal::Clear(crossterm::terminal::ClearType::All) )?; for (row_idx, row) in display.contents.iter().enumerate() { const MASK: u64 = 0x8000_0000_0000_0000; for i in 0..64 { let pxl = (MASK >> i) & row; if pxl != 0 { queue!( stdout, crossterm::cursor::MoveTo(i, row_idx as u16), crossterm::style::Print(pixel) )?; } } } stdout.flush()?; Ok(()) } pub fn init() -> crossterm::Result<()> { use crossterm::terminal::{EnterAlternateScreen}; let mut stdout = stdout(); execute!( stdout, crossterm::cursor::Hide, crossterm::terminal::Clear(crossterm::terminal::ClearType::All), crossterm::terminal::SetSize(64,32), ) // match term.terminal().terminal_size() { // size if (size.0 >= 64 && size.1 >= 32) => Ok((term, alternate)), // _ => Err(crossterm::ErrorKind::ResizingTerminalFailure( // "Could not set expected size! Please set terminal to 64x32".to_string(), // )), // } }
#[doc = "Reader of register IER"] pub type R = crate::R<u32, super::IER>; #[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Register IER `reset()`'s with value 0"] impl crate::ResetValue for super::IER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Burst mode period Interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum BMPERIE_A { #[doc = "0: Burst mode period interrupt disabled"] DISABLED = 0, #[doc = "1: Burst mode period interrupt enabled"] ENABLED = 1, } impl From<BMPERIE_A> for bool { #[inline(always)] fn from(variant: BMPERIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `BMPERIE`"] pub type BMPERIE_R = crate::R<bool, BMPERIE_A>; impl BMPERIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BMPERIE_A { match self.bits { false => BMPERIE_A::DISABLED, true => BMPERIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == BMPERIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == BMPERIE_A::ENABLED } } #[doc = "Write proxy for field `BMPERIE`"] pub struct BMPERIE_W<'a> { w: &'a mut W, } impl<'a> BMPERIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: BMPERIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Burst mode period interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(BMPERIE_A::DISABLED) } #[doc = "Burst mode period interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(BMPERIE_A::ENABLED) } #[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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "DLL Ready Interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DLLRDYIE_A { #[doc = "0: DLL ready interrupt disabled"] DISABLED = 0, #[doc = "1: DLL Ready interrupt enabled"] ENABLED = 1, } impl From<DLLRDYIE_A> for bool { #[inline(always)] fn from(variant: DLLRDYIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DLLRDYIE`"] pub type DLLRDYIE_R = crate::R<bool, DLLRDYIE_A>; impl DLLRDYIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DLLRDYIE_A { match self.bits { false => DLLRDYIE_A::DISABLED, true => DLLRDYIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == DLLRDYIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == DLLRDYIE_A::ENABLED } } #[doc = "Write proxy for field `DLLRDYIE`"] pub struct DLLRDYIE_W<'a> { w: &'a mut W, } impl<'a> DLLRDYIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DLLRDYIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "DLL ready interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(DLLRDYIE_A::DISABLED) } #[doc = "DLL Ready interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(DLLRDYIE_A::ENABLED) } #[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 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "System Fault Interrupt Enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYSFLTIE_A { #[doc = "0: Fault interrupt disabled"] DISABLED = 0, #[doc = "1: Fault interrupt enabled"] ENABLED = 1, } impl From<SYSFLTIE_A> for bool { #[inline(always)] fn from(variant: SYSFLTIE_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SYSFLTIE`"] pub type SYSFLTIE_R = crate::R<bool, SYSFLTIE_A>; impl SYSFLTIE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SYSFLTIE_A { match self.bits { false => SYSFLTIE_A::DISABLED, true => SYSFLTIE_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == SYSFLTIE_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == SYSFLTIE_A::ENABLED } } #[doc = "Write proxy for field `SYSFLTIE`"] pub struct SYSFLTIE_W<'a> { w: &'a mut W, } impl<'a> SYSFLTIE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SYSFLTIE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 = "Fault 5 Interrupt Enable"] pub type FLT5IE_A = SYSFLTIE_A; #[doc = "Reader of field `FLT5IE`"] pub type FLT5IE_R = crate::R<bool, SYSFLTIE_A>; #[doc = "Write proxy for field `FLT5IE`"] pub struct FLT5IE_W<'a> { w: &'a mut W, } impl<'a> FLT5IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLT5IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 = "Fault 4 Interrupt Enable"] pub type FLT4IE_A = SYSFLTIE_A; #[doc = "Reader of field `FLT4IE`"] pub type FLT4IE_R = crate::R<bool, SYSFLTIE_A>; #[doc = "Write proxy for field `FLT4IE`"] pub struct FLT4IE_W<'a> { w: &'a mut W, } impl<'a> FLT4IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLT4IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 = "Fault 3 Interrupt Enable"] pub type FLT3IE_A = SYSFLTIE_A; #[doc = "Reader of field `FLT3IE`"] pub type FLT3IE_R = crate::R<bool, SYSFLTIE_A>; #[doc = "Write proxy for field `FLT3IE`"] pub struct FLT3IE_W<'a> { w: &'a mut W, } impl<'a> FLT3IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLT3IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 = "Fault 2 Interrupt Enable"] pub type FLT2IE_A = SYSFLTIE_A; #[doc = "Reader of field `FLT2IE`"] pub type FLT2IE_R = crate::R<bool, SYSFLTIE_A>; #[doc = "Write proxy for field `FLT2IE`"] pub struct FLT2IE_W<'a> { w: &'a mut W, } impl<'a> FLT2IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLT2IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 = "Fault 1 Interrupt Enable"] pub type FLT1IE_A = SYSFLTIE_A; #[doc = "Reader of field `FLT1IE`"] pub type FLT1IE_R = crate::R<bool, SYSFLTIE_A>; #[doc = "Write proxy for field `FLT1IE`"] pub struct FLT1IE_W<'a> { w: &'a mut W, } impl<'a> FLT1IE_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLT1IE_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Fault interrupt disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::DISABLED) } #[doc = "Fault interrupt enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(SYSFLTIE_A::ENABLED) } #[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 } } impl R { #[doc = "Bit 17 - Burst mode period Interrupt Enable"] #[inline(always)] pub fn bmperie(&self) -> BMPERIE_R { BMPERIE_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - DLL Ready Interrupt Enable"] #[inline(always)] pub fn dllrdyie(&self) -> DLLRDYIE_R { DLLRDYIE_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 5 - System Fault Interrupt Enable"] #[inline(always)] pub fn sysfltie(&self) -> SYSFLTIE_R { SYSFLTIE_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 4 - Fault 5 Interrupt Enable"] #[inline(always)] pub fn flt5ie(&self) -> FLT5IE_R { FLT5IE_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 3 - Fault 4 Interrupt Enable"] #[inline(always)] pub fn flt4ie(&self) -> FLT4IE_R { FLT4IE_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - Fault 3 Interrupt Enable"] #[inline(always)] pub fn flt3ie(&self) -> FLT3IE_R { FLT3IE_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - Fault 2 Interrupt Enable"] #[inline(always)] pub fn flt2ie(&self) -> FLT2IE_R { FLT2IE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - Fault 1 Interrupt Enable"] #[inline(always)] pub fn flt1ie(&self) -> FLT1IE_R { FLT1IE_R::new((self.bits & 0x01) != 0) } } impl W { #[doc = "Bit 17 - Burst mode period Interrupt Enable"] #[inline(always)] pub fn bmperie(&mut self) -> BMPERIE_W { BMPERIE_W { w: self } } #[doc = "Bit 16 - DLL Ready Interrupt Enable"] #[inline(always)] pub fn dllrdyie(&mut self) -> DLLRDYIE_W { DLLRDYIE_W { w: self } } #[doc = "Bit 5 - System Fault Interrupt Enable"] #[inline(always)] pub fn sysfltie(&mut self) -> SYSFLTIE_W { SYSFLTIE_W { w: self } } #[doc = "Bit 4 - Fault 5 Interrupt Enable"] #[inline(always)] pub fn flt5ie(&mut self) -> FLT5IE_W { FLT5IE_W { w: self } } #[doc = "Bit 3 - Fault 4 Interrupt Enable"] #[inline(always)] pub fn flt4ie(&mut self) -> FLT4IE_W { FLT4IE_W { w: self } } #[doc = "Bit 2 - Fault 3 Interrupt Enable"] #[inline(always)] pub fn flt3ie(&mut self) -> FLT3IE_W { FLT3IE_W { w: self } } #[doc = "Bit 1 - Fault 2 Interrupt Enable"] #[inline(always)] pub fn flt2ie(&mut self) -> FLT2IE_W { FLT2IE_W { w: self } } #[doc = "Bit 0 - Fault 1 Interrupt Enable"] #[inline(always)] pub fn flt1ie(&mut self) -> FLT1IE_W { FLT1IE_W { w: self } } }
use std::env; use std::fs::File; use std::io::{BufRead, BufReader}; use tantivy::Index; use tantivy::collector::TopDocs; use tantivy::query::{QueryParser, RangeQuery}; use tantivy::schema::*; fn main() -> tantivy::Result<()> { let file_lines = env::args() .skip(1) .next() .and_then(|f| File::open(f).ok()) .map(|f| BufReader::new(f).lines()); let mut schema_builder = Schema::builder(); let _name = schema_builder.add_text_field("name", STRING | STORED); let color = schema_builder.add_text_field("color", STRING | STORED); let price = schema_builder.add_i64_field("price", INDEXED | STORED); let _date = schema_builder.add_date_field("date", INDEXED | STORED); let schema = schema_builder.build(); let index = Index::create_in_ram(schema.clone()); let mut index_writer = index.writer(3_000_000)?; for lines in file_lines { for line in lines { let doc = schema.parse_document(line?.as_str())?; index_writer.add_document(doc); } } index_writer.commit()?; let reader = index.reader()?; let searcher = reader.searcher(); let query = QueryParser::for_index(&index, vec![color]) .parse_query("white")?; let docs = searcher.search(&query, &TopDocs::with_limit(10))?; print_docs(&schema, &searcher, docs)?; println!("-----"); let query = RangeQuery::new_i64(price, 300..2000); let docs = searcher.search(&query, &TopDocs::with_limit(5))?; print_docs(&schema, &searcher, docs)?; println!("-----"); let query = QueryParser::for_index(&index, vec![]) .parse_query("price:[300 TO 2000]")?; let docs = searcher.search(&query, &TopDocs::with_limit(10))?; print_docs(&schema, &searcher, docs)?; println!("-----"); let query = QueryParser::for_index(&index, vec![]) .parse_query("date:[2022-02-17T14:00:00+09:00 TO *] AND color:black")?; let docs = searcher.search(&query, &TopDocs::with_limit(10))?; print_docs(&schema, &searcher, docs)?; Ok(()) } fn print_docs(schema: &Schema, searcher: &tantivy::Searcher, docs: Vec<(f32, tantivy::DocAddress)>) -> tantivy::Result<()> { for (_score, address) in docs { let doc = searcher.doc(address)?; //println!("{:?}", doc); println!("{}", schema.to_json(&doc)); } Ok(()) }
fn calculate_frequency(input: String) -> i32 { input .split("\n") .map(|x| x.parse::<i32>().unwrap()) .fold(0, |acc, x| acc + x) } fn main() { let input = include_str!("input.txt").into(); println!("{}", calculate_frequency(input)); } #[test] fn test_01() { assert_eq!(calculate_frequency("+1\n+1\n+1".into()), 3); assert_eq!(calculate_frequency("+1\n+1\n-2".into()), 0); assert_eq!(calculate_frequency("-1\n-2\n-3".into()), -6); }
#![allow(unused_variables)] #![allow(dead_code)] pub fn fibonacci_until(mut x:usize, mut y:usize, limit:usize) { match limit{ 0 => {print!(""); return}, 1 => {print!("{}", x); return}, 2 => {print!("{}, {}", x, y); return}, _ => { print!("{}, {}, ", x, y); loop { (x, y) = (y, y + x); if y > limit { break }; print!("{}, ", y); }}}} pub fn fib_seq(mut x: usize, mut y: usize, qtd: usize) -> Vec<usize> { let mut seq = vec![]; match qtd{ 0 => seq, 1 => {seq.push(x); seq}, 2 => {seq.push(x); seq.push(y); seq}, _ => { seq.push(x); seq.push(y); for _ in 1..(qtd-1) { (x, y) = (y, y+x); seq.push(y); } seq }}} pub fn nth_fib(mut x:usize, mut y:usize, mut n:usize) -> Option<usize>{ match n { 0 => Option::None, 1 => Some(x), 2 => Some(y), 3 => Some(x+y), _ =>{ { n-=2; while n != 0 { (x, y) = (y, y + x); n -= 1; } Some(y) }}}}
use std::path::Path; use std::process::Stdio; use anyhow::{anyhow, Context, Result}; use async_trait::async_trait; use clap::{Parser, IntoApp}; use tokio::fs; use crate::Runnable; use self::database::Database; use self::protobuf::Protobuf; mod database; mod protobuf; /// Compiles app to generate packages #[derive(Parser)] pub struct Compile { /// Compiles all packages #[clap(long)] pub all: bool, #[clap(subcommand)] pub subcmd: Option<SubCommand>, /// Prints more information #[clap(short, long)] pub verbose: bool, } #[derive(Parser)] pub enum SubCommand { Database(Database), Protobuf(Protobuf), } #[async_trait] impl Runnable for Compile { async fn run(&mut self) -> Result<()> { if !self.all { return Ok(Compile::into_app().print_help()?); } let mut database = Database { verbose: self.verbose, }; database.run().await?; let mut protobuf = Protobuf { verbose: self.verbose, }; protobuf.run().await?; Ok(()) } } async fn prepare_awto_dir() -> Result<()> { let awto_path = Path::new("./awto"); if !awto_path.is_dir() { fs::create_dir(awto_path) .await .context("could not create directory './awto'")?; } fs::write("./awto/README.md", include_bytes!("../templates/README.md")) .await .context("could not write file './awto/README.md'")?; Ok(()) } async fn build_awto_pkg(name: &str) -> Result<()> { let status = tokio::process::Command::new("cargo") .current_dir("./awto") .arg("build") .arg("-p") .arg(name) .stdout(Stdio::inherit()) .stderr(Stdio::inherit()) .status() .await?; if !status.success() { return Err(anyhow!("cargo build failed")); } Ok(()) }
/// fn main() { println!("Hello reader !"); }
#[macro_use] extern crate log; use clap::{App, AppSettings, Arg}; use env_logger::Env; use nb::Node; use tokio::runtime::Runtime; fn main() { let matches = App::new("nb") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about("A simple blockchain node") .setting(AppSettings::DisableHelpSubcommand) .arg( Arg::with_name("addr") .long("addr") .takes_value(true) .value_name("IP-PORT") .default_value("127.0.0.1:4000") .help("the node's address"), ) .get_matches(); let addr = matches.value_of("addr").unwrap(); let addr = addr.to_owned(); env_logger::from_env(Env::default().default_filter_or("debug")).init(); info!("nb {}", env!("CARGO_PKG_VERSION")); info!("Listening on {}", addr); let rt = Runtime::new().expect("tokio runtime can be initialized"); rt.block_on(async move { Node::handle_events(addr).await.unwrap() }); }
use super::*; use std::process::{Command, Child, Stdio}; use std::thread; use std::time::Duration; use std::net::TcpListener; /// Find a TCP port number to use. This is racy but see /// https://bugzilla.mozilla.org/show_bug.cgi?id=1240830 /// /// If port is Some, check if we can bind to the given port. Otherwise /// pick a random port. fn check_tcp_port(port: Option<u16>) -> io::Result<u16> { TcpListener::bind(&("localhost", port.unwrap_or(0))) .and_then(|stream| stream.local_addr()) .map(|x| x.port()) } pub struct GeckoDriverBuilder { port: Option<u16>, ff_binary: String, kill_on_drop: bool, } impl GeckoDriverBuilder { pub fn new() -> Self { GeckoDriverBuilder { port: None, ff_binary: "firefox".to_owned(), kill_on_drop: true, } } pub fn port(mut self, port: u16) -> Self { self.port = Some(port); self } pub fn firefox_binary(mut self, binary: &str) -> Self { self.ff_binary = binary.to_owned(); self } pub fn kill_on_drop(mut self, kill: bool) -> Self { self.kill_on_drop = kill; self } pub fn spawn(self) -> Result<GeckoDriver, Error> { let port = check_tcp_port(self.port)?; let child = Command::new("geckodriver") .arg("-b") .arg(self.ff_binary) .arg("--webdriver-port") .arg(format!("{}", port)) .stdin(Stdio::null()) .stderr(Stdio::null()) .stdout(Stdio::null()) .spawn()?; // TODO: parameterize this thread::sleep(Duration::new(1, 500)); Ok(GeckoDriver { child: child, url: format!("http://localhost:{}", port), kill_on_drop: self.kill_on_drop, }) } } /// A geckodriver process pub struct GeckoDriver { pub child: Child, url: String, kill_on_drop: bool, } impl GeckoDriver { pub fn spawn() -> Result<Self, Error> { GeckoDriverBuilder::new().spawn() } pub fn build() -> GeckoDriverBuilder { GeckoDriverBuilder::new() } } impl Drop for GeckoDriver { fn drop(&mut self) { if self.kill_on_drop { let _ = self.child.kill(); } } } impl Driver for GeckoDriver { fn url(&self) -> &str { &self.url } }
use std::error::Error; use std::path::Path; use colored::*; use log::*; use tokio::process::Command; use crate::stack::parser::*; const LOCALSTACK_DYNAMODB_ENDPOINT: &str = "http://localhost:4569"; pub async fn wait_for_it() -> Result<(), Box<dyn Error>> { let mut ready: bool = false; while !ready { warn!("waiting for localstack's dynamodb to be ready.."); let cmd = Command::new("aws") .arg("dynamodb") .arg("list-tables") .args(&["--endpoint-url", LOCALSTACK_DYNAMODB_ENDPOINT]) .status() .await?; if cmd.success() { ready = true; } } Ok(()) } pub async fn deploy((name, service): (String, AWSService)) { match service { AWSService::Dynamo { table_name, schema, recreate, } => { if recreate { info!("deleting dynamodb table '{}'", name.yellow()); delete_table(&table_name).await } info!("creating dynamodb table '{}'", name.yellow()); let sch; // NOTE: // - when schema is specified as an object, it's expected to - // have proper schema with the expected fields in a json object // // - when schema is specified as a string, it's expected - // to refer to a json file contains the proper schema with the expected fields if schema.is_object() { sch = schema.to_string(); } else if schema.is_string() { sch = match schema.as_str() { Some(f) => { if Path::new(f).exists() { String::from(format!("file://{}", f)) } else { warn!("schema file does not exist"); warn!("skipping '{}'", name.yellow()); return; } } None => { warn!("proper schema is required"); warn!("skipping '{}'", name.yellow()); return; } } } else { warn!("proper schema is required, expected a json object or a json file"); warn!("skipping '{}'", name.yellow()); return; } Command::new("aws") .arg("dynamodb") .arg("create-table") .args(&["--table-name", &table_name]) .args(&["--cli-input-json", &sch]) .args(&["--endpoint-url", LOCALSTACK_DYNAMODB_ENDPOINT]) .status() .await .expect("failed to create dynamodb table"); } _ => (), } } async fn delete_table(table_name: &str) { Command::new("aws") .arg("dynamodb") .arg("delete-table") .args(&["--table-name", &table_name]) .args(&["--endpoint-url", LOCALSTACK_DYNAMODB_ENDPOINT]) .status() .await .expect("failed to delete dynamodb table"); }
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion}; use crossbeam::queue::SegQueue; use futures::{channel::oneshot, executor::block_on, future, stream::StreamExt as _, task::Poll}; use std::{sync::Arc, thread}; pub fn polling_benchmark(c: &mut Criterion) { { let mut group = c.benchmark_group("poll overhead # futures"); for i in [10, 100, 1000, 2500, 5000, 7500, 10000].iter() { group.bench_with_input(BenchmarkId::new("unicycle", i), i, |b, i| { b.iter(|| unicycle(*i, 1)) }); group.bench_with_input(BenchmarkId::new("futures-rs", i), i, |b, i| { b.iter(|| futures_rs(*i, 1)) }); } } { let mut group = c.benchmark_group("poll overhead # threads"); for i in [1, 10, 20, 50, 100].iter() { group.bench_with_input(BenchmarkId::new("unicycle", i), i, |b, i| { b.iter(|| unicycle(10000, *i)) }); group.bench_with_input(BenchmarkId::new("futures-rs", i), i, |b, i| { b.iter(|| futures_rs(10000, *i)) }); } } fn unicycle(num: usize, threads: usize) -> usize { use std::pin::Pin; use unicycle::{FuturesUnordered, PollNext}; let txs = SegQueue::new(); let mut rxs = FuturesUnordered::new(); let mut expected = 0usize; for i in 0..num { expected = expected.wrapping_add(i); let (tx, rx) = oneshot::channel(); txs.push((i, tx)); rxs.push(rx); } let txs = Arc::new(txs); for _ in 0..threads { let txs = txs.clone(); thread::spawn(move || { while let Some((n, tx)) = txs.pop() { let _ = tx.send(n); } }); } let result = block_on(future::poll_fn(move |cx| { let mut result = 0usize; loop { if let Poll::Ready(ready) = Pin::new(&mut rxs).poll_next(cx) { match ready { Some(num) => result = result.wrapping_add(num.unwrap()), None => break, } } } Poll::Ready(expected) })); assert_eq!(expected, result); result } fn futures_rs(num: usize, threads: usize) -> usize { use futures::stream::FuturesUnordered; let txs = SegQueue::new(); let mut rxs = FuturesUnordered::new(); let mut expected = 0usize; for i in 0..num { expected = expected.wrapping_add(i); let (tx, rx) = oneshot::channel(); txs.push((i, tx)); rxs.push(rx); } let txs = Arc::new(txs); for _ in 0..threads { let txs = txs.clone(); thread::spawn(move || { while let Some((n, tx)) = txs.pop() { let _ = tx.send(n); } }); } let result = block_on(future::poll_fn(move |cx| { let mut result = 0usize; loop { if let Poll::Ready(ready) = rxs.poll_next_unpin(cx) { match ready { Some(num) => result = result.wrapping_add(num.unwrap()), None => break, } } } Poll::Ready(expected) })); assert_eq!(expected, result); result } } criterion_group!(unordered, polling_benchmark); criterion_main!(unordered);
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Win32_System_Com_StructuredStorage")] #[inline] pub unsafe fn BindIFilterFromStorage<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::StructuredStorage::IStorage>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pstg: Param0, punkouter: Param1, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn BindIFilterFromStorage(pstg: ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } BindIFilterFromStorage(pstg.into_param().abi(), punkouter.into_param().abi(), ::core::mem::transmute(ppiunk)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_System_Com")] #[inline] pub unsafe fn BindIFilterFromStream<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pstm: Param0, punkouter: Param1, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn BindIFilterFromStream(pstm: ::windows::core::RawPtr, punkouter: ::windows::core::RawPtr, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } BindIFilterFromStream(pstm.into_param().abi(), punkouter.into_param().abi(), ::core::mem::transmute(ppiunk)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct CHUNKSTATE(pub i32); pub const CHUNK_TEXT: CHUNKSTATE = CHUNKSTATE(1i32); pub const CHUNK_VALUE: CHUNKSTATE = CHUNKSTATE(2i32); pub const CHUNK_FILTER_OWNED_VALUE: CHUNKSTATE = CHUNKSTATE(4i32); impl ::core::convert::From<i32> for CHUNKSTATE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CHUNKSTATE { 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 CHUNK_BREAKTYPE(pub i32); pub const CHUNK_NO_BREAK: CHUNK_BREAKTYPE = CHUNK_BREAKTYPE(0i32); pub const CHUNK_EOW: CHUNK_BREAKTYPE = CHUNK_BREAKTYPE(1i32); pub const CHUNK_EOS: CHUNK_BREAKTYPE = CHUNK_BREAKTYPE(2i32); pub const CHUNK_EOP: CHUNK_BREAKTYPE = CHUNK_BREAKTYPE(3i32); pub const CHUNK_EOC: CHUNK_BREAKTYPE = CHUNK_BREAKTYPE(4i32); impl ::core::convert::From<i32> for CHUNK_BREAKTYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CHUNK_BREAKTYPE { type Abi = Self; } pub const CICAT_ALL_OPENED: u32 = 32u32; pub const CICAT_GET_STATE: u32 = 16u32; pub const CICAT_NO_QUERY: u32 = 8u32; pub const CICAT_READONLY: u32 = 2u32; pub const CICAT_STOPPED: u32 = 1u32; pub const CICAT_WRITABLE: u32 = 4u32; pub const CI_PROVIDER_ALL: u32 = 4294967295u32; pub const CI_PROVIDER_INDEXING_SERVICE: u32 = 2u32; pub const CI_PROVIDER_MSSEARCH: u32 = 1u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct CI_STATE { pub cbStruct: u32, pub cWordList: u32, pub cPersistentIndex: u32, pub cQueries: u32, pub cDocuments: u32, pub cFreshTest: u32, pub dwMergeProgress: u32, pub eState: u32, pub cFilteredDocuments: u32, pub cTotalDocuments: u32, pub cPendingScans: u32, pub dwIndexSize: u32, pub cUniqueKeys: u32, pub cSecQDocuments: u32, pub dwPropCacheSize: u32, } impl CI_STATE {} impl ::core::default::Default for CI_STATE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for CI_STATE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("CI_STATE") .field("cbStruct", &self.cbStruct) .field("cWordList", &self.cWordList) .field("cPersistentIndex", &self.cPersistentIndex) .field("cQueries", &self.cQueries) .field("cDocuments", &self.cDocuments) .field("cFreshTest", &self.cFreshTest) .field("dwMergeProgress", &self.dwMergeProgress) .field("eState", &self.eState) .field("cFilteredDocuments", &self.cFilteredDocuments) .field("cTotalDocuments", &self.cTotalDocuments) .field("cPendingScans", &self.cPendingScans) .field("dwIndexSize", &self.dwIndexSize) .field("cUniqueKeys", &self.cUniqueKeys) .field("cSecQDocuments", &self.cSecQDocuments) .field("dwPropCacheSize", &self.dwPropCacheSize) .finish() } } impl ::core::cmp::PartialEq for CI_STATE { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.cWordList == other.cWordList && self.cPersistentIndex == other.cPersistentIndex && self.cQueries == other.cQueries && self.cDocuments == other.cDocuments && self.cFreshTest == other.cFreshTest && self.dwMergeProgress == other.dwMergeProgress && self.eState == other.eState && self.cFilteredDocuments == other.cFilteredDocuments && self.cTotalDocuments == other.cTotalDocuments && self.cPendingScans == other.cPendingScans && self.dwIndexSize == other.dwIndexSize && self.cUniqueKeys == other.cUniqueKeys && self.cSecQDocuments == other.cSecQDocuments && self.dwPropCacheSize == other.dwPropCacheSize } } impl ::core::cmp::Eq for CI_STATE {} unsafe impl ::windows::core::Abi for CI_STATE { type Abi = Self; } pub const CI_STATE_ANNEALING_MERGE: u32 = 8u32; pub const CI_STATE_BATTERY_POLICY: u32 = 262144u32; pub const CI_STATE_BATTERY_POWER: u32 = 2048u32; pub const CI_STATE_CONTENT_SCAN_REQUIRED: u32 = 4u32; pub const CI_STATE_DELETION_MERGE: u32 = 32768u32; pub const CI_STATE_HIGH_CPU: u32 = 131072u32; pub const CI_STATE_HIGH_IO: u32 = 256u32; pub const CI_STATE_INDEX_MIGRATION_MERGE: u32 = 64u32; pub const CI_STATE_LOW_DISK: u32 = 65536u32; pub const CI_STATE_LOW_MEMORY: u32 = 128u32; pub const CI_STATE_MASTER_MERGE: u32 = 2u32; pub const CI_STATE_MASTER_MERGE_PAUSED: u32 = 512u32; pub const CI_STATE_READING_USNS: u32 = 16384u32; pub const CI_STATE_READ_ONLY: u32 = 1024u32; pub const CI_STATE_RECOVERING: u32 = 32u32; pub const CI_STATE_SCANNING: u32 = 16u32; pub const CI_STATE_SHADOW_MERGE: u32 = 1u32; pub const CI_STATE_STARTING: u32 = 8192u32; pub const CI_STATE_USER_ACTIVE: u32 = 4096u32; pub const CI_VERSION_WDS30: u32 = 258u32; pub const CI_VERSION_WDS40: u32 = 265u32; pub const CI_VERSION_WIN70: u32 = 1792u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub struct DBID { pub uGuid: DBID_0, pub eKind: u32, pub uName: DBID_1, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl DBID {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub union DBID_0 { pub guid: ::windows::core::GUID, pub pguid: *mut ::windows::core::GUID, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl DBID_0 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID_0 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] pub union DBID_1 { pub pwszName: super::super::Foundation::PWSTR, pub ulPropid: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl DBID_1 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID_1 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID_1 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID_1 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(2))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub struct DBID { pub uGuid: DBID_0, pub eKind: u32, pub uName: DBID_1, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl DBID {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(2))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub union DBID_0 { pub guid: ::windows::core::GUID, pub pguid: *mut ::windows::core::GUID, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl DBID_0 {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID_0 {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID_0 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C, packed(2))] #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] pub union DBID_1 { pub pwszName: super::super::Foundation::PWSTR, pub ulPropid: u32, } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl DBID_1 {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DBID_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DBID_1 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DBID_1 {} #[cfg(any(target_arch = "x86",))] #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DBID_1 { 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 DBKINDENUM(pub i32); pub const DBKIND_GUID_NAME: DBKINDENUM = DBKINDENUM(0i32); pub const DBKIND_GUID_PROPID: DBKINDENUM = DBKINDENUM(1i32); pub const DBKIND_NAME: DBKINDENUM = DBKINDENUM(2i32); pub const DBKIND_PGUID_NAME: DBKINDENUM = DBKINDENUM(3i32); pub const DBKIND_PGUID_PROPID: DBKINDENUM = DBKINDENUM(4i32); pub const DBKIND_PROPID: DBKINDENUM = DBKINDENUM(5i32); pub const DBKIND_GUID: DBKINDENUM = DBKINDENUM(6i32); impl ::core::convert::From<i32> for DBKINDENUM { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DBKINDENUM { type Abi = Self; } pub const DBPROP_APPLICATION_NAME: u32 = 11u32; pub const DBPROP_CATALOGLISTID: u32 = 9u32; pub const DBPROP_CI_CATALOG_NAME: u32 = 2u32; pub const DBPROP_CI_DEPTHS: u32 = 4u32; pub const DBPROP_CI_EXCLUDE_SCOPES: u32 = 5u32; pub const DBPROP_CI_INCLUDE_SCOPES: u32 = 3u32; pub const DBPROP_CI_PROVIDER: u32 = 8u32; pub const DBPROP_CI_QUERY_TYPE: u32 = 7u32; pub const DBPROP_CI_SCOPE_FLAGS: u32 = 4u32; pub const DBPROP_CI_SECURITY_ID: u32 = 6u32; pub const DBPROP_CLIENT_CLSID: u32 = 3u32; pub const DBPROP_DEFAULT_EQUALS_BEHAVIOR: u32 = 2u32; pub const DBPROP_DEFERCATALOGVERIFICATION: u32 = 8u32; pub const DBPROP_DEFERNONINDEXEDTRIMMING: u32 = 3u32; pub const DBPROP_DONOTCOMPUTEEXPENSIVEPROPS: u32 = 15u32; pub const DBPROP_ENABLEROWSETEVENTS: u32 = 16u32; pub const DBPROP_FIRSTROWS: u32 = 7u32; pub const DBPROP_FREETEXTANYTERM: u32 = 12u32; pub const DBPROP_FREETEXTUSESTEMMING: u32 = 13u32; pub const DBPROP_GENERATEPARSETREE: u32 = 10u32; pub const DBPROP_GENERICOPTIONS_STRING: u32 = 6u32; pub const DBPROP_IGNORENOISEONLYCLAUSES: u32 = 5u32; pub const DBPROP_IGNORESBRI: u32 = 14u32; pub const DBPROP_MACHINE: u32 = 2u32; pub const DBPROP_USECONTENTINDEX: u32 = 2u32; pub const DBPROP_USEEXTENDEDDBTYPES: u32 = 4u32; pub const DBSETFUNC_ALL: u32 = 1u32; pub const DBSETFUNC_DISTINCT: u32 = 2u32; pub const DBSETFUNC_NONE: u32 = 0u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct FILTERREGION { pub idChunk: u32, pub cwcStart: u32, pub cwcExtent: u32, } impl FILTERREGION {} impl ::core::default::Default for FILTERREGION { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for FILTERREGION { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("FILTERREGION").field("idChunk", &self.idChunk).field("cwcStart", &self.cwcStart).field("cwcExtent", &self.cwcExtent).finish() } } impl ::core::cmp::PartialEq for FILTERREGION { fn eq(&self, other: &Self) -> bool { self.idChunk == other.idChunk && self.cwcStart == other.cwcStart && self.cwcExtent == other.cwcExtent } } impl ::core::cmp::Eq for FILTERREGION {} unsafe impl ::windows::core::Abi for FILTERREGION { type Abi = Self; } pub const FILTER_E_ACCESS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215613i32 as _); pub const FILTER_E_EMBEDDING_UNAVAILABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215609i32 as _); pub const FILTER_E_END_OF_CHUNKS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215616i32 as _); pub const FILTER_E_LINK_UNAVAILABLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215608i32 as _); pub const FILTER_E_NO_MORE_TEXT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215615i32 as _); pub const FILTER_E_NO_MORE_VALUES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215614i32 as _); pub const FILTER_E_NO_TEXT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215611i32 as _); pub const FILTER_E_NO_VALUES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215610i32 as _); pub const FILTER_E_PASSWORD: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215605i32 as _); pub const FILTER_E_UNKNOWNFORMAT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147215604i32 as _); pub const FILTER_S_LAST_TEXT: ::windows::core::HRESULT = ::windows::core::HRESULT(268041i32 as _); pub const FILTER_S_LAST_VALUES: ::windows::core::HRESULT = ::windows::core::HRESULT(268042i32 as _); pub const FILTER_W_MONIKER_CLIPPED: ::windows::core::HRESULT = ::windows::core::HRESULT(268036i32 as _); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] pub struct FULLPROPSPEC { pub guidPropSet: ::windows::core::GUID, pub psProperty: super::super::System::Com::StructuredStorage::PROPSPEC, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl FULLPROPSPEC {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::default::Default for FULLPROPSPEC { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::cmp::PartialEq for FULLPROPSPEC { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::cmp::Eq for FULLPROPSPEC {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] unsafe impl ::windows::core::Abi for FULLPROPSPEC { type Abi = Self; } pub const GENERATE_METHOD_EXACT: u32 = 0u32; pub const GENERATE_METHOD_INFLECT: u32 = 2u32; pub const GENERATE_METHOD_PREFIX: u32 = 1u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct IFILTER_FLAGS(pub i32); pub const IFILTER_FLAGS_OLE_PROPERTIES: IFILTER_FLAGS = IFILTER_FLAGS(1i32); impl ::core::convert::From<i32> for IFILTER_FLAGS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for IFILTER_FLAGS { 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 IFILTER_INIT(pub i32); pub const IFILTER_INIT_CANON_PARAGRAPHS: IFILTER_INIT = IFILTER_INIT(1i32); pub const IFILTER_INIT_HARD_LINE_BREAKS: IFILTER_INIT = IFILTER_INIT(2i32); pub const IFILTER_INIT_CANON_HYPHENS: IFILTER_INIT = IFILTER_INIT(4i32); pub const IFILTER_INIT_CANON_SPACES: IFILTER_INIT = IFILTER_INIT(8i32); pub const IFILTER_INIT_APPLY_INDEX_ATTRIBUTES: IFILTER_INIT = IFILTER_INIT(16i32); pub const IFILTER_INIT_APPLY_OTHER_ATTRIBUTES: IFILTER_INIT = IFILTER_INIT(32i32); pub const IFILTER_INIT_APPLY_CRAWL_ATTRIBUTES: IFILTER_INIT = IFILTER_INIT(256i32); pub const IFILTER_INIT_INDEXING_ONLY: IFILTER_INIT = IFILTER_INIT(64i32); pub const IFILTER_INIT_SEARCH_LINKS: IFILTER_INIT = IFILTER_INIT(128i32); pub const IFILTER_INIT_FILTER_OWNED_VALUE_OK: IFILTER_INIT = IFILTER_INIT(512i32); pub const IFILTER_INIT_FILTER_AGGRESSIVE_BREAK: IFILTER_INIT = IFILTER_INIT(1024i32); pub const IFILTER_INIT_DISABLE_EMBEDDED: IFILTER_INIT = IFILTER_INIT(2048i32); pub const IFILTER_INIT_EMIT_FORMATTING: IFILTER_INIT = IFILTER_INIT(4096i32); impl ::core::convert::From<i32> for IFILTER_INIT { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for IFILTER_INIT { type Abi = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IFilter(pub ::windows::core::IUnknown); impl IFilter { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe fn Init(&self, grfflags: u32, cattributes: u32, aattributes: *const FULLPROPSPEC, pflags: *mut u32) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(grfflags), ::core::mem::transmute(cattributes), ::core::mem::transmute(aattributes), ::core::mem::transmute(pflags))) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe fn GetChunk(&self, pstat: *mut STAT_CHUNK) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pstat))) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetText(&self, pcwcbuffer: *mut u32, awcbuffer: super::super::Foundation::PWSTR) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcwcbuffer), ::core::mem::transmute(awcbuffer))) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe fn GetValue(&self, pppropvalue: *mut *mut super::super::System::Com::StructuredStorage::PROPVARIANT) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pppropvalue))) } pub unsafe fn BindRegion<'a, Param0: ::windows::core::IntoParam<'a, FILTERREGION>>(&self, origpos: Param0, riid: *const ::windows::core::GUID, ppunk: *mut *mut ::core::ffi::c_void) -> i32 { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), origpos.into_param().abi(), ::core::mem::transmute(riid), ::core::mem::transmute(ppunk))) } } unsafe impl ::windows::core::Interface for IFilter { type Vtable = IFilter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x89bcb740_6119_101a_bcb7_00dd010655af); } impl ::core::convert::From<IFilter> for ::windows::core::IUnknown { fn from(value: IFilter) -> Self { value.0 } } impl ::core::convert::From<&IFilter> for ::windows::core::IUnknown { fn from(value: &IFilter) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IFilter { 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 IFilter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IFilter_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_StructuredStorage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, grfflags: u32, cattributes: u32, aattributes: *const FULLPROPSPEC, pflags: *mut u32) -> i32, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstat: *mut STAT_CHUNK) -> i32, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage")))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcwcbuffer: *mut u32, awcbuffer: super::super::Foundation::PWSTR) -> i32, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Com_StructuredStorage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pppropvalue: *mut *mut super::super::System::Com::StructuredStorage::PROPVARIANT) -> i32, #[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, origpos: FILTERREGION, riid: *const ::windows::core::GUID, ppunk: *mut *mut ::core::ffi::c_void) -> i32, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IPhraseSink(pub ::windows::core::IUnknown); impl IPhraseSink { #[cfg(feature = "Win32_Foundation")] pub unsafe fn PutSmallPhrase<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwcnoun: Param0, cwcnoun: u32, pwcmodifier: Param2, cwcmodifier: u32, ulattachmenttype: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pwcnoun.into_param().abi(), ::core::mem::transmute(cwcnoun), pwcmodifier.into_param().abi(), ::core::mem::transmute(cwcmodifier), ::core::mem::transmute(ulattachmenttype)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn PutPhrase<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwcphrase: Param0, cwcphrase: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pwcphrase.into_param().abi(), ::core::mem::transmute(cwcphrase)).ok() } } unsafe impl ::windows::core::Interface for IPhraseSink { type Vtable = IPhraseSink_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcc906ff0_c058_101a_b554_08002b33b0e6); } impl ::core::convert::From<IPhraseSink> for ::windows::core::IUnknown { fn from(value: IPhraseSink) -> Self { value.0 } } impl ::core::convert::From<&IPhraseSink> for ::windows::core::IUnknown { fn from(value: &IPhraseSink) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IPhraseSink { 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 IPhraseSink { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IPhraseSink_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_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwcnoun: super::super::Foundation::PWSTR, cwcnoun: u32, pwcmodifier: super::super::Foundation::PWSTR, cwcmodifier: u32, ulattachmenttype: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwcphrase: super::super::Foundation::PWSTR, cwcphrase: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); pub const LIFF_FORCE_TEXT_FILTER_FALLBACK: u32 = 3u32; pub const LIFF_IMPLEMENT_TEXT_FILTER_FALLBACK_POLICY: u32 = 2u32; pub const LIFF_LOAD_DEFINED_FILTER: u32 = 1u32; #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoadIFilter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(pwcspath: Param0, punkouter: Param1, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoadIFilter(pwcspath: super::super::Foundation::PWSTR, punkouter: ::windows::core::RawPtr, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } LoadIFilter(pwcspath.into_param().abi(), punkouter.into_param().abi(), ::core::mem::transmute(ppiunk)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn LoadIFilterEx<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(pwcspath: Param0, dwflags: u32, riid: *const ::windows::core::GUID, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn LoadIFilterEx(pwcspath: super::super::Foundation::PWSTR, dwflags: u32, riid: *const ::windows::core::GUID, ppiunk: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } LoadIFilterEx(pwcspath.into_param().abi(), ::core::mem::transmute(dwflags), ::core::mem::transmute(riid), ::core::mem::transmute(ppiunk)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } pub const MSIDXSPROP_COMMAND_LOCALE_STRING: u32 = 3u32; pub const MSIDXSPROP_MAX_RANK: u32 = 6u32; pub const MSIDXSPROP_PARSE_TREE: u32 = 5u32; pub const MSIDXSPROP_QUERY_RESTRICTION: u32 = 4u32; pub const MSIDXSPROP_RESULTS_FOUND: u32 = 7u32; pub const MSIDXSPROP_ROWSETQUERYSTATUS: u32 = 2u32; pub const MSIDXSPROP_SAME_SORTORDER_USED: u32 = 14u32; pub const MSIDXSPROP_SERVER_NLSVERSION: u32 = 12u32; pub const MSIDXSPROP_SERVER_NLSVER_DEFINED: u32 = 13u32; pub const MSIDXSPROP_SERVER_VERSION: u32 = 9u32; pub const MSIDXSPROP_SERVER_WINVER_MAJOR: u32 = 10u32; pub const MSIDXSPROP_SERVER_WINVER_MINOR: u32 = 11u32; pub const MSIDXSPROP_WHEREID: u32 = 8u32; pub const NOT_AN_ERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(524288i32 as _); pub const PID_FILENAME: u32 = 100u32; pub const PROPID_QUERY_ALL: u32 = 6u32; pub const PROPID_QUERY_HITCOUNT: u32 = 4u32; pub const PROPID_QUERY_LASTSEENTIME: u32 = 10u32; pub const PROPID_QUERY_RANK: u32 = 3u32; pub const PROPID_QUERY_RANKVECTOR: u32 = 2u32; pub const PROPID_QUERY_UNFILTERED: u32 = 7u32; pub const PROPID_QUERY_VIRTUALPATH: u32 = 9u32; pub const PROPID_QUERY_WORKID: u32 = 5u32; pub const PROPID_STG_CONTENTS: u32 = 19u32; pub const PROXIMITY_UNIT_CHAPTER: u32 = 3u32; pub const PROXIMITY_UNIT_PARAGRAPH: u32 = 2u32; pub const PROXIMITY_UNIT_SENTENCE: u32 = 1u32; pub const PROXIMITY_UNIT_WORD: u32 = 0u32; pub const QUERY_DEEP: u32 = 1u32; pub const QUERY_PHYSICAL_PATH: u32 = 0u32; pub const QUERY_SHALLOW: u32 = 0u32; pub const QUERY_VIRTUAL_PATH: u32 = 2u32; pub const SCOPE_FLAG_DEEP: u32 = 2u32; pub const SCOPE_FLAG_INCLUDE: u32 = 1u32; pub const SCOPE_FLAG_MASK: u32 = 255u32; pub const SCOPE_TYPE_MASK: u32 = 4294967040u32; pub const SCOPE_TYPE_VPATH: u32 = 512u32; pub const SCOPE_TYPE_WINPATH: u32 = 256u32; pub const STAT_BUSY: u32 = 0u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] pub struct STAT_CHUNK { pub idChunk: u32, pub breakType: CHUNK_BREAKTYPE, pub flags: CHUNKSTATE, pub locale: u32, pub attribute: FULLPROPSPEC, pub idChunkSource: u32, pub cwcStartSource: u32, pub cwcLenSource: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl STAT_CHUNK {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::default::Default for STAT_CHUNK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::cmp::PartialEq for STAT_CHUNK { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] impl ::core::cmp::Eq for STAT_CHUNK {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com_StructuredStorage"))] unsafe impl ::windows::core::Abi for STAT_CHUNK { type Abi = Self; } pub const STAT_COALESCE_COMP_ALL_NOISE: u32 = 8192u32; pub const STAT_CONTENT_OUT_OF_DATE: u32 = 32u32; pub const STAT_CONTENT_QUERY_INCOMPLETE: u32 = 128u32; pub const STAT_DONE: u32 = 2u32; pub const STAT_ERROR: u32 = 1u32; pub const STAT_MISSING_PROP_IN_RELDOC: u32 = 2048u32; pub const STAT_MISSING_RELDOC: u32 = 1024u32; pub const STAT_NOISE_WORDS: u32 = 16u32; pub const STAT_PARTIAL_SCOPE: u32 = 8u32; pub const STAT_REFRESH: u32 = 3u32; pub const STAT_REFRESH_INCOMPLETE: u32 = 64u32; pub const STAT_RELDOC_ACCESS_DENIED: u32 = 4096u32; pub const STAT_SHARING_VIOLATION: u32 = 512u32; pub const STAT_TIME_LIMIT_EXCEEDED: u32 = 256u32; pub const VECTOR_RANK_DICE: u32 = 3u32; pub const VECTOR_RANK_INNER: u32 = 2u32; pub const VECTOR_RANK_JACCARD: u32 = 4u32; pub const VECTOR_RANK_MAX: u32 = 1u32; pub const VECTOR_RANK_MIN: u32 = 0u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WORDREP_BREAK_TYPE(pub i32); pub const WORDREP_BREAK_EOW: WORDREP_BREAK_TYPE = WORDREP_BREAK_TYPE(0i32); pub const WORDREP_BREAK_EOS: WORDREP_BREAK_TYPE = WORDREP_BREAK_TYPE(1i32); pub const WORDREP_BREAK_EOP: WORDREP_BREAK_TYPE = WORDREP_BREAK_TYPE(2i32); pub const WORDREP_BREAK_EOC: WORDREP_BREAK_TYPE = WORDREP_BREAK_TYPE(3i32); impl ::core::convert::From<i32> for WORDREP_BREAK_TYPE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WORDREP_BREAK_TYPE { type Abi = Self; }
use std::error::Error as StdError; use std::fmt::{self, Display}; use crate::error::DatabaseError; use crate::postgres::protocol::Response; #[derive(Debug)] pub struct PgError(pub(super) Response); impl DatabaseError for PgError { fn message(&self) -> &str { &self.0.message } fn code(&self) -> Option<&str> { Some(&self.0.code) } fn details(&self) -> Option<&str> { self.0.detail.as_ref().map(|s| &**s) } fn hint(&self) -> Option<&str> { self.0.hint.as_ref().map(|s| &**s) } fn table_name(&self) -> Option<&str> { self.0.table.as_ref().map(|s| &**s) } fn column_name(&self) -> Option<&str> { self.0.column.as_ref().map(|s| &**s) } fn constraint_name(&self) -> Option<&str> { self.0.constraint.as_ref().map(|s| &**s) } fn as_ref_err(&self) -> &(dyn StdError + Send + Sync + 'static) { self } fn as_mut_err(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) { self } fn into_box_err(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static> { self } } impl Display for PgError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(self.message()) } } impl StdError for PgError {} impl From<PgError> for crate::Error { fn from(err: PgError) -> Self { crate::Error::Database(Box::new(err)) } } #[test] fn test_error_downcasting() { use super::protocol::Severity; let error = PgError(Response { severity: Severity::Panic, code: "".into(), message: "".into(), detail: None, hint: None, position: None, internal_position: None, internal_query: None, where_: None, schema: None, table: None, column: None, data_type: None, constraint: None, file: None, line: None, routine: None, }); let error = crate::Error::from(error); let db_err = match error { crate::Error::Database(db_err) => db_err, e => panic!("expected Error::Database, got {:?}", e), }; assert_eq!(db_err.downcast_ref::<PgError>().0.severity, Severity::Panic); assert_eq!(db_err.downcast::<PgError>().0.severity, Severity::Panic); }
#![allow(clippy::comparison_chain)] #![allow(clippy::collapsible_if)] use std::cmp::Reverse; use std::cmp::{max, min}; use std::collections::{BTreeSet, HashMap, HashSet}; 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 (h, w): (usize, usize) = parse_line().unwrap(); let mut map: Vec<Vec<usize>> = vec![]; for _ in 0..h { map.push(parse_line().unwrap()); } let mut ans = std::usize::MIN; for mut bits in 1..2_u64.pow(map.len() as u32) { let mut vv = vec![]; for i in 0..map.len() { if bits % 2 == 1 { vv.push(&map[i]); } bits /= 2; } let hi = vv.len(); // filter let tmp: Vec<usize> = tench(vv) .into_iter() .filter(|i| i.iter().all_equal()) .map(|i| i[0]) .collect(); let mut count: HashMap<usize, usize> = HashMap::new(); for t in tmp { let e = count.entry(t).or_default(); *e += 1; } let mut maxv = std::usize::MIN; for (k, v) in count.iter() { maxv = maxv.max(*v); } ans = ans.max(hi * maxv); } println!("{}", ans); } fn tench(v: Vec<&Vec<usize>>) -> Vec<Vec<usize>> { if v.len() == 0 { panic!("wtf"); } let h = v.len(); let w = v[0].len(); let mut ans = vec![vec![0; h]; w]; for i in 0..h { for j in 0..w { ans[j][i] = v[i][j]; } } ans }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[cfg(feature = "Phone_Speech_Recognition")] pub mod Recognition;
// OpenTimestamps Viewer // Written in 2017 by // Andrew Poelstra <rust-ots@wpsoftware.net> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the CC0 Public Domain Dedication // along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // //! # Multipart Stream //! //! Shim to allow streaming of multipart data //! use std::io::Read; use multipart::server::{Multipart, MultipartData, ReadEntryResult}; use rocket::{Request, Data, Outcome}; use rocket::data::{self, FromData}; use rocket::http::Status; const SIZE_LIMIT: u64 = 32768; /// A wrapper around a multipart stream pub struct MultipartStream { pub stream: Box<dyn Read> } impl<'a> FromData<'a> for MultipartStream { type Error = &'static str; type Owned = &'static str; type Borrowed = &'static str; fn from_data(request: &Request, data: Data) -> data::Outcome<Self, Self::Error> { let ct = match request.headers().get_one("Content-Type") { Some(ct) => ct, None => { return Outcome::Failure((Status::BadRequest, "no Content-Type in request")); } }; let idx = match ct.find("boundary=") { Some(idx) => idx, None => { return Outcome::Failure((Status::BadRequest, "no boundary= in Content-Type")); } }; let boundary = &ct[(idx + "boundary=".len())..]; let mp = Multipart::with_body(data.open(), boundary); if let ReadEntryResult::Entry(entry) = mp.into_entry() { if entry.name == "file" { if let MultipartData::File(file) = entry.data { Outcome::Success(MultipartStream { stream: Box::new(file.take(SIZE_LIMIT)) }) } else { Outcome::Failure((Status::BadRequest, "malformed multipart data")) } } else { Outcome::Failure((Status::BadRequest, "malformed multipart data")) } } else { Outcome::Failure((Status::BadRequest, "missing multipart data")) } } }
//! Many of this code is from: https://github.com/RustPython/RustPython //! Different token definitions. //! Loosely based on token.h from CPython source: use std::fmt::{self, Write}; /// Python source code can be tokenized in a sequence of these tokens. #[derive(Clone, Debug, PartialEq)] pub enum Tok { Name { name: String }, UInt { value: u64 }, Int { value: i64 }, Float { value: f64 }, String { value: String }, Bytes { value: Vec<u8> }, StartFile, Newline, Indent, Dedent, EndOfFile, Comma, Lpar, Rpar, Lbrace, Rbrace, Lbracket, Rbracket, Colon, Equal, NodeIdx, Dot, Add, Sub, Mul, Div, Mod, Pow, And, Xor, Or, BoolYes, BoolNo, WithDef, WithSet, LetDef, LetBool, LetInt, LetReal, LetDim, NodeDef, NodeExtern, NodeData, NodeOptim, NodeExec, UseDef, UseBy, } impl fmt::Display for Tok { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use Tok::*; match self { Name { name } => write!(f, "'{}'", name), UInt { value } => write!(f, "'{}'", value), Int { value } => write!(f, "'{}'", value), Float { value } => write!(f, "'{}'", value), String { value } => write!(f, "{:?}", value), Bytes { value } => { write!(f, "b\"")?; for i in value { match i { 0..=8 => write!(f, "\\x0{}", i)?, 9 => f.write_str("\\t")?, 10 => f.write_str("\\n")?, 11 => write!(f, "\\x0{:x}", i)?, 13 => f.write_str("\\r")?, 32..=126 => f.write_char(*i as char)?, _ => write!(f, "\\x{:x}", i)?, } } f.write_str("\"") } StartFile => f.write_str("StartFile"), Newline => f.write_str("Newline"), Indent => f.write_str("Indent"), Dedent => f.write_str("Dedent"), EndOfFile => f.write_str("EOF"), Comma => f.write_str("','"), Lpar => f.write_str("'('"), Rpar => f.write_str("')'"), Lbrace => f.write_str("'{'"), Rbrace => f.write_str("'}'"), Lbracket => f.write_str("'['"), Rbracket => f.write_str("']'"), Colon => f.write_str("':'"), Equal => f.write_str("'='"), NodeIdx => f.write_str("'$'"), Dot => f.write_str("'.'"), Add => f.write_str("'+'"), Sub => f.write_str("'-'"), Mul => f.write_str("'*'"), Div => f.write_str("'/'"), Mod => f.write_str("'%'"), Pow => f.write_str("'**'"), And => f.write_str("'&'"), Xor => f.write_str("'^'"), Or => f.write_str("'|'"), BoolYes => f.write_str("'yes'"), BoolNo => f.write_str("'no'"), WithDef => f.write_str("'with'"), WithSet => f.write_str("'set'"), LetDef => f.write_str("'let'"), LetBool => f.write_str("'bool'"), LetInt => f.write_str("'int'"), LetReal => f.write_str("'real'"), LetDim => f.write_str("'dim'"), NodeDef => f.write_str("'node'"), NodeExtern => f.write_str("'extern'"), NodeData => f.write_str("'data'"), NodeOptim => f.write_str("'optim'"), NodeExec => f.write_str("'exec'"), UseDef => f.write_str("'use'"), UseBy => f.write_str("'by'"), } } }
use std::cmp; use std::io::{self, Read, Write}; use bytes::{Buf, BufMut, Bytes, IntoBuf}; use futures::{Async, Poll}; use tokio_io::{AsyncRead, AsyncWrite}; /// Combine a buffer with an IO, rewinding reads to use the buffer. #[derive(Debug)] pub(crate) struct Rewind<T> { pre: Option<Bytes>, inner: T, } impl<T> Rewind<T> { pub(crate) fn new(io: T) -> Self { Rewind { pre: None, inner: io, } } pub(crate) fn new_buffered(io: T, buf: Bytes) -> Self { Rewind { pre: Some(buf), inner: io, } } pub(crate) fn rewind(&mut self, bs: Bytes) { debug_assert!(self.pre.is_none()); self.pre = Some(bs); } pub(crate) fn into_inner(self) -> (T, Bytes) { (self.inner, self.pre.unwrap_or_else(Bytes::new)) } } impl<T> Read for Rewind<T> where T: Read, { #[inline] fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { if let Some(pre_bs) = self.pre.take() { // If there are no remaining bytes, let the bytes get dropped. if pre_bs.len() > 0 { let mut pre_reader = pre_bs.into_buf().reader(); let read_cnt = pre_reader.read(buf)?; let mut new_pre = pre_reader.into_inner().into_inner(); new_pre.advance(read_cnt); // Put back whats left if new_pre.len() > 0 { self.pre = Some(new_pre); } return Ok(read_cnt); } } self.inner.read(buf) } } impl<T> Write for Rewind<T> where T: Write, { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.inner.write(buf) } #[inline] fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } impl<T> AsyncRead for Rewind<T> where T: AsyncRead, { #[inline] unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool { self.inner.prepare_uninitialized_buffer(buf) } #[inline] fn read_buf<B: BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { if let Some(bs) = self.pre.take() { let pre_len = bs.len(); // If there are no remaining bytes, let the bytes get dropped. if pre_len > 0 { let cnt = cmp::min(buf.remaining_mut(), pre_len); let pre_buf = bs.into_buf(); let mut xfer = Buf::take(pre_buf, cnt); buf.put(&mut xfer); let mut new_pre = xfer.into_inner().into_inner(); new_pre.advance(cnt); // Put back whats left if new_pre.len() > 0 { self.pre = Some(new_pre); } return Ok(Async::Ready(cnt)); } } self.inner.read_buf(buf) } } impl<T> AsyncWrite for Rewind<T> where T: AsyncWrite, { #[inline] fn shutdown(&mut self) -> Poll<(), io::Error> { AsyncWrite::shutdown(&mut self.inner) } #[inline] fn write_buf<B: Buf>(&mut self, buf: &mut B) -> Poll<usize, io::Error> { self.inner.write_buf(buf) } } #[cfg(test)] mod tests { use super::*; extern crate tokio_mockstream; use self::tokio_mockstream::MockStream; use std::io::Cursor; // Test a partial rewind #[test] fn async_partial_rewind() { let bs = &mut [104, 101, 108, 108, 111]; let o1 = &mut [0, 0]; let o2 = &mut [0, 0, 0, 0, 0]; let mut stream = Rewind::new(MockStream::new(bs)); let mut o1_cursor = Cursor::new(o1); // Read off some bytes, ensure we filled o1 match stream.read_buf(&mut o1_cursor).unwrap() { Async::NotReady => panic!("should be ready"), Async::Ready(cnt) => assert_eq!(2, cnt), } // Rewind the stream so that it is as if we never read in the first place. let read_buf = Bytes::from(&o1_cursor.into_inner()[..]); stream.rewind(read_buf); // We poll 2x here since the first time we'll only get what is in the // prefix (the rewinded part) of the Rewind.\ let mut o2_cursor = Cursor::new(o2); stream.read_buf(&mut o2_cursor).unwrap(); stream.read_buf(&mut o2_cursor).unwrap(); let o2_final = o2_cursor.into_inner(); // At this point we should have read everything that was in the MockStream assert_eq!(&o2_final, &bs); } // Test a full rewind #[test] fn async_full_rewind() { let bs = &mut [104, 101, 108, 108, 111]; let o1 = &mut [0, 0, 0, 0, 0]; let o2 = &mut [0, 0, 0, 0, 0]; let mut stream = Rewind::new(MockStream::new(bs)); let mut o1_cursor = Cursor::new(o1); match stream.read_buf(&mut o1_cursor).unwrap() { Async::NotReady => panic!("should be ready"), Async::Ready(cnt) => assert_eq!(5, cnt), } let read_buf = Bytes::from(&o1_cursor.into_inner()[..]); stream.rewind(read_buf); let mut o2_cursor = Cursor::new(o2); stream.read_buf(&mut o2_cursor).unwrap(); stream.read_buf(&mut o2_cursor).unwrap(); let o2_final = o2_cursor.into_inner(); assert_eq!(&o2_final, &bs); } #[test] fn partial_rewind() { let bs = &mut [104, 101, 108, 108, 111]; let o1 = &mut [0, 0]; let o2 = &mut [0, 0, 0, 0, 0]; let mut stream = Rewind::new(MockStream::new(bs)); stream.read(o1).unwrap(); let read_buf = Bytes::from(&o1[..]); stream.rewind(read_buf); let cnt = stream.read(o2).unwrap(); stream.read(&mut o2[cnt..]).unwrap(); assert_eq!(&o2, &bs); } #[test] fn full_rewind() { let bs = &mut [104, 101, 108, 108, 111]; let o1 = &mut [0, 0, 0, 0, 0]; let o2 = &mut [0, 0, 0, 0, 0]; let mut stream = Rewind::new(MockStream::new(bs)); stream.read(o1).unwrap(); let read_buf = Bytes::from(&o1[..]); stream.rewind(read_buf); let cnt = stream.read(o2).unwrap(); stream.read(&mut o2[cnt..]).unwrap(); assert_eq!(&o2, &bs); } }
use mysql as my; use mysql::params; pub fn insert_temporary_user(email: &str, password: &str, salt: &str, cypher: &str) { let pool = my::Pool::new("mysql://shin:0523@localhost:3306/db").unwrap(); let mut stmt = pool.prepare(r"INSERT INTO temporary_users (mail, password, salt, cypher) VALUES (:mail, :password, :salt, :cypher)").unwrap(); stmt.execute(params!{ "mail" => email, "password" => password, "salt" => &salt, "cypher" => &cypher, }).unwrap(); println!("{:?}", email); println!("{:?}", password); println!("{:?}", salt); println!("{:?}", cypher); } pub fn select_temporary_user_salt(email: &str) -> (String, String) { let pool = my::Pool::new("mysql://shin:0523@localhost:3306/db").unwrap(); let mut stmt = pool.prepare(r"SELECT salt, password FROM temporary_users WHERE mail = :mail").unwrap(); let mut row = stmt.execute(params!{ "mail" => &email,}).unwrap(); match row.next().unwrap() { Ok(row_salt) => { my::from_row(row_salt) }, Err(msg) => panic!("There is no record {}", msg), } }
//! Irq-safe locking via Mutex and RwLock. //! Identical behavior to the regular `spin` crate's //! Mutex and RwLock, with the added behavior of holding interrupts //! for the duration of the Mutex guard. #![cfg_attr(feature = "const_fn", feature(const_fn))] #![feature(asm)] #![feature(manually_drop)] #![no_std] extern crate spin; extern crate owning_ref; extern crate stable_deref_trait; pub use mutex_irqsafe::*; pub use rwlock_irqsafe::*; pub use held_interrupts::*; mod mutex_irqsafe; mod rwlock_irqsafe; mod held_interrupts;
use std::cmp::{max, min}; use std::collections::{HashMap, HashSet}; use itertools::Itertools; use whiteread::parse_line; fn main() { let (n, m): (usize, usize) = parse_line().unwrap(); let mut pp: Vec<usize> = vec![]; for _ in 0..n { pp.push(parse_line().unwrap()); } let mut two = vec![]; for i in 0..n + 1 { for j in 0..n + 1 { let iv = if i == n { 0 } else { pp[i] }; let jv = if j == n { 0 } else { pp[j] }; two.push(iv + jv); } } two.sort_by(|a, b| b.cmp(&a)); let mut ans = 0; for j in two.iter() { if j > &m { continue; } let mut left = 0; let mut right = two.len(); while left < right { let pivot = (right + left) / 2; if two[pivot] + j <= m { right = pivot; } else { left = pivot + 1; } } if left >= two.len() { left = two.len() - 1; } ans = max(ans, two[left] + j); } println!("{}", ans); }
use std::io::TcpStream; use std::io::IoResult; use std::rand; use std::rand::Rng; use std::io::Timer; use std::time::duration::Duration; fn main() { let mut socket: TcpStream = TcpStream::connect("127.0.0.1", 8000).unwrap(); let interval = Duration::milliseconds(1000); let mut timer = Timer::new().unwrap(); let mut rng = rand::task_rng(); let two_pi = 6.28318530718; let namespace: &str = "house1.first-floor.sensor1"; send_str(namespace, &mut socket).unwrap(); // Iterate 100000 times (long enough to test out things) for i in range(0f64, 10000f64) { // Start a one second timer let oneshot: Receiver<()> = timer.oneshot(interval); println!("Wait {} ms...", interval.num_milliseconds()); // Block the task until notification arrives (aka the timer is done) oneshot.recv(); // Generate a random number (alternates between -40 and 40 slowly) let mid: f64 = (i / two_pi).sin(); let num: f64 = rng.gen_range(mid * 40.0 - 1.0, mid * 40.0 + 1.0); // Send the random number through sockets to the server match socket.write_be_f64(num) { Ok(x) => println!("{}", x), Err(x) => println!("{}", x), } println!("sent {}", num) } drop(socket) } fn send_str(string: &str, socket: &mut TcpStream) -> IoResult<()> { try!(socket.write_be_uint(string.len())); socket.write(string.as_bytes()) }
//! Helper types for constructing strings and arrays composed of other strings and arrays. //! //! These datatypes are special-cased for small composite collections , //! whose indices fit in a u16. use std::{ borrow::Borrow, convert::TryFrom, fmt::{Debug, Display}, marker::PhantomData, ops::{Add, Range}, }; use as_derive_utils::{return_syn_err, to_stream}; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::ToTokens; use crate::common_tokens::StartLenTokens; /// A `{start:16,len:u16}` range. pub type SmallStartLen = StartLen<u16>; /// A `{start:N,len:N}` range. #[derive(Copy, Clone, Debug, PartialEq, Eq, Ord, PartialOrd)] pub struct StartLen<N> { pub start: N, pub len: N, } impl StartLen<u16> { abi_stable_shared::declare_start_len_bit_methods! {} } impl<N> StartLen<N> { #[inline] pub(crate) fn from_start_len(start: usize, len: usize) -> Self where N: TryFrom<usize>, N::Error: Debug, { Self { start: N::try_from(start).unwrap(), len: N::try_from(len).unwrap(), } } #[inline] pub const fn new(start: N, len: N) -> Self { Self { start, len } } #[allow(dead_code)] pub(crate) fn into_range(self) -> Range<N> where N: Copy + Add<N, Output = N>, { self.start..(self.start + self.len) } #[inline] pub(crate) fn tokenizer(self, ctokens: &StartLenTokens) -> StartLenTokenizer<'_, N> { StartLenTokenizer { start: self.start, len: self.len, ctokens, } } } impl StartLen<u16> { pub const DUMMY: Self = Self { start: (1u16 << 15) + 1, len: (1u16 << 15) + 1, }; pub const EMPTY: Self = Self { start: 0, len: 0 }; /// The start of this range. #[inline] pub const fn start(self) -> usize { self.start as usize } #[inline] pub const fn len(self) -> usize { self.len as usize } /// Converts this StartLen to a u32. pub const fn to_u32(self) -> u32 { self.start as u32 | ((self.len as u32) << 16) } pub fn check_ident_length(&self, span: Span) -> Result<(), syn::Error> { if self.len > Self::IDENT_MAX_LEN { return_syn_err!( span, "Identifier is too long,it must be at most {} bytes.", Self::IDENT_MAX_LEN, ); } Ok(()) } } pub struct StartLenTokenizer<'a, N> { start: N, len: N, ctokens: &'a StartLenTokens, } impl<'a, N> ToTokens for StartLenTokenizer<'a, N> where N: ToTokens, { fn to_tokens(&self, ts: &mut TokenStream2) { use syn::token::{Colon2, Comma, Paren}; let ct = self.ctokens; to_stream!(ts; ct.start_len,Colon2::default(),ct.new ); Paren::default().surround(ts, |ts| { to_stream!(ts; self.start,Comma::default(),self.len ); }); } } /////////////////////////////////////////////////////////////////////// #[allow(dead_code)] pub type SmallCompositeString = CompositeString<u16>; /// A String-like type, /// returning a `{start:16,len:u16}` range from methods that extend it. pub struct CompositeString<N> { buffer: String, _integer: PhantomData<N>, } #[allow(dead_code)] impl<N> CompositeString<N> where N: TryFrom<usize>, N::Error: Debug, { pub fn new() -> Self { Self { buffer: String::with_capacity(128), _integer: PhantomData, } } fn len(&self) -> usize { self.buffer.len() } pub fn push_str(&mut self, s: &str) -> StartLen<N> { let start = self.len(); self.buffer.push_str(s); StartLen::from_start_len(start, s.len()) } pub fn push_display<D>(&mut self, s: &D) -> StartLen<N> where D: Display, { use std::fmt::Write; let start = self.len(); let _ = write!(self.buffer, "{}", s); StartLen::from_start_len(start, self.len() - start) } #[allow(dead_code)] pub fn extend_with_str<I>(&mut self, separator: &str, iter: I) -> StartLen<N> where I: IntoIterator, I::Item: Borrow<str>, { let start = self.len(); for s in iter { self.buffer.push_str(s.borrow()); self.buffer.push_str(separator); } StartLen::from_start_len(start, self.len() - start) } pub fn extend_with_display<I>(&mut self, separator: &str, iter: I) -> StartLen<N> where I: IntoIterator, I::Item: Display, { use std::fmt::Write; let start = self.len(); for elem in iter { let _ = write!(self.buffer, "{}", elem); self.buffer.push_str(separator); } StartLen::from_start_len(start, self.len() - start) } pub fn into_inner(self) -> String { self.buffer } pub fn as_inner(&self) -> &str { &self.buffer } } /////////////////////////////////////////////////////////////////////// pub type SmallCompositeVec<T> = CompositeVec<T, u16>; /// A Vec-like type, /// returning a `{start:16,len:u16}` range from methods that extend it. pub struct CompositeVec<T, N> { list: Vec<T>, _integer: PhantomData<N>, } #[allow(dead_code)] impl<T, N> CompositeVec<T, N> where N: TryFrom<usize>, N::Error: Debug, { pub fn new() -> Self { Self { list: Vec::new(), _integer: PhantomData, } } pub fn with_capacity(capacity: usize) -> Self { Self { list: Vec::with_capacity(capacity), _integer: PhantomData, } } fn len(&self) -> usize { self.list.len() } pub fn push(&mut self, elem: T) -> u16 { let ind = self.len(); self.list.push(elem); ind as u16 } pub fn extend<I>(&mut self, iter: I) -> StartLen<N> where I: IntoIterator<Item = T>, { let start = self.len(); self.list.extend(iter); StartLen::from_start_len(start, self.len() - start) } pub fn into_inner(self) -> Vec<T> { self.list } pub fn as_inner(&self) -> &[T] { &self.list } }
use { failure::Error, fuchsia_async as fasync, fuchsia_syslog as syslog, setui_client_lib::*, structopt::StructOpt, }; #[fasync::run_singlethreaded] async fn main() -> Result<(), Error> { syslog::init_with_tags(&["setui-client"]).expect("Can't init logger"); let command = SettingClient::from_args(); run_command(command).await?; Ok(()) }
use crate::arithmetic_command::ArithmeticCommand; use crate::segment::Segment; #[derive(Debug)] pub enum Command { Arithmetic(ArithmeticCommand), Push(Segment, i32), Pop(Segment, i32), Label(String), GoTo(String), IfGoTo(String), Function(String, i32), Call(String, i32), Return, }
// Copyright (c) 2016 The Rouille developers // 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. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use percent_encoding; use serde; use serde_json; use std::borrow::Cow; use std::fmt; use std::fs::File; use std::io; use std::io::Cursor; use std::io::Read; use Request; use Upgrade; /// Contains a prototype of a response. /// /// The response is only sent to the client when you return the `Response` object from your /// request handler. This means that you are free to create as many `Response` objects as you want. pub struct Response { /// The status code to return to the user. pub status_code: u16, /// List of headers to be returned in the response. /// /// The value of the following headers will be ignored from this list, even if present: /// /// - Accept-Ranges /// - Connection /// - Content-Length /// - Content-Range /// - Trailer /// - Transfer-Encoding /// /// Additionally, the `Upgrade` header is ignored as well unless the `upgrade` field of the /// `Response` is set to something. /// /// The reason for this is that these headers are too low-level and are directly handled by /// the underlying HTTP response system. /// /// The value of `Content-Length` is automatically determined by the `ResponseBody` object of /// the `data` member. /// /// If you want to send back `Connection: upgrade`, you should set the value of the `upgrade` /// field to something. pub headers: Vec<(Cow<'static, str>, Cow<'static, str>)>, /// An opaque type that contains the body of the response. pub data: ResponseBody, /// If set, rouille will give ownership of the client socket to the `Upgrade` object. /// /// In all circumstances, the value of the `Connection` header is managed by the framework and /// cannot be customized. If this value is set, the response will automatically contain /// `Connection: Upgrade`. pub upgrade: Option<Box<dyn Upgrade + Send>>, } impl fmt::Debug for Response { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Response") .field("status_code", &self.status_code) .field("headers", &self.headers) .finish() } } impl Response { /// Returns true if the status code of this `Response` indicates success. /// /// This is the range [200-399]. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::text("hello world"); /// assert!(response.is_success()); /// ``` #[inline] pub fn is_success(&self) -> bool { self.status_code >= 200 && self.status_code < 400 } /// Shortcut for `!response.is_success()`. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::empty_400(); /// assert!(response.is_error()); /// ``` #[inline] pub fn is_error(&self) -> bool { !self.is_success() } /// Builds a `Response` that redirects the user to another URL with a 301 status code. This /// semantically means a permanent redirect. /// /// > **Note**: If you're uncertain about which status code to use for a redirection, 303 is /// > the safest choice. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::redirect_301("/foo"); /// ``` #[inline] pub fn redirect_301<S>(target: S) -> Response where S: Into<Cow<'static, str>>, { Response { status_code: 301, headers: vec![("Location".into(), target.into())], data: ResponseBody::empty(), upgrade: None, } } /// Builds a `Response` that redirects the user to another URL with a 302 status code. This /// semantically means a temporary redirect. /// /// > **Note**: If you're uncertain about which status code to use for a redirection, 303 is /// > the safest choice. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::redirect_302("/bar"); /// ``` #[inline] pub fn redirect_302<S>(target: S) -> Response where S: Into<Cow<'static, str>>, { Response { status_code: 302, headers: vec![("Location".into(), target.into())], data: ResponseBody::empty(), upgrade: None, } } /// Builds a `Response` that redirects the user to another URL with a 303 status code. This /// means "See Other" and is usually used to indicate where the response of a query is /// located. /// /// For example when a user sends a POST request to URL `/foo` the server can return a 303 /// response with a target to `/bar`, in which case the browser will automatically change /// the page to `/bar` (with a GET request to `/bar`). /// /// > **Note**: If you're uncertain about which status code to use for a redirection, 303 is /// > the safest choice. /// /// # Example /// /// ``` /// use rouille::Response; /// let user_id = 5; /// let response = Response::redirect_303(format!("/users/{}", user_id)); /// ``` #[inline] pub fn redirect_303<S>(target: S) -> Response where S: Into<Cow<'static, str>>, { Response { status_code: 303, headers: vec![("Location".into(), target.into())], data: ResponseBody::empty(), upgrade: None, } } /// Builds a `Response` that redirects the user to another URL with a 307 status code. This /// semantically means a permanent redirect. /// /// The difference between 307 and 301 is that the client must keep the same method after /// the redirection. For example if the browser sends a POST request to `/foo` and that route /// returns a 307 redirection to `/bar`, then the browser will make a POST request to `/bar`. /// With a 301 redirection it would use a GET request instead. /// /// > **Note**: If you're uncertain about which status code to use for a redirection, 303 is /// > the safest choice. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::redirect_307("/foo"); /// ``` #[inline] pub fn redirect_307<S>(target: S) -> Response where S: Into<Cow<'static, str>>, { Response { status_code: 307, headers: vec![("Location".into(), target.into())], data: ResponseBody::empty(), upgrade: None, } } /// Builds a `Response` that redirects the user to another URL with a 302 status code. This /// semantically means a temporary redirect. /// /// The difference between 308 and 302 is that the client must keep the same method after /// the redirection. For example if the browser sends a POST request to `/foo` and that route /// returns a 308 redirection to `/bar`, then the browser will make a POST request to `/bar`. /// With a 302 redirection it would use a GET request instead. /// /// > **Note**: If you're uncertain about which status code to use for a redirection, 303 is /// > the safest choice. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::redirect_302("/bar"); /// ``` #[inline] pub fn redirect_308<S>(target: S) -> Response where S: Into<Cow<'static, str>>, { Response { status_code: 308, headers: vec![("Location".into(), target.into())], data: ResponseBody::empty(), upgrade: None, } } /// Builds a 200 `Response` with data. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::from_data("application/octet-stream", vec![1, 2, 3, 4]); /// ``` #[inline] pub fn from_data<C, D>(content_type: C, data: D) -> Response where C: Into<Cow<'static, str>>, D: Into<Vec<u8>>, { Response { status_code: 200, headers: vec![("Content-Type".into(), content_type.into())], data: ResponseBody::from_data(data), upgrade: None, } } /// Builds a 200 `Response` with the content of a file. /// /// # Example /// /// ```no_run /// use std::fs::File; /// use rouille::Response; /// /// let file = File::open("image.png").unwrap(); /// let response = Response::from_file("image/png", file); /// ``` #[inline] pub fn from_file<C>(content_type: C, file: File) -> Response where C: Into<Cow<'static, str>>, { Response { status_code: 200, headers: vec![("Content-Type".into(), content_type.into())], data: ResponseBody::from_file(file), upgrade: None, } } /// Builds a `Response` that outputs HTML. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::html("<p>hello <strong>world</strong></p>"); /// ``` #[inline] pub fn html<D>(content: D) -> Response where D: Into<String>, { Response { status_code: 200, headers: vec![("Content-Type".into(), "text/html; charset=utf-8".into())], data: ResponseBody::from_string(content), upgrade: None, } } /// Builds a `Response` that outputs SVG. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::svg("<svg xmlns='http://www.w3.org/2000/svg'/>"); /// ``` #[inline] pub fn svg<D>(content: D) -> Response where D: Into<String>, { Response { status_code: 200, headers: vec![("Content-Type".into(), "image/svg+xml; charset=utf-8".into())], data: ResponseBody::from_string(content), upgrade: None, } } /// Builds a `Response` that outputs plain text. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::text("hello world"); /// ``` #[inline] pub fn text<S>(text: S) -> Response where S: Into<String>, { Response { status_code: 200, headers: vec![("Content-Type".into(), "text/plain; charset=utf-8".into())], data: ResponseBody::from_string(text), upgrade: None, } } /// Builds a `Response` that outputs JSON. /// /// # Example /// /// ``` /// extern crate serde; /// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate rouille; /// use rouille::Response; /// # fn main() { /// /// #[derive(Serialize)] /// struct MyStruct { /// field1: String, /// field2: i32, /// } /// /// let response = Response::json(&MyStruct { field1: "hello".to_owned(), field2: 5 }); /// // The Response will contain something like `{ field1: "hello", field2: 5 }` /// # } /// ``` #[inline] pub fn json<T>(content: &T) -> Response where T: serde::Serialize, { let data = serde_json::to_string(content).unwrap(); Response { status_code: 200, headers: vec![( "Content-Type".into(), "application/json; charset=utf-8".into(), )], data: ResponseBody::from_data(data), upgrade: None, } } /// Builds a `Response` that returns a `401 Not Authorized` status /// and a `WWW-Authenticate` header. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::basic_http_auth_login_required("realm"); /// ``` #[inline] pub fn basic_http_auth_login_required(realm: &str) -> Response { // TODO: escape the realm Response { status_code: 401, headers: vec![( "WWW-Authenticate".into(), format!("Basic realm=\"{}\"", realm).into(), )], data: ResponseBody::empty(), upgrade: None, } } /// Builds an empty `Response` with a 204 status code. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::empty_204(); /// ``` #[inline] pub fn empty_204() -> Response { Response { status_code: 204, headers: vec![], data: ResponseBody::empty(), upgrade: None, } } /// Builds an empty `Response` with a 400 status code. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::empty_400(); /// ``` #[inline] pub fn empty_400() -> Response { Response { status_code: 400, headers: vec![], data: ResponseBody::empty(), upgrade: None, } } /// Builds an empty `Response` with a 404 status code. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::empty_404(); /// ``` #[inline] pub fn empty_404() -> Response { Response { status_code: 404, headers: vec![], data: ResponseBody::empty(), upgrade: None, } } /// Builds an empty `Response` with a 406 status code. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::empty_406(); /// ``` #[inline] pub fn empty_406() -> Response { Response { status_code: 406, headers: vec![], data: ResponseBody::empty(), upgrade: None, } } /// Changes the status code of the response. /// /// # Example /// /// ``` /// use rouille::Response; /// let response = Response::text("hello world").with_status_code(500); /// ``` #[inline] pub fn with_status_code(mut self, code: u16) -> Response { self.status_code = code; self } /// Removes all headers from the response that match `header`. pub fn without_header(mut self, header: &str) -> Response { self.headers .retain(|&(ref h, _)| !h.eq_ignore_ascii_case(header)); self } /// Adds an additional header to the response. #[inline] pub fn with_additional_header<H, V>(mut self, header: H, value: V) -> Response where H: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { self.headers.push((header.into(), value.into())); self } /// Removes all headers from the response whose names are `header`, and replaces them . pub fn with_unique_header<H, V>(mut self, header: H, value: V) -> Response where H: Into<Cow<'static, str>>, V: Into<Cow<'static, str>>, { // If Vec::retain provided a mutable reference this code would be much simpler and would // only need to iterate once. // See https://github.com/rust-lang/rust/issues/25477 // TODO: if the response already has a matching header we shouldn't have to build a Cow // from the header let header = header.into(); let mut found_one = false; self.headers.retain(|&(ref h, _)| { if h.eq_ignore_ascii_case(&header) { if !found_one { found_one = true; true } else { false } } else { true } }); if found_one { for &mut (ref h, ref mut v) in &mut self.headers { if !h.eq_ignore_ascii_case(&header) { continue; } *v = value.into(); break; } self } else { self.with_additional_header(header, value) } } /// Adds or replaces a `ETag` header to the response, and turns the response into an empty 304 /// response if the ETag matches a `If-None-Match` header of the request. /// /// An ETag is a unique representation of the content of a resource. If the content of the /// resource changes, the ETag should change as well. /// The purpose of using ETags is that a client can later ask the server to send the body of /// a response only if it still matches a certain ETag the client has stored in memory. /// /// > **Note**: You should always try to specify an ETag for responses that have a large body. /// /// # Example /// /// ```rust /// use rouille::Request; /// use rouille::Response; /// /// fn handle(request: &Request) -> Response { /// Response::text("hello world").with_etag(request, "my-etag-1234") /// } /// ``` #[inline] pub fn with_etag<E>(self, request: &Request, etag: E) -> Response where E: Into<Cow<'static, str>>, { self.with_etag_keep(etag).simplify_if_etag_match(request) } /// Turns the response into an empty 304 response if the `ETag` that is stored in it matches a /// `If-None-Match` header of the request. pub fn simplify_if_etag_match(mut self, request: &Request) -> Response { if self.status_code < 200 || self.status_code >= 300 { return self; } let mut not_modified = false; for &(ref key, ref etag) in &self.headers { if !key.eq_ignore_ascii_case("ETag") { continue; } not_modified = request .header("If-None-Match") .map(|header| header == etag) .unwrap_or(false); } if not_modified { self.data = ResponseBody::empty(); self.status_code = 304; } self } /// Adds a `ETag` header to the response, or replaces an existing header if there is one. /// /// > **Note**: Contrary to `with_etag`, this function doesn't try to turn the response into /// > a 304 response. If you're unsure of what to do, prefer `with_etag`. #[inline] pub fn with_etag_keep<E>(self, etag: E) -> Response where E: Into<Cow<'static, str>>, { self.with_unique_header("ETag", etag) } /// Adds or replace a `Content-Disposition` header of the response. Tells the browser that the /// body of the request should fire a download popup instead of being shown in the browser. /// /// # Example /// /// ```rust /// use rouille::Request; /// use rouille::Response; /// /// fn handle(request: &Request) -> Response { /// Response::text("hello world").with_content_disposition_attachment("book.txt") /// } /// ``` /// /// When the response is sent back to the browser, it will show a popup asking the user to /// download the file "book.txt" whose content will be "hello world". pub fn with_content_disposition_attachment(mut self, filename: &str) -> Response { // The name must be percent-encoded. let name = percent_encoding::percent_encode(filename.as_bytes(), super::DEFAULT_ENCODE_SET); // If you find a more elegant way to do the thing below, don't hesitate to open a PR // Support for this format varies browser by browser, so this may not be the most // ideal thing. // TODO: it's maybe possible to specify multiple file names let mut header = Some(format!("attachment; filename*=UTF8''{}", name).into()); for &mut (ref key, ref mut val) in &mut self.headers { if key.eq_ignore_ascii_case("Content-Disposition") { *val = header.take().unwrap(); break; } } if let Some(header) = header { self.headers.push(("Content-Disposition".into(), header)); } self } /// Adds or replaces a `Cache-Control` header that specifies that the resource is public and /// can be cached for the given number of seconds. /// /// > **Note**: This function doesn't do any caching itself. It just indicates that clients /// > that receive this response are allowed to cache it. #[inline] pub fn with_public_cache(self, max_age_seconds: u64) -> Response { self.with_unique_header( "Cache-Control", format!("public, max-age={}", max_age_seconds), ) .without_header("Expires") .without_header("Pragma") } /// Adds or replaces a `Cache-Control` header that specifies that the resource is private and /// can be cached for the given number of seconds. /// /// Only the browser or the final client is authorized to cache the resource. Intermediate /// proxies must not cache it. /// /// > **Note**: This function doesn't do any caching itself. It just indicates that clients /// > that receive this response are allowed to cache it. #[inline] pub fn with_private_cache(self, max_age_seconds: u64) -> Response { self.with_unique_header( "Cache-Control", format!("private, max-age={}", max_age_seconds), ) .without_header("Expires") .without_header("Pragma") } /// Adds or replaces a `Cache-Control` header that specifies that the client must not cache /// the resource. #[inline] pub fn with_no_cache(self) -> Response { self.with_unique_header("Cache-Control", "no-cache, no-store, must-revalidate") .with_unique_header("Expires", "0") .with_unique_header("Pragma", "no-cache") } } /// An opaque type that represents the body of a response. /// /// You can't access the inside of this struct, but you can build one by using one of the provided /// constructors. /// /// # Example /// /// ``` /// use rouille::ResponseBody; /// let body = ResponseBody::from_string("hello world"); /// ``` pub struct ResponseBody { data: Box<dyn Read + Send>, data_length: Option<usize>, } impl ResponseBody { /// Builds a `ResponseBody` that doesn't return any data. /// /// # Example /// /// ``` /// use rouille::ResponseBody; /// let body = ResponseBody::empty(); /// ``` #[inline] pub fn empty() -> ResponseBody { ResponseBody { data: Box::new(io::empty()), data_length: Some(0), } } /// Builds a new `ResponseBody` that will read the data from a `Read`. /// /// Note that this is suboptimal compared to other constructors because the length /// isn't known in advance. /// /// # Example /// /// ```no_run /// use std::io; /// use std::io::Read; /// use rouille::ResponseBody; /// /// let body = ResponseBody::from_reader(io::stdin().take(128)); /// ``` #[inline] pub fn from_reader<R>(data: R) -> ResponseBody where R: Read + Send + 'static, { ResponseBody { data: Box::new(data), data_length: None, } } /// Builds a new `ResponseBody` that will read the data from a `Read`. /// /// The caller must provide the content length. It is unspecified /// what will happen if the content length does not match the actual /// length of the data returned from the reader. /// /// # Example /// /// ```no_run /// use std::io; /// use std::io::Read; /// use rouille::ResponseBody; /// /// let body = ResponseBody::from_reader_and_size(io::stdin().take(128), 128); /// ``` #[inline] pub fn from_reader_and_size<R>(data: R, size: usize) -> ResponseBody where R: Read + Send + 'static, { ResponseBody { data: Box::new(data), data_length: Some(size), } } /// Builds a new `ResponseBody` that returns the given data. /// /// # Example /// /// ``` /// use rouille::ResponseBody; /// let body = ResponseBody::from_data(vec![12u8, 97, 34]); /// ``` #[inline] pub fn from_data<D>(data: D) -> ResponseBody where D: Into<Vec<u8>>, { let data = data.into(); let len = data.len(); ResponseBody { data: Box::new(Cursor::new(data)), data_length: Some(len), } } /// Builds a new `ResponseBody` that returns the content of the given file. /// /// # Example /// /// ```no_run /// use std::fs::File; /// use rouille::ResponseBody; /// /// let file = File::open("page.html").unwrap(); /// let body = ResponseBody::from_file(file); /// ``` #[inline] pub fn from_file(file: File) -> ResponseBody { let len = file.metadata().map(|metadata| metadata.len() as usize).ok(); ResponseBody { data: Box::new(file), data_length: len, } } /// Builds a new `ResponseBody` that returns an UTF-8 string. /// /// # Example /// /// ``` /// use rouille::ResponseBody; /// let body = ResponseBody::from_string("hello world"); /// ``` #[inline] pub fn from_string<S>(data: S) -> ResponseBody where S: Into<String>, { ResponseBody::from_data(data.into().into_bytes()) } /// Extracts the content of the response. /// /// Returns the size of the body and the body itself. If the size is `None`, then it is /// unknown. #[inline] pub fn into_reader_and_size(self) -> (Box<dyn Read + Send>, Option<usize>) { (self.data, self.data_length) } } #[cfg(test)] mod tests { use Response; #[test] fn unique_header_adds() { let r = Response { headers: vec![], ..Response::empty_400() }; let r = r.with_unique_header("Foo", "Bar"); assert_eq!(r.headers.len(), 1); assert_eq!(r.headers[0], ("Foo".into(), "Bar".into())); } #[test] fn unique_header_adds_without_touching() { let r = Response { headers: vec![("Bar".into(), "Foo".into())], ..Response::empty_400() }; let r = r.with_unique_header("Foo", "Bar"); assert_eq!(r.headers.len(), 2); assert_eq!(r.headers[0], ("Bar".into(), "Foo".into())); assert_eq!(r.headers[1], ("Foo".into(), "Bar".into())); } #[test] fn unique_header_replaces() { let r = Response { headers: vec![ ("foo".into(), "A".into()), ("fOO".into(), "B".into()), ("Foo".into(), "C".into()), ], ..Response::empty_400() }; let r = r.with_unique_header("Foo", "Bar"); assert_eq!(r.headers.len(), 1); assert_eq!(r.headers[0], ("foo".into(), "Bar".into())); } }
use std::io; pub fn vrsta(stevilo: i32, seznam: &mut [i32]) { let mut x = 1; print!("\ngenerirani poskusi po vrsti: "); for stev in seznam { let num = *stev; if num != 0 { if x>=10 { print!("\n"); x=1; } print!(" {},", num); } else { break; } x+=1; } print!(" {}.\n", stevilo); } pub fn line(spodnja: i32, stevilo: i32, zgornja: i32, seznam: &mut [i32]) { print!("\nprikaz poskusov: {} ", spodnja); if spodnja+zgornja > 100 { print!("{} ---------- {} ---------- {} [crta za prikaz je skrcena]", spodnja, stevilo, zgornja); } else { let mut x = 2; while x < stevilo { if seznam.contains(&x) { print!(" {} ", x); } else { print!("-"); } x+=1; } print!(" {} ", stevilo); x+=1; while x < zgornja { if seznam.contains(&x) { print!(" {} ", x); } else { print!("-"); } x+=1; } print!(" {}\n", zgornja); } } pub fn zgornja(spodnja: i32) -> i32 { let mut newzgornja = vnos(); loop { if newzgornja > spodnja { break; } else { println!("zgornja meja naj je večja od spodnje!"); newzgornja = zgornja(spodnja); } } newzgornja } pub fn vnos() -> i32 { println!("(stevilo naj je pozitivno)"); let mut vn = String::new(); io::stdin() .read_line(&mut vn) .expect("napaka branja!"); let vn = vn.trim().parse::<i32>().expect("napacen vnos!"); if vn < 1 { println!("Napaka! stevilo mora biti pozitivno! "); let vn = vnos(); vn } else { vn } }