text
stringlengths
8
4.13M
use std::error::Error; use std::io; use std::io::Write; use std::fs::File; fn main () { match main_real () { Ok (_) => (), Err (error) => { writeln! ( & mut io::stderr (), "{}", error, ).unwrap_or (()); }, }; } fn main_real ( ) -> Result <(), String> { write_metadata ( ).map_err ( |io_error| format! ( "Error writing metadata: {}", io_error.description ()) ) ?; Ok (()) } fn write_metadata ( ) -> Result <(), io::Error> { let mut file = File::create ( "src/metadata.rs", ) ?; writeln! ( & mut file, "// WARNING: this file is generated by build.rs, changes will be lost.", ) ?; writeln! ( & mut file, "", ) ?; writeln! ( & mut file, "pub const VERSION: & 'static str = \"{}\";", env! ("CARGO_PKG_VERSION"), ) ?; writeln! ( & mut file, "pub const AUTHOR: & 'static str = \"{}\";", "James Pharaoh <james@pharaoh.uk>", ) ?; writeln! ( & mut file, "", ) ?; writeln! ( & mut file, "// ex: noet ts=4 filetype=rust", ) ?; Ok (()) } // ex: noet ts=4 filetype=rust
extern crate ansi_term; extern crate serde_json; use parse_config::Task; use std::fs; use std::process::Command; use std::process::Output; use std::sync::{Arc, Mutex}; use std::thread; use task_output; use task_output::SerializableOutput; use self::ansi_term::ANSIString; use self::ansi_term::Colour::{Black, Green, Red, Yellow}; fn task_success(task: Task, output: Output, json: bool) { if json == false { let stdout = ANSIString::from(String::from_utf8(output.stdout).unwrap()); println!( "{} {}\n{}\n", Black.bold().on(Green).paint(" SUCCESS "), Yellow.paint(format!("{}", task.name)), stdout ); } } fn task_failure(task: Task, output: Output, json: bool) { if json == false { let stderr = ANSIString::from(String::from_utf8(output.stderr).unwrap()); println!( "{} {}\n{}\n", Black.bold().on(Red).paint(" FAIL "), Yellow.paint(format!("{}", task.name)), stderr ); } } fn print_json(outputs: Arc<Mutex<Vec<task_output::TaskOutput>>>, json: bool) { if json == true { let slice = &*outputs.lock().unwrap(); let serializable_output = SerializableOutput { tasks: slice.to_vec(), }; println!("{}", serde_json::to_string(&serializable_output).unwrap()); } } pub fn run(tasks: Vec<Task>, cwd_path: String, json_output: bool) -> bool { let outputs = Arc::new(Mutex::new(task_output::Tasks::with_capacity(tasks.len()))); let mut handles = Vec::with_capacity(tasks.len()); println!("\n"); for task in &tasks { let (data, path) = (task.clone(), cwd_path.clone()); let outputs = Arc::clone(&outputs); let child = thread::spawn(move || { let local_task = data.clone(); let task_data = data.clone(); let mut iter = local_task.command.split_whitespace(); let current_dir = path.clone(); let command_canon_path = format!( "{:?}/{}", fs::canonicalize(path).unwrap(), iter.nth(0).unwrap() ) .replace("\"", ""); let command_output = Command::new(command_canon_path) .args(iter) .current_dir(current_dir) .output() .expect("command failed"); let cloned_output = command_output.clone(); let mut list = outputs.lock().unwrap(); list.push(task_output::build_task_output(cloned_output, task_data)); match command_output.status.code() { Some(0) => task_success(data, command_output, json_output), Some(_) => task_failure(data, command_output, json_output), None => println!("Process terminated by signal"), } }); handles.push(child); } for handle in handles { handle.join().unwrap(); } print_json(outputs, json_output); true }
#[doc = "Register `CFGR2` reader"] pub type R = crate::R<CFGR2_SPEC>; #[doc = "Register `CFGR2` writer"] pub type W = crate::W<CFGR2_SPEC>; #[doc = "Field `RXFILTDIS` reader - BMC decoder Rx pre-filter enable The sampling clock is that of the receiver (that is, after pre-scaler)."] pub type RXFILTDIS_R = crate::BitReader; #[doc = "Field `RXFILTDIS` writer - BMC decoder Rx pre-filter enable The sampling clock is that of the receiver (that is, after pre-scaler)."] pub type RXFILTDIS_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RXFILT2N3` reader - BMC decoder Rx pre-filter sampling method Number of consistent consecutive samples before confirming a new value."] pub type RXFILT2N3_R = crate::BitReader; #[doc = "Field `RXFILT2N3` writer - BMC decoder Rx pre-filter sampling method Number of consistent consecutive samples before confirming a new value."] pub type RXFILT2N3_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `FORCECLK` reader - Force ClkReq clock request"] pub type FORCECLK_R = crate::BitReader; #[doc = "Field `FORCECLK` writer - Force ClkReq clock request"] pub type FORCECLK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WUPEN` reader - Wakeup from Stop mode enable Setting the bit enables the UCPD_ASYNC_INT signal."] pub type WUPEN_R = crate::BitReader; #[doc = "Field `WUPEN` writer - Wakeup from Stop mode enable Setting the bit enables the UCPD_ASYNC_INT signal."] pub type WUPEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RXAFILTEN` reader - Rx analog filter enable Setting the bit enables the Rx analog filter required for optimum Power Delivery reception."] pub type RXAFILTEN_R = crate::BitReader; #[doc = "Field `RXAFILTEN` writer - Rx analog filter enable Setting the bit enables the Rx analog filter required for optimum Power Delivery reception."] pub type RXAFILTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - BMC decoder Rx pre-filter enable The sampling clock is that of the receiver (that is, after pre-scaler)."] #[inline(always)] pub fn rxfiltdis(&self) -> RXFILTDIS_R { RXFILTDIS_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - BMC decoder Rx pre-filter sampling method Number of consistent consecutive samples before confirming a new value."] #[inline(always)] pub fn rxfilt2n3(&self) -> RXFILT2N3_R { RXFILT2N3_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Force ClkReq clock request"] #[inline(always)] pub fn forceclk(&self) -> FORCECLK_R { FORCECLK_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Wakeup from Stop mode enable Setting the bit enables the UCPD_ASYNC_INT signal."] #[inline(always)] pub fn wupen(&self) -> WUPEN_R { WUPEN_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 8 - Rx analog filter enable Setting the bit enables the Rx analog filter required for optimum Power Delivery reception."] #[inline(always)] pub fn rxafilten(&self) -> RXAFILTEN_R { RXAFILTEN_R::new(((self.bits >> 8) & 1) != 0) } } impl W { #[doc = "Bit 0 - BMC decoder Rx pre-filter enable The sampling clock is that of the receiver (that is, after pre-scaler)."] #[inline(always)] #[must_use] pub fn rxfiltdis(&mut self) -> RXFILTDIS_W<CFGR2_SPEC, 0> { RXFILTDIS_W::new(self) } #[doc = "Bit 1 - BMC decoder Rx pre-filter sampling method Number of consistent consecutive samples before confirming a new value."] #[inline(always)] #[must_use] pub fn rxfilt2n3(&mut self) -> RXFILT2N3_W<CFGR2_SPEC, 1> { RXFILT2N3_W::new(self) } #[doc = "Bit 2 - Force ClkReq clock request"] #[inline(always)] #[must_use] pub fn forceclk(&mut self) -> FORCECLK_W<CFGR2_SPEC, 2> { FORCECLK_W::new(self) } #[doc = "Bit 3 - Wakeup from Stop mode enable Setting the bit enables the UCPD_ASYNC_INT signal."] #[inline(always)] #[must_use] pub fn wupen(&mut self) -> WUPEN_W<CFGR2_SPEC, 3> { WUPEN_W::new(self) } #[doc = "Bit 8 - Rx analog filter enable Setting the bit enables the Rx analog filter required for optimum Power Delivery reception."] #[inline(always)] #[must_use] pub fn rxafilten(&mut self) -> RXAFILTEN_W<CFGR2_SPEC, 8> { RXAFILTEN_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "UCPD configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cfgr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cfgr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CFGR2_SPEC; impl crate::RegisterSpec for CFGR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cfgr2::R`](R) reader structure"] impl crate::Readable for CFGR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`cfgr2::W`](W) writer structure"] impl crate::Writable for CFGR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CFGR2 to value 0"] impl crate::Resettable for CFGR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ use reqwest; use crate::apis::ResponseContent; use super::{Error, configuration}; /// struct for typed errors of method `create_slo_correction` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateSloCorrectionError { Status400(crate::models::ApiErrorResponse), Status403(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `delete_slo_correction` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteSloCorrectionError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `get_slo_correction` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetSloCorrectionError { Status400(crate::models::ApiErrorResponse), Status403(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `list_slo_correction` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ListSloCorrectionError { Status403(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `update_slo_correction` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateSloCorrectionError { Status400(crate::models::ApiErrorResponse), Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// Create an SLO Correction pub async fn create_slo_correction(configuration: &configuration::Configuration, body: crate::models::SloCorrectionCreateRequest) -> Result<crate::models::SloCorrectionResponse, Error<CreateSloCorrectionError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/slo/correction", configuration.base_path); let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; local_var_req_builder = local_var_req_builder.json(&body); let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<CreateSloCorrectionError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Permanently delete the specified SLO correction object pub async fn delete_slo_correction(configuration: &configuration::Configuration, slo_correction_id: &str) -> Result<(), Error<DeleteSloCorrectionError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/slo/correction/{slo_correction_id}", configuration.base_path, slo_correction_id=crate::apis::urlencode(slo_correction_id)); let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { Ok(()) } else { let local_var_entity: Option<DeleteSloCorrectionError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Get an SLO correction pub async fn get_slo_correction(configuration: &configuration::Configuration, slo_correction_id: &str) -> Result<crate::models::SloCorrectionResponse, Error<GetSloCorrectionError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/slo/correction/{slo_correction_id}", configuration.base_path, slo_correction_id=crate::apis::urlencode(slo_correction_id)); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<GetSloCorrectionError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Get all Service Level Objective corrections pub async fn list_slo_correction(configuration: &configuration::Configuration, ) -> Result<crate::models::SloCorrectionListResponse, Error<ListSloCorrectionError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/slo/correction", configuration.base_path); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<ListSloCorrectionError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Update the specified SLO correction object object pub async fn update_slo_correction(configuration: &configuration::Configuration, slo_correction_id: &str, body: crate::models::SloCorrectionUpdateRequest) -> Result<crate::models::SloCorrectionResponse, Error<UpdateSloCorrectionError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/slo/correction/{slo_correction_id}", configuration.base_path, slo_correction_id=crate::apis::urlencode(slo_correction_id)); let mut local_var_req_builder = local_var_client.patch(local_var_uri_str.as_str()); if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; local_var_req_builder = local_var_req_builder.json(&body); let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<UpdateSloCorrectionError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } }
#[derive(Debug)] struct Pixel{ r:u8, g:u8, b:u8, } impl IntoIterator for Pixel{ type Item = u8; type IntoIter = PixelIntoIterator; fn into_iter(self) -> Self::IntoIter{ PixelIntoIterator{ pixel:self, index:0, } } } struct PixelIntoIterator{ pixel:Pixel, index:u8, } impl Iterator for PixelIntoIterator{ type Item = u8; fn next(&mut self) -> Option<u8>{ let result = match self.index{ 0 => { self.pixel.r}, 1 => { self.pixel.g}, 2 => { self.pixel.b}, _ => { return None}, }; self.index +=1; Some(result) } } fn main(){ let p = Pixel{ r:45, g:34, b:33 }; let p1 = Pixel{ r:4, g:3, b:39 }; let mut v = vec!(); v.push(p); v.push(p1); //for loop on pixel println!("This is for loop on Pixel struct"); for j in v{ for i in j{ println!("{}",i); } } }
#[doc = "Register `SR` reader"] pub type R = crate::R<SR_SPEC>; #[doc = "Field `CCF` reader - Computation complete flag"] pub type CCF_R = crate::BitReader<CCF_A>; #[doc = "Computation complete flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CCF_A { #[doc = "0: Computation complete"] Complete = 0, #[doc = "1: Computation not complete"] NotComplete = 1, } impl From<CCF_A> for bool { #[inline(always)] fn from(variant: CCF_A) -> Self { variant as u8 != 0 } } impl CCF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CCF_A { match self.bits { false => CCF_A::Complete, true => CCF_A::NotComplete, } } #[doc = "Computation complete"] #[inline(always)] pub fn is_complete(&self) -> bool { *self == CCF_A::Complete } #[doc = "Computation not complete"] #[inline(always)] pub fn is_not_complete(&self) -> bool { *self == CCF_A::NotComplete } } #[doc = "Field `RDERR` reader - Read error flag"] pub type RDERR_R = crate::BitReader<RDERR_A>; #[doc = "Read error flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RDERR_A { #[doc = "0: Read error not detected"] NoError = 0, #[doc = "1: Read error detected"] Error = 1, } impl From<RDERR_A> for bool { #[inline(always)] fn from(variant: RDERR_A) -> Self { variant as u8 != 0 } } impl RDERR_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RDERR_A { match self.bits { false => RDERR_A::NoError, true => RDERR_A::Error, } } #[doc = "Read error not detected"] #[inline(always)] pub fn is_no_error(&self) -> bool { *self == RDERR_A::NoError } #[doc = "Read error detected"] #[inline(always)] pub fn is_error(&self) -> bool { *self == RDERR_A::Error } } #[doc = "Field `WRERR` reader - Write error flag"] pub type WRERR_R = crate::BitReader<WRERR_A>; #[doc = "Write error flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WRERR_A { #[doc = "0: Write error not detected"] NoError = 0, #[doc = "1: Write error detected"] Error = 1, } impl From<WRERR_A> for bool { #[inline(always)] fn from(variant: WRERR_A) -> Self { variant as u8 != 0 } } impl WRERR_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> WRERR_A { match self.bits { false => WRERR_A::NoError, true => WRERR_A::Error, } } #[doc = "Write error not detected"] #[inline(always)] pub fn is_no_error(&self) -> bool { *self == WRERR_A::NoError } #[doc = "Write error detected"] #[inline(always)] pub fn is_error(&self) -> bool { *self == WRERR_A::Error } } #[doc = "Field `BUSY` reader - Busy flag"] pub type BUSY_R = crate::BitReader<BUSY_A>; #[doc = "Busy flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum BUSY_A { #[doc = "0: Idle"] Idle = 0, #[doc = "1: Busy"] Busy = 1, } impl From<BUSY_A> for bool { #[inline(always)] fn from(variant: BUSY_A) -> Self { variant as u8 != 0 } } impl BUSY_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> BUSY_A { match self.bits { false => BUSY_A::Idle, true => BUSY_A::Busy, } } #[doc = "Idle"] #[inline(always)] pub fn is_idle(&self) -> bool { *self == BUSY_A::Idle } #[doc = "Busy"] #[inline(always)] pub fn is_busy(&self) -> bool { *self == BUSY_A::Busy } } impl R { #[doc = "Bit 0 - Computation complete flag"] #[inline(always)] pub fn ccf(&self) -> CCF_R { CCF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Read error flag"] #[inline(always)] pub fn rderr(&self) -> RDERR_R { RDERR_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Write error flag"] #[inline(always)] pub fn wrerr(&self) -> WRERR_R { WRERR_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Busy flag"] #[inline(always)] pub fn busy(&self) -> BUSY_R { BUSY_R::new(((self.bits >> 3) & 1) != 0) } } #[doc = "status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SR_SPEC; impl crate::RegisterSpec for SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`sr::R`](R) reader structure"] impl crate::Readable for SR_SPEC {} #[doc = "`reset()` method sets SR to value 0"] impl crate::Resettable for SR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::hit::HitRecord; use super::hit::Hittable; use crate::math::Ray; use std::sync::Arc; pub struct HittableList<T: Hittable + Send + Sync> { objects: Vec<Arc<T>>, } impl<T: Hittable + Send + Sync> HittableList<T> { pub fn add(&mut self, obj: Arc<T>) { self.objects.push(obj); } pub fn new() -> Self { HittableList { objects: Vec::<Arc<T>>::new(), } } } impl<T: Hittable + Send + Sync> Hittable for HittableList<T> { fn hit(&self, ray: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> { let mut hit = None; let mut closest = t_max; for obj in &self.objects { if let Some(h) = obj.hit(ray, t_min, closest) { closest = h.t; hit = Some(h); } } hit } }
extern crate chan; extern crate handlebars; extern crate hyper; extern crate rustc_serialize; extern crate websocket; extern crate walkdir; use std::collections::BTreeMap; use std::default::Default; use std::fs::File; use std::io::{Write, Read}; use std::sync::{Arc, Mutex}; use std::thread; use self::handlebars::Handlebars; use self::hyper::Server as HttpServer; use self::hyper::server::Handler; use self::hyper::net::Fresh; use self::hyper::server::request::Request; use self::hyper::server::response::Response; use self::rustc_serialize::json::{Json, ToJson}; use self::walkdir::WalkDir; use self::websocket::{Message, Sender}; use watcher; #[derive(Default)] pub struct Server<'a> { http_addr: &'a str, websocket_addr: &'a str, watchpath: String, } impl<'a> Server<'a> { pub fn bind(http_addr: &'a str, websocket_addr: &'a str) -> Server<'a> { Server { http_addr: http_addr, websocket_addr: websocket_addr, ..Default::default() } } pub fn watch(&mut self, path: String) { self.watchpath = path; } pub fn start(&self) { http_server(self.http_addr); websocket_server(self.websocket_addr, self.watchpath.clone()); } } fn websocket_server(addr: &str, watchpath: String) { let websocket_server = websocket::Server::bind(addr).unwrap(); let (sx, rx) = chan::sync(0); let treepath = watchpath.clone(); let rootpath = watchpath.clone(); thread::spawn(move || { watcher::watch(&watchpath[..], sx); }); let wait_group = chan::WaitGroup::new(); let tree = Arc::new(Mutex::new(WalkDir::new(treepath) .into_iter() .filter_map(|e| e.ok()) .map(|e| e.path().display().to_string().replace(&rootpath[..], "")) .collect::<Vec<String>>())); for connection in websocket_server { let tree = tree.clone(); let wait_group = wait_group.clone(); let rx = rx.clone(); wait_group.add(1); thread::spawn(move || { let request = connection.unwrap().read_request().unwrap(); let response = request.accept(); let mut client = response.send().unwrap(); for fop in rx { if let Some(path) = fop.path.to_str() { let mut code = String::new(); let mut file = File::open(path).unwrap(); file.read_to_string(&mut code).unwrap(); let mut data: BTreeMap<String, Json> = BTreeMap::new(); data.insert("code".to_string(), code.to_json()); data.insert("tree".to_string(), tree.lock().unwrap().to_json()); let message = Message::text(data.to_json().to_string()); client.send_message(&message).unwrap(); } } wait_group.done(); }); } wait_group.wait(); } fn render() -> String { let mut handlebars = Handlebars::new(); let mut file = File::open("static/filesync.html").unwrap(); let mut template = String::new(); file.read_to_string(&mut template).unwrap(); handlebars.register_template_string("filesync", template).ok().unwrap(); let mut data: BTreeMap<String, Json> = BTreeMap::new(); data.insert("websocket_addr".to_string(), "127.0.0.1:1234".to_json()); handlebars.render("filesync", &data).ok().unwrap() } fn http_handler(_: Request, response: Response<Fresh>) { let mut response = response.start().unwrap(); response.write_all(render().as_bytes()).unwrap(); response.end().unwrap(); } fn http_server(addr: &str) { let addr: String = String::from(addr); thread::spawn(move || { let http_server = HttpServer::http(&addr[..]).unwrap(); http_server.handle(http_handler).unwrap(); }); }
#![allow(non_snake_case)] #[macro_use] extern crate criterion; use criterion::Criterion; use rand; use rand::Rng; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use bulletproofs::RangeProof; use bulletproofs::{BulletproofGens, PedersenGens}; static AGGREGATION_SIZES: [usize; 6] = [1, 2, 4, 8, 16, 32]; fn create_aggregated_rangeproof_helper(n: usize, c: &mut Criterion) { let label = format!("Aggregated {}-bit rangeproof creation", n); c.bench_function_over_inputs( &label, move |b, &&m| { let pc_gens = PedersenGens::default(); let bp_gens = BulletproofGens::new(n, m); let mut rng = rand::thread_rng(); let (min, max) = (0u64, ((1u128 << n) - 1) as u64); let values: Vec<u64> = (0..m).map(|_| rng.gen_range(min, max)).collect(); let blindings: Vec<Scalar> = (0..m).map(|_| Scalar::random(&mut rng)).collect(); b.iter(|| { // Each proof creation requires a clean transcript. let mut transcript = Transcript::new(b"AggregateRangeProofBenchmark"); RangeProof::prove_multiple( &bp_gens, &pc_gens, &mut transcript, &values, &blindings, n, ) }) }, &AGGREGATION_SIZES, ); } fn create_aggregated_rangeproof_n_8(c: &mut Criterion) { create_aggregated_rangeproof_helper(8, c); } fn create_aggregated_rangeproof_n_16(c: &mut Criterion) { create_aggregated_rangeproof_helper(16, c); } fn create_aggregated_rangeproof_n_32(c: &mut Criterion) { create_aggregated_rangeproof_helper(32, c); } fn create_aggregated_rangeproof_n_64(c: &mut Criterion) { create_aggregated_rangeproof_helper(64, c); } fn verify_aggregated_rangeproof_helper(n: usize, c: &mut Criterion) { let label = format!("Aggregated {}-bit rangeproof verification", n); c.bench_function_over_inputs( &label, move |b, &&m| { let pc_gens = PedersenGens::default(); let bp_gens = BulletproofGens::new(n, m); let mut rng = rand::thread_rng(); let (min, max) = (0u64, ((1u128 << n) - 1) as u64); let values: Vec<u64> = (0..m).map(|_| rng.gen_range(min, max)).collect(); let blindings: Vec<Scalar> = (0..m).map(|_| Scalar::random(&mut rng)).collect(); let mut transcript = Transcript::new(b"AggregateRangeProofBenchmark"); let (proof, value_commitments) = RangeProof::prove_multiple( &bp_gens, &pc_gens, &mut transcript, &values, &blindings, n, ) .unwrap(); b.iter(|| { // Each proof creation requires a clean transcript. let mut transcript = Transcript::new(b"AggregateRangeProofBenchmark"); proof.verify_multiple(&bp_gens, &pc_gens, &mut transcript, &value_commitments, n) }); }, &AGGREGATION_SIZES, ); } fn verify_aggregated_rangeproof_n_8(c: &mut Criterion) { verify_aggregated_rangeproof_helper(8, c); } fn verify_aggregated_rangeproof_n_16(c: &mut Criterion) { verify_aggregated_rangeproof_helper(16, c); } fn verify_aggregated_rangeproof_n_32(c: &mut Criterion) { verify_aggregated_rangeproof_helper(32, c); } fn verify_aggregated_rangeproof_n_64(c: &mut Criterion) { verify_aggregated_rangeproof_helper(64, c); } criterion_group! { name = create_rp; config = Criterion::default().sample_size(10); targets = create_aggregated_rangeproof_n_8, create_aggregated_rangeproof_n_16, create_aggregated_rangeproof_n_32, create_aggregated_rangeproof_n_64, } criterion_group! { name = verify_rp; config = Criterion::default(); targets = verify_aggregated_rangeproof_n_8, verify_aggregated_rangeproof_n_16, verify_aggregated_rangeproof_n_32, verify_aggregated_rangeproof_n_64, } criterion_main!(create_rp, verify_rp);
use std::process::Command; fn main() { Command::new("bash") .args(&["./bin/buildjs.sh"]) .output() .expect("failed to build javascript"); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - control register"] pub cr: CR, #[doc = "0x04 - data input register"] pub din: DIN, #[doc = "0x08 - start register"] pub str: STR, #[doc = "0x0c - HASH aliased digest register 0"] pub hra0: HRA0, #[doc = "0x10 - HASH aliased digest register 1"] pub hra1: HRA1, #[doc = "0x14 - HASH aliased digest register 2"] pub hra2: HRA2, #[doc = "0x18 - HASH aliased digest register 3"] pub hra3: HRA3, #[doc = "0x1c - HASH aliased digest register 4"] pub hra4: HRA4, #[doc = "0x20 - interrupt enable register"] pub imr: IMR, #[doc = "0x24 - status register"] pub sr: SR, _reserved10: [u8; 0xd0], #[doc = "0xf8 - context swap registers"] pub csr0: CSR0, #[doc = "0xfc - context swap registers"] pub csr1: CSR1, #[doc = "0x100 - context swap registers"] pub csr2: CSR2, #[doc = "0x104 - context swap registers"] pub csr3: CSR3, #[doc = "0x108 - context swap registers"] pub csr4: CSR4, #[doc = "0x10c - context swap registers"] pub csr5: CSR5, #[doc = "0x110 - context swap registers"] pub csr6: CSR6, #[doc = "0x114 - context swap registers"] pub csr7: CSR7, #[doc = "0x118 - context swap registers"] pub csr8: CSR8, #[doc = "0x11c - context swap registers"] pub csr9: CSR9, #[doc = "0x120 - context swap registers"] pub csr10: CSR10, #[doc = "0x124 - context swap registers"] pub csr11: CSR11, #[doc = "0x128 - context swap registers"] pub csr12: CSR12, #[doc = "0x12c - context swap registers"] pub csr13: CSR13, #[doc = "0x130 - context swap registers"] pub csr14: CSR14, #[doc = "0x134 - context swap registers"] pub csr15: CSR15, #[doc = "0x138 - context swap registers"] pub csr16: CSR16, #[doc = "0x13c - context swap registers"] pub csr17: CSR17, #[doc = "0x140 - context swap registers"] pub csr18: CSR18, #[doc = "0x144 - context swap registers"] pub csr19: CSR19, #[doc = "0x148 - context swap registers"] pub csr20: CSR20, #[doc = "0x14c - context swap registers"] pub csr21: CSR21, #[doc = "0x150 - context swap registers"] pub csr22: CSR22, #[doc = "0x154 - context swap registers"] pub csr23: CSR23, #[doc = "0x158 - context swap registers"] pub csr24: CSR24, #[doc = "0x15c - context swap registers"] pub csr25: CSR25, #[doc = "0x160 - context swap registers"] pub csr26: CSR26, #[doc = "0x164 - context swap registers"] pub csr27: CSR27, #[doc = "0x168 - context swap registers"] pub csr28: CSR28, #[doc = "0x16c - context swap registers"] pub csr29: CSR29, #[doc = "0x170 - context swap registers"] pub csr30: CSR30, #[doc = "0x174 - context swap registers"] pub csr31: CSR31, #[doc = "0x178 - context swap registers"] pub csr32: CSR32, #[doc = "0x17c - context swap registers"] pub csr33: CSR33, #[doc = "0x180 - context swap registers"] pub csr34: CSR34, #[doc = "0x184 - context swap registers"] pub csr35: CSR35, #[doc = "0x188 - context swap registers"] pub csr36: CSR36, #[doc = "0x18c - context swap registers"] pub csr37: CSR37, #[doc = "0x190 - context swap registers"] pub csr38: CSR38, #[doc = "0x194 - context swap registers"] pub csr39: CSR39, #[doc = "0x198 - context swap registers"] pub csr40: CSR40, #[doc = "0x19c - context swap registers"] pub csr41: CSR41, #[doc = "0x1a0 - context swap registers"] pub csr42: CSR42, #[doc = "0x1a4 - context swap registers"] pub csr43: CSR43, #[doc = "0x1a8 - context swap registers"] pub csr44: CSR44, #[doc = "0x1ac - context swap registers"] pub csr45: CSR45, #[doc = "0x1b0 - context swap registers"] pub csr46: CSR46, #[doc = "0x1b4 - context swap registers"] pub csr47: CSR47, #[doc = "0x1b8 - context swap registers"] pub csr48: CSR48, #[doc = "0x1bc - context swap registers"] pub csr49: CSR49, #[doc = "0x1c0 - context swap registers"] pub csr50: CSR50, #[doc = "0x1c4 - context swap registers"] pub csr51: CSR51, #[doc = "0x1c8 - context swap registers"] pub csr52: CSR52, #[doc = "0x1cc - context swap registers"] pub csr53: CSR53, _reserved64: [u8; 0x0140], #[doc = "0x310 - digest register 0"] pub hr0: HR0, #[doc = "0x314 - digest register 1"] pub hr1: HR1, #[doc = "0x318 - digest register 4"] pub hr2: HR2, #[doc = "0x31c - digest register 3"] pub hr3: HR3, #[doc = "0x320 - digest register 4"] pub hr4: HR4, #[doc = "0x324 - supplementary digest register 5"] pub hr5: HR5, #[doc = "0x328 - supplementary digest register 6"] pub hr6: HR6, #[doc = "0x32c - supplementary digest register 7"] pub hr7: HR7, } #[doc = "CR (rw) register accessor: control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr`] module"] pub type CR = crate::Reg<cr::CR_SPEC>; #[doc = "control register"] pub mod cr; #[doc = "DIN (rw) register accessor: data input register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`din::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`din::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`din`] module"] pub type DIN = crate::Reg<din::DIN_SPEC>; #[doc = "data input register"] pub mod din; #[doc = "STR (rw) register accessor: start register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`str::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`str::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`str`] module"] pub type STR = crate::Reg<str::STR_SPEC>; #[doc = "start register"] pub mod str; #[doc = "HRA0 (r) register accessor: HASH aliased digest register 0\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hra0::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hra0`] module"] pub type HRA0 = crate::Reg<hra0::HRA0_SPEC>; #[doc = "HASH aliased digest register 0"] pub mod hra0; #[doc = "HRA1 (r) register accessor: HASH aliased digest register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hra1::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hra1`] module"] pub type HRA1 = crate::Reg<hra1::HRA1_SPEC>; #[doc = "HASH aliased digest register 1"] pub mod hra1; #[doc = "HRA2 (r) register accessor: HASH aliased digest register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hra2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hra2`] module"] pub type HRA2 = crate::Reg<hra2::HRA2_SPEC>; #[doc = "HASH aliased digest register 2"] pub mod hra2; #[doc = "HRA3 (r) register accessor: HASH aliased digest register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hra3::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hra3`] module"] pub type HRA3 = crate::Reg<hra3::HRA3_SPEC>; #[doc = "HASH aliased digest register 3"] pub mod hra3; #[doc = "HRA4 (r) register accessor: HASH aliased digest register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hra4::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hra4`] module"] pub type HRA4 = crate::Reg<hra4::HRA4_SPEC>; #[doc = "HASH aliased digest register 4"] pub mod hra4; #[doc = "HR0 (r) register accessor: digest register 0\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr0::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr0`] module"] pub type HR0 = crate::Reg<hr0::HR0_SPEC>; #[doc = "digest register 0"] pub mod hr0; #[doc = "HR1 (r) register accessor: digest register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr1::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr1`] module"] pub type HR1 = crate::Reg<hr1::HR1_SPEC>; #[doc = "digest register 1"] pub mod hr1; #[doc = "HR2 (r) register accessor: digest register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr2::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr2`] module"] pub type HR2 = crate::Reg<hr2::HR2_SPEC>; #[doc = "digest register 4"] pub mod hr2; #[doc = "HR3 (r) register accessor: digest register 3\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr3::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr3`] module"] pub type HR3 = crate::Reg<hr3::HR3_SPEC>; #[doc = "digest register 3"] pub mod hr3; #[doc = "HR4 (r) register accessor: digest register 4\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr4::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr4`] module"] pub type HR4 = crate::Reg<hr4::HR4_SPEC>; #[doc = "digest register 4"] pub mod hr4; #[doc = "HR5 (r) register accessor: supplementary digest register 5\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr5::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr5`] module"] pub type HR5 = crate::Reg<hr5::HR5_SPEC>; #[doc = "supplementary digest register 5"] pub mod hr5; #[doc = "HR6 (r) register accessor: supplementary digest register 6\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr6::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr6`] module"] pub type HR6 = crate::Reg<hr6::HR6_SPEC>; #[doc = "supplementary digest register 6"] pub mod hr6; #[doc = "HR7 (r) register accessor: supplementary digest register 7\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hr7::R`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`hr7`] module"] pub type HR7 = crate::Reg<hr7::HR7_SPEC>; #[doc = "supplementary digest register 7"] pub mod hr7; #[doc = "IMR (rw) register accessor: interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`imr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`imr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`imr`] module"] pub type IMR = crate::Reg<imr::IMR_SPEC>; #[doc = "interrupt enable register"] pub mod imr; #[doc = "SR (rw) register accessor: status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr`] module"] pub type SR = crate::Reg<sr::SR_SPEC>; #[doc = "status register"] pub mod sr; #[doc = "CSR0 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr0::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr0::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr0`] module"] pub type CSR0 = crate::Reg<csr0::CSR0_SPEC>; #[doc = "context swap registers"] pub mod csr0; #[doc = "CSR1 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr1`] module"] pub type CSR1 = crate::Reg<csr1::CSR1_SPEC>; #[doc = "context swap registers"] pub mod csr1; #[doc = "CSR2 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr2`] module"] pub type CSR2 = crate::Reg<csr2::CSR2_SPEC>; #[doc = "context swap registers"] pub mod csr2; #[doc = "CSR3 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr3::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr3::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr3`] module"] pub type CSR3 = crate::Reg<csr3::CSR3_SPEC>; #[doc = "context swap registers"] pub mod csr3; #[doc = "CSR4 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr4::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr4::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr4`] module"] pub type CSR4 = crate::Reg<csr4::CSR4_SPEC>; #[doc = "context swap registers"] pub mod csr4; #[doc = "CSR5 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr5::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr5::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr5`] module"] pub type CSR5 = crate::Reg<csr5::CSR5_SPEC>; #[doc = "context swap registers"] pub mod csr5; #[doc = "CSR6 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr6::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr6::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr6`] module"] pub type CSR6 = crate::Reg<csr6::CSR6_SPEC>; #[doc = "context swap registers"] pub mod csr6; #[doc = "CSR7 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr7::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr7::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr7`] module"] pub type CSR7 = crate::Reg<csr7::CSR7_SPEC>; #[doc = "context swap registers"] pub mod csr7; #[doc = "CSR8 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr8::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr8::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr8`] module"] pub type CSR8 = crate::Reg<csr8::CSR8_SPEC>; #[doc = "context swap registers"] pub mod csr8; #[doc = "CSR9 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr9::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr9::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr9`] module"] pub type CSR9 = crate::Reg<csr9::CSR9_SPEC>; #[doc = "context swap registers"] pub mod csr9; #[doc = "CSR10 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr10::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr10::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr10`] module"] pub type CSR10 = crate::Reg<csr10::CSR10_SPEC>; #[doc = "context swap registers"] pub mod csr10; #[doc = "CSR11 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr11::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr11::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr11`] module"] pub type CSR11 = crate::Reg<csr11::CSR11_SPEC>; #[doc = "context swap registers"] pub mod csr11; #[doc = "CSR12 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr12::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr12::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr12`] module"] pub type CSR12 = crate::Reg<csr12::CSR12_SPEC>; #[doc = "context swap registers"] pub mod csr12; #[doc = "CSR13 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr13::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr13::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr13`] module"] pub type CSR13 = crate::Reg<csr13::CSR13_SPEC>; #[doc = "context swap registers"] pub mod csr13; #[doc = "CSR14 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr14::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr14::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr14`] module"] pub type CSR14 = crate::Reg<csr14::CSR14_SPEC>; #[doc = "context swap registers"] pub mod csr14; #[doc = "CSR15 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr15::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr15::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr15`] module"] pub type CSR15 = crate::Reg<csr15::CSR15_SPEC>; #[doc = "context swap registers"] pub mod csr15; #[doc = "CSR16 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr16::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr16::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr16`] module"] pub type CSR16 = crate::Reg<csr16::CSR16_SPEC>; #[doc = "context swap registers"] pub mod csr16; #[doc = "CSR17 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr17::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr17::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr17`] module"] pub type CSR17 = crate::Reg<csr17::CSR17_SPEC>; #[doc = "context swap registers"] pub mod csr17; #[doc = "CSR18 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr18::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr18::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr18`] module"] pub type CSR18 = crate::Reg<csr18::CSR18_SPEC>; #[doc = "context swap registers"] pub mod csr18; #[doc = "CSR19 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr19::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr19::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr19`] module"] pub type CSR19 = crate::Reg<csr19::CSR19_SPEC>; #[doc = "context swap registers"] pub mod csr19; #[doc = "CSR20 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr20::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr20::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr20`] module"] pub type CSR20 = crate::Reg<csr20::CSR20_SPEC>; #[doc = "context swap registers"] pub mod csr20; #[doc = "CSR21 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr21::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr21::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr21`] module"] pub type CSR21 = crate::Reg<csr21::CSR21_SPEC>; #[doc = "context swap registers"] pub mod csr21; #[doc = "CSR22 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr22::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr22::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr22`] module"] pub type CSR22 = crate::Reg<csr22::CSR22_SPEC>; #[doc = "context swap registers"] pub mod csr22; #[doc = "CSR23 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr23::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr23::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr23`] module"] pub type CSR23 = crate::Reg<csr23::CSR23_SPEC>; #[doc = "context swap registers"] pub mod csr23; #[doc = "CSR24 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr24::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr24::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr24`] module"] pub type CSR24 = crate::Reg<csr24::CSR24_SPEC>; #[doc = "context swap registers"] pub mod csr24; #[doc = "CSR25 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr25::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr25::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr25`] module"] pub type CSR25 = crate::Reg<csr25::CSR25_SPEC>; #[doc = "context swap registers"] pub mod csr25; #[doc = "CSR26 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr26::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr26::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr26`] module"] pub type CSR26 = crate::Reg<csr26::CSR26_SPEC>; #[doc = "context swap registers"] pub mod csr26; #[doc = "CSR27 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr27::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr27::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr27`] module"] pub type CSR27 = crate::Reg<csr27::CSR27_SPEC>; #[doc = "context swap registers"] pub mod csr27; #[doc = "CSR28 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr28::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr28::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr28`] module"] pub type CSR28 = crate::Reg<csr28::CSR28_SPEC>; #[doc = "context swap registers"] pub mod csr28; #[doc = "CSR29 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr29::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr29::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr29`] module"] pub type CSR29 = crate::Reg<csr29::CSR29_SPEC>; #[doc = "context swap registers"] pub mod csr29; #[doc = "CSR30 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr30::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr30::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr30`] module"] pub type CSR30 = crate::Reg<csr30::CSR30_SPEC>; #[doc = "context swap registers"] pub mod csr30; #[doc = "CSR31 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr31::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr31::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr31`] module"] pub type CSR31 = crate::Reg<csr31::CSR31_SPEC>; #[doc = "context swap registers"] pub mod csr31; #[doc = "CSR32 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr32::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr32::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr32`] module"] pub type CSR32 = crate::Reg<csr32::CSR32_SPEC>; #[doc = "context swap registers"] pub mod csr32; #[doc = "CSR33 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr33::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr33::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr33`] module"] pub type CSR33 = crate::Reg<csr33::CSR33_SPEC>; #[doc = "context swap registers"] pub mod csr33; #[doc = "CSR34 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr34::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr34::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr34`] module"] pub type CSR34 = crate::Reg<csr34::CSR34_SPEC>; #[doc = "context swap registers"] pub mod csr34; #[doc = "CSR35 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr35::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr35::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr35`] module"] pub type CSR35 = crate::Reg<csr35::CSR35_SPEC>; #[doc = "context swap registers"] pub mod csr35; #[doc = "CSR36 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr36::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr36::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr36`] module"] pub type CSR36 = crate::Reg<csr36::CSR36_SPEC>; #[doc = "context swap registers"] pub mod csr36; #[doc = "CSR37 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr37::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr37::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr37`] module"] pub type CSR37 = crate::Reg<csr37::CSR37_SPEC>; #[doc = "context swap registers"] pub mod csr37; #[doc = "CSR38 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr38::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr38::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr38`] module"] pub type CSR38 = crate::Reg<csr38::CSR38_SPEC>; #[doc = "context swap registers"] pub mod csr38; #[doc = "CSR39 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr39::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr39::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr39`] module"] pub type CSR39 = crate::Reg<csr39::CSR39_SPEC>; #[doc = "context swap registers"] pub mod csr39; #[doc = "CSR40 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr40::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr40::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr40`] module"] pub type CSR40 = crate::Reg<csr40::CSR40_SPEC>; #[doc = "context swap registers"] pub mod csr40; #[doc = "CSR41 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr41::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr41::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr41`] module"] pub type CSR41 = crate::Reg<csr41::CSR41_SPEC>; #[doc = "context swap registers"] pub mod csr41; #[doc = "CSR42 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr42::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr42::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr42`] module"] pub type CSR42 = crate::Reg<csr42::CSR42_SPEC>; #[doc = "context swap registers"] pub mod csr42; #[doc = "CSR43 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr43::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr43::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr43`] module"] pub type CSR43 = crate::Reg<csr43::CSR43_SPEC>; #[doc = "context swap registers"] pub mod csr43; #[doc = "CSR44 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr44::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr44::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr44`] module"] pub type CSR44 = crate::Reg<csr44::CSR44_SPEC>; #[doc = "context swap registers"] pub mod csr44; #[doc = "CSR45 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr45::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr45::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr45`] module"] pub type CSR45 = crate::Reg<csr45::CSR45_SPEC>; #[doc = "context swap registers"] pub mod csr45; #[doc = "CSR46 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr46::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr46::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr46`] module"] pub type CSR46 = crate::Reg<csr46::CSR46_SPEC>; #[doc = "context swap registers"] pub mod csr46; #[doc = "CSR47 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr47::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr47::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr47`] module"] pub type CSR47 = crate::Reg<csr47::CSR47_SPEC>; #[doc = "context swap registers"] pub mod csr47; #[doc = "CSR48 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr48::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr48::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr48`] module"] pub type CSR48 = crate::Reg<csr48::CSR48_SPEC>; #[doc = "context swap registers"] pub mod csr48; #[doc = "CSR49 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr49::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr49::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr49`] module"] pub type CSR49 = crate::Reg<csr49::CSR49_SPEC>; #[doc = "context swap registers"] pub mod csr49; #[doc = "CSR50 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr50::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr50::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr50`] module"] pub type CSR50 = crate::Reg<csr50::CSR50_SPEC>; #[doc = "context swap registers"] pub mod csr50; #[doc = "CSR51 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr51::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr51::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr51`] module"] pub type CSR51 = crate::Reg<csr51::CSR51_SPEC>; #[doc = "context swap registers"] pub mod csr51; #[doc = "CSR52 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr52::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr52::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr52`] module"] pub type CSR52 = crate::Reg<csr52::CSR52_SPEC>; #[doc = "context swap registers"] pub mod csr52; #[doc = "CSR53 (rw) register accessor: context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`csr53::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`csr53::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`csr53`] module"] pub type CSR53 = crate::Reg<csr53::CSR53_SPEC>; #[doc = "context swap registers"] pub mod csr53;
use reqwest::{Client, Response}; pub use reqwest::{Method, RequestBuilder}; use result::{BestbuyError, BestbuyResult}; use serde::Deserialize; use serde_json; pub struct BestbuyClient { http: Client, token: String, } impl BestbuyClient { pub fn new(token: &str) -> Self { Self::with_http_client(token, Client::new()) } pub fn with_http_client(token: &str, http: Client) -> Self { Self { token: token.to_owned(), http, } } pub fn request(&self, method: Method, path: &str) -> RequestBuilder { use reqwest::{ header::{qitem, Accept, Authorization, CacheControl, CacheDirective}, mime, }; let mut b = self .http .request(method, &format!("https://marketplace.bestbuy.ca{}", path)); b.header(Authorization(self.token.clone())) .header(CacheControl(vec![CacheDirective::NoCache])) .header(Accept(vec![qitem(mime::APPLICATION_JSON)])); b } } pub trait BestbuyResponse { fn get_response<T: for<'de> Deserialize<'de>>(&mut self) -> BestbuyResult<T>; fn no_content(&mut self) -> BestbuyResult<()>; } impl BestbuyResponse for Response { fn get_response<T: for<'de> Deserialize<'de>>(&mut self) -> BestbuyResult<T> { let body = self.text()?; if !self.status().is_success() { return Err(BestbuyError::Request { path: self.url().to_string(), status: self.status(), body, }); } match serde_json::from_str(&body) { Ok(v) => Ok(v), Err(err) => { return Err(BestbuyError::Deserialize { msg: err.to_string(), body, }) } } } fn no_content(&mut self) -> BestbuyResult<()> { let body = self.text()?; if !self.status().is_success() { return Err(BestbuyError::Request { path: self.url().to_string(), status: self.status(), body, }); } Ok(()) } }
pub mod signature; pub mod curie_to_iri; pub mod iri_2_curie; pub mod structural_identity; pub mod parser;
use std::fmt; use strum_macros::{EnumIter, EnumString}; #[derive(Debug, PartialEq, EnumString, EnumIter)] pub enum ContinentCode { None, // ENUM START AF, AS, EU, NA, OC, SA, // ENUM END } impl ContinentCode { pub fn is_none(&self) -> bool { match *self { ContinentCode::None => true, _ => false, } } } impl fmt::Display for ContinentCode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self) } }
use crate::Uncertain; use num_traits::{identities, Float}; use rand_pcg::Pcg32; use std::error::Error; use std::fmt; const STEP: usize = 10; const MAXS: usize = 1000; /// Information about a failed call to [`expect`](Uncertain::expect). /// /// This struct allows introspection of a failed attempt to calculate /// the expected value of an [`Uncertain`](Uncertain). #[derive(Debug, Clone)] pub struct ConvergenceError<F> where F: Float, { sample_mean: F, diff_sum: F, steps: F, precision: F, } impl<F: Float> ConvergenceError<F> { /// The expected value estimate obtained. /// /// This value is less precise than desired /// and should be used with caution. pub fn non_converged_value(&self) -> F { self.sample_mean } /// The two sigma confidence interval around the /// computed value. /// /// # Details /// /// Mathematically, this is an estimate for the /// standard deviation of the expected value, i.e. /// `2 * sqrt(var(E(x)))`. /// /// This value is calculated under the assumption /// that samples from the original [`Uncertain`](Uncertain) /// are [identically and independently distributed][iid]. /// /// [iid]: https://en.wikipedia.org/wiki/Independent_and_identically_distributed_random_variables pub fn two_sigma_error(&self) -> F { let std = mean_standard_deviation(self.diff_sum, self.steps); std + std } /// The precision which was originally mandated by the /// call to [`Uncertain::expect`](Uncertain::expect). pub fn desired_precision(&self) -> F { self.precision } } impl<F: Float + fmt::Display> fmt::Display for ConvergenceError<F> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "Expected value {} +/- {} did not converge to desired precision {}", self.non_converged_value(), self.two_sigma_error(), self.desired_precision() ) } } impl<F: Float + fmt::Debug + fmt::Display> Error for ConvergenceError<F> {} fn mean_standard_deviation<F: Float>(diff_sum: F, steps: F) -> F { diff_sum.sqrt() / steps // = sqrt( sigma^2 / n ) i.e. sqrt(var(E(x))) } /// Compute the sample expectation. pub fn compute<U>(src: &U, precision: U::Value) -> Result<U::Value, ConvergenceError<U::Value>> where U: Uncertain + ?Sized, U::Value: Float, { let mut rng = Pcg32::new(0xcafef00dd15ea5e5, 0xa02bdbf7bb3c0a7); let mut sample_mean = identities::zero(); let mut diff_sum = identities::zero(); let mut steps = identities::zero(); for batch in 0..MAXS { for batch_step in 0..STEP { let epoch = STEP * batch + batch_step; let sample = src.sample(&mut rng, epoch); let prev_sample_mean = sample_mean; // Using Welford's online algorithm: // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance steps = steps + identities::one(); sample_mean = prev_sample_mean + (sample - prev_sample_mean) / steps; diff_sum = diff_sum + (sample - prev_sample_mean) * (sample - sample_mean); } let std = mean_standard_deviation(diff_sum, steps); if std + std <= precision { return Ok(sample_mean); } } Err(ConvergenceError { sample_mean, diff_sum, steps, precision, }) } #[cfg(test)] mod tests { use super::*; use crate::Distribution; use rand_distr::Normal; #[test] fn simple_expectation() { let values = vec![0.0, 1.0, 5.0, 17.0, 23525.108213]; for val in values { let x = Distribution::from(Normal::new(val, 1.0).unwrap()); let mu = compute(&x, 0.1); assert!(mu.is_ok()); assert!((mu.unwrap() - val).abs() < 0.1); } } #[test] fn failed_expectation() { let x = Distribution::from(Normal::new(0.0, 1000.0).unwrap()); let mu = compute(&x, 0.1); assert!(mu.is_err()); assert!(mu.err().unwrap().two_sigma_error() > 0.1); let mu = compute(&x, 100.0); assert!(mu.is_ok()); assert!(mu.unwrap().abs() < 100.0); } #[test] fn errors_are_correct() { let cases: Vec<f64> = vec![1000.0, 5000.0, 10_000.0, 23452345.0, 23245.0]; for var in cases { let x = Distribution::from(Normal::new(0.0, var).unwrap()); let err = x.expect(0.1); assert!(err.is_err()); let err = err.err().unwrap(); // one sigma should be var(x) / sqrt(N), N = STEP * MAXS // we do two sigma, so divide by two let have_err = err.two_sigma_error() / 2.0; let want_err = var / ((STEP * MAXS) as f64).sqrt(); let tolerance = 0.01; // plus minus 1% assert!( (have_err - want_err).abs() / want_err.abs() < tolerance, "{} is not approximately {}", have_err, want_err ); // the value reported by the error should still be good to // within the reported two sigma interval let val = err.non_converged_value(); assert!( val.abs() < err.two_sigma_error(), "{} is not close enough to 0", val ); // but the desired precision should not have been reached assert!(err.two_sigma_error() > err.desired_precision()); } } }
extern crate azul; use std::time::Duration; use azul::{ prelude::*, widgets::{button::Button, svg::*}, }; const SVG: &str = include_str!("../../img/tiger.svg"); #[derive(Debug)] struct MyAppData { cache: SvgCache, layers: Vec<(SvgLayerId, SvgStyle)>, frame_count: u64, } type CbInfo<'a, 'b> = CallbackInfo<'a, 'b, MyAppData>; impl Layout for MyAppData { fn layout(&self, _info: LayoutInfo<Self>) -> Dom<MyAppData> { let ptr = StackCheckedPointer::new(self, self).unwrap(); Dom::div().with_child( Dom::gl_texture(draw_svg, ptr).with_id("svg-container"), ) } } fn timer_callback(state: TimerCallbackInfo<MyAppData>) -> (UpdateScreen, TerminateTimer) { eprintln!("cb {}", state.state.frame_count); (Redraw, if state.state.frame_count >= 256 { TerminateTimer::Terminate }else { TerminateTimer::Continue }) } fn draw_svg(info: GlCallbackInfoUnchecked<MyAppData>) -> GlCallbackReturn { let cb = |info: GlCallbackInfo<MyAppData, MyAppData>| { use azul::widgets::svg::SvgLayerResource::*; info.state.frame_count += 1; let map = info.state; let logical_size = info.bounds.get_logical_size(); Some(Svg::with_layers(map.layers.iter().map(|e| Reference(*e)).collect()) .render_svg(&map.cache, &info.layout_info.window, logical_size)) }; unsafe { info.invoke_callback(cb) } } fn main() { let mut svg_cache = SvgCache::empty(); let mut svg_layers = svg_cache.add_svg(&SVG).unwrap(); let app_data = MyAppData { cache: svg_cache, layers: svg_layers, frame_count: 0, }; let mut app = App::new(app_data, AppConfig::default()).unwrap(); let window = app.create_window(WindowCreateOptions::default(), css::native()).unwrap(); let timer = Timer::new(timer_callback).with_interval(Duration::from_millis(5)); app.app_state.add_timer(TimerId::new(), timer); app.run(window).unwrap(); }
use diesel::prelude::*; use super::db_connection::*; use crate::db::models::UserEntity; use crate::db::models::User; use crate::schema::users::dsl::*; pub fn fetch_user_by_email(database_url: &String, input_email: &String) -> Option<UserEntity> { let connection = db_connection(&database_url); let mut users_by_id: Vec<UserEntity> = users .filter(email.eq(input_email)) .load::<UserEntity>(&connection) .expect("ErrorLoadingUser"); if users_by_id.len() == 0 { None } else { Some(users_by_id.remove(0)) } } pub fn fetch_user_by_id(database_url: &String, uid: i32) -> Option<UserEntity> { let connection = db_connection(&database_url); let mut users_by_id: Vec<UserEntity> = users .filter(id.eq(uid)) .load::<UserEntity>(&connection) .expect("ErrorLoadingUser"); if users_by_id.len() == 0 { None } else { Some(users_by_id.remove(0)) } } pub fn insert_user(database_url: &String, user: User) -> UserEntity { let connection = db_connection(&database_url); use crate::schema::users::dsl::*; diesel::insert_into(users) .values(user) .get_result(&connection) .expect("ErrorSavingUser") }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crypto::Hasher; use utils::{ collections::Vec, ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable, SliceReader, }; // COMMITMENTS // ================================================================================================ /// Commitments made by the prover during commit phase of the protocol. /// /// These commitments include: /// * Commitment to the extended execution trace. /// * Commitment to the evaluations of constraint composition polynomial over LDE domain. /// * Commitments to the evaluations of polynomials at all FRI layers. /// /// Internally, the commitments are stored as a sequence of bytes. Thus, to retrieve the /// commitments, [parse()](Commitments::parse) function should be used. #[derive(Debug, Clone, Eq, PartialEq)] pub struct Commitments(Vec<u8>); impl Commitments { // CONSTRUCTOR // -------------------------------------------------------------------------------------------- /// Returns a new Commitments struct initialized with the provided commitments. pub fn new<H: Hasher>( trace_root: H::Digest, constraint_root: H::Digest, fri_roots: Vec<H::Digest>, ) -> Self { let mut bytes = Vec::new(); bytes.extend_from_slice(trace_root.as_ref()); bytes.extend_from_slice(constraint_root.as_ref()); for fri_root in fri_roots.iter() { bytes.extend_from_slice(fri_root.as_ref()); } Commitments(bytes) } // PUBLIC METHODS // -------------------------------------------------------------------------------------------- /// Adds the specified commitment to the list of commitments. pub fn add<H: Hasher>(&mut self, commitment: &H::Digest) { self.0.extend_from_slice(commitment.as_ref()) } // PARSING // -------------------------------------------------------------------------------------------- /// Parses the serialized commitments into distinct parts. /// /// The parts are (in the order in which they appear in the tuple): /// 1. Extended execution trace commitment. /// 2. Constraint composition polynomial evaluation commitment. /// 3. FRI layer commitments. /// /// # Errors /// Returns an error if the bytes stored in self could not be parsed into the requested number /// of commitments, or if there are any unconsumed bytes remaining after the parsing completes. #[allow(clippy::type_complexity)] pub fn parse<H: Hasher>( self, num_fri_layers: usize, ) -> Result<(H::Digest, H::Digest, Vec<H::Digest>), DeserializationError> { // +1 for trace_root, +1 for constraint root, +1 for FRI remainder commitment let num_commitments = num_fri_layers + 3; let mut reader = SliceReader::new(&self.0); let commitments = H::Digest::read_batch_from(&mut reader, num_commitments)?; // make sure we consumed all available commitment bytes if reader.has_more_bytes() { return Err(DeserializationError::UnconsumedBytes); } Ok((commitments[0], commitments[1], commitments[2..].to_vec())) } } impl Default for Commitments { fn default() -> Self { Commitments(Vec::new()) } } impl Serializable for Commitments { /// Serializes `self` and writes the resulting bytes into the `target`. fn write_into<W: ByteWriter>(&self, target: &mut W) { assert!(self.0.len() < u16::MAX as usize); target.write_u16(self.0.len() as u16); target.write_u8_slice(&self.0); } } impl Deserializable for Commitments { /// Reads commitments from the specified `source` and returns the result. /// /// # Errors /// Returns an error of a valid Commitments struct could not be read from the specified /// `source`. fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> { let num_bytes = source.read_u16()? as usize; let result = source.read_u8_vec(num_bytes)?; Ok(Commitments(result)) } }
// use na::{Vector3}; use na::{Point3}; use macroquad::prelude::*; // mod thing_lines; use crate::thing::Thing; // use std::convert::TryInto; pub fn draw_thing(th: &Thing) { for line in &th.lines { let (i0, i1) = line; let ui0 = *i0 as usize; let ui1 = *i1 as usize; // let pt0: Point3<f32> = th.points[i0.try_into().unwrap()]; // let pt1: Point3<f32> = th.points[i1.try_into().unwrap()]; let pt0: Point3<f32> = th.points[ui0]; let pt1: Point3<f32> = th.points[ui1]; let vec0 = vec3(pt0.x, pt0.y, pt0.z); let vec1 = vec3(pt1.x, pt1.y, pt1.z); // println!("line {} {} {} {}", i0, i1, pt0, pt1); draw_line_3d(vec0, vec1, DARKGREEN); } }
// Copyright 2019 Fullstop000 <fullstop1005@gmail.com>. // // 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, // See the License for the specific language governing permissions and // limitations under the License. // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. use crate::cache::Cache; use crate::util::collection::HashMap; use std::hash::{Hash, Hasher}; use std::mem; use std::mem::MaybeUninit; use std::ptr; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; use std::sync::Mutex; #[derive(Copy, Clone)] struct Key<K> { k: *const K, } impl<K: Hash> Hash for Key<K> { fn hash<H: Hasher>(&self, state: &mut H) { unsafe { (*self.k).hash(state) } } } impl<K: PartialEq> PartialEq for Key<K> { fn eq(&self, other: &Key<K>) -> bool { unsafe { (*self.k).eq(&*other.k) } } } impl<K: Eq> Eq for Key<K> {} impl<K> Default for Key<K> { fn default() -> Self { Key { k: ptr::null() } } } /// Exact node in the `LRUCache` pub struct LRUHandle<K, V> { key: MaybeUninit<K>, value: MaybeUninit<V>, prev: *mut LRUHandle<K, V>, next: *mut LRUHandle<K, V>, charge: usize, } impl<K, V> LRUHandle<K, V> { /// Create new LRUHandle pub fn new(key: K, value: V, charge: usize) -> LRUHandle<K, V> { LRUHandle { key: MaybeUninit::new(key), value: MaybeUninit::new(value), charge, next: ptr::null_mut(), prev: ptr::null_mut(), } } } // TODO: remove mutex /// LRU cache implementation pub struct LRUCache<K, V> { // The capacity of LRU capacity: usize, mutex: Mutex<MutexFields<K, V>>, // The size of space which have been allocated usage: AtomicUsize, cache_id: AtomicU64, callback: Option<Box<dyn Fn(&K, &V)>>, } struct MutexFields<K, V> { // Dummy head of LRU list. // lru.prev is newest entry, lru.next is oldest entry. lru: *mut LRUHandle<K, V>, table: HashMap<Key<K>, Box<LRUHandle<K, V>>>, } impl<K: Hash + Eq, V> LRUCache<K, V> { pub fn new(cap: usize, callback: Option<Box<dyn Fn(&K, &V)>>) -> Self { let mutex = unsafe { MutexFields { lru: Self::create_dummy_node(), table: HashMap::default(), } }; LRUCache { usage: AtomicUsize::new(0), capacity: cap, mutex: Mutex::new(mutex), cache_id: AtomicU64::new(0), callback, } } // Unlink the node `n` fn lru_remove(n: *mut LRUHandle<K, V>) { unsafe { (*(*n).next).prev = (*n).prev; (*(*n).prev).next = (*n).next; } } // Append the `new_node` to the head of given list `n` fn lru_append(n: *mut LRUHandle<K, V>, new_node: *mut LRUHandle<K, V>) { unsafe { (*new_node).next = n; (*new_node).prev = (*n).prev; (*(*n).prev).next = new_node; (*n).prev = new_node; } } // Create a dummy node whose 'next' and 'prev' are both itself unsafe fn create_dummy_node() -> *mut LRUHandle<K, V> { let n: *mut LRUHandle<K, V> = Box::into_raw(Box::new(mem::MaybeUninit::uninit().assume_init())); (*n).next = n; (*n).prev = n; n } } impl<K: Hash + Eq, V> Cache<K, V> for LRUCache<K, V> { fn insert(&self, key: K, mut value: V, charge: usize) -> Option<V> { let mut mutex_data = self.mutex.lock().unwrap(); if self.capacity > 0 { match mutex_data.table.get_mut(&Key { k: &key as *const K, }) { Some(h) => { let old_p = h as *mut Box<LRUHandle<K, V>>; // swap the value and move handle to the head unsafe { mem::swap(&mut value, &mut (*(*old_p).value.as_mut_ptr())) }; let p: *mut LRUHandle<K, V> = h.as_mut(); Self::lru_remove(p); Self::lru_append(mutex_data.lru, p); if let Some(cb) = &self.callback { cb(&key, &value); } Some(value) } None => { let handle = LRUHandle::new(key, value, charge); let mut v = Box::new(handle); let k: *const K = v.as_ref().key.as_ptr(); let value_ptr: *mut LRUHandle<K, V> = v.as_mut(); mutex_data.table.insert(Key { k }, v); Self::lru_append(mutex_data.lru, value_ptr); self.usage.fetch_add(charge, Ordering::Release); // evict last lru entries unsafe { while self.usage.load(Ordering::Acquire) > self.capacity && (*(*mutex_data).lru).next != mutex_data.lru // not the dummy head { let k = (*(*mutex_data.lru).next).key.as_ptr(); let key = Key { k }; if let Some(mut n) = mutex_data.table.remove(&key) { self.usage.fetch_sub(n.charge, Ordering::SeqCst); Self::lru_remove(n.as_mut()); if let Some(cb) = &self.callback { cb(&(*n.key.as_ptr()), &(*n.value.as_ptr())); } ptr::drop_in_place(n.key.as_mut_ptr()); ptr::drop_in_place(n.value.as_mut_ptr()); } } } None } } } else { None } } fn look_up<'a>(&'a self, key: &K) -> Option<&'a V> { let k = Key { k: key as *const K }; let l = self.mutex.lock().unwrap(); l.table.get(&k).map(|h| { let p = h.as_ref() as *const LRUHandle<K, V> as *mut LRUHandle<K, V>; Self::lru_remove(p); Self::lru_append(l.lru, p); unsafe { &(*(*p).value.as_ptr()) as &V } }) } fn erase(&self, key: &K) { let k = Key { k: key as *const K }; let mut mutex_data = self.mutex.lock().unwrap(); // remove the key in hashtable if let Some(mut n) = mutex_data.table.remove(&k) { self.usage.fetch_sub(n.charge, Ordering::SeqCst); Self::lru_remove(n.as_mut() as *mut LRUHandle<K, V>); unsafe { if let Some(cb) = &self.callback { cb(key, &(*n.value.as_ptr())); } } } } #[inline] fn new_id(&self) -> u64 { self.cache_id.fetch_add(1, Ordering::SeqCst) } #[inline] fn total_charge(&self) -> usize { self.usage.load(Ordering::Acquire) } } impl<K, V> Drop for LRUCache<K, V> { fn drop(&mut self) { let mut m = self.mutex.lock().unwrap(); (*m).table.values_mut().for_each(|e| unsafe { ptr::drop_in_place(e.key.as_mut_ptr()); ptr::drop_in_place(e.value.as_mut_ptr()); }); unsafe { let _head = *Box::from_raw(m.lru); } } } unsafe impl<K: Send, V: Send> Send for LRUCache<K, V> {} unsafe impl<K: Sync, V: Sync> Sync for LRUCache<K, V> {} #[cfg(test)] mod tests { use super::*; use crate::util::coding::{decode_fixed_32, put_fixed_32}; use std::cell::RefCell; use std::rc::Rc; const CACHE_SIZE: usize = 100; struct CacheTest { cache: LRUCache<Vec<u8>, u32>, deleted_kv: Rc<RefCell<Vec<(u32, u32)>>>, } impl CacheTest { fn new(cap: usize) -> Self { let deleted_kv = Rc::new(RefCell::new(vec![])); let cloned = deleted_kv.clone(); let callback: Box<dyn Fn(&Vec<u8>, &u32)> = Box::new(move |k, v| { let key = decode_fixed_32(k); cloned.borrow_mut().push((key, *v)); }); Self { cache: LRUCache::<Vec<u8>, u32>::new(cap, Some(callback)), deleted_kv, } } fn look_up(&self, key: u32) -> Option<u32> { let mut k = vec![]; put_fixed_32(&mut k, key); self.cache.look_up(&k).and_then(|v| Some(*v)) } fn insert(&self, key: u32, value: u32) { self.cache.insert(encoded_u32(key), value, 1); } fn insert_with_charge(&self, key: u32, value: u32, charge: usize) { self.cache.insert(encoded_u32(key), value, charge); } fn erase(&self, key: u32) { let mut k = vec![]; put_fixed_32(&mut k, key); self.cache.erase(&k); } fn assert_deleted_kv(&self, index: usize, (key, val): (u32, u32)) { assert_eq!((key, val), self.deleted_kv.borrow()[index]); } fn assert_get(&self, key: u32, want: u32) -> &u32 { let encoded = encoded_u32(key); let h = self.cache.look_up(&encoded).unwrap(); assert_eq!(want, *h); h } } fn encoded_u32(i: u32) -> Vec<u8> { let mut v = vec![]; put_fixed_32(&mut v, i); v } #[test] fn test_hit_and_miss() { let cache = CacheTest::new(CACHE_SIZE); assert_eq!(None, cache.look_up(100)); cache.insert(100, 101); assert_eq!(Some(101), cache.look_up(100)); assert_eq!(None, cache.look_up(200)); assert_eq!(None, cache.look_up(300)); cache.insert(200, 201); assert_eq!(Some(101), cache.look_up(100)); assert_eq!(Some(201), cache.look_up(200)); assert_eq!(None, cache.look_up(300)); cache.insert(100, 102); assert_eq!(Some(102), cache.look_up(100)); assert_eq!(Some(201), cache.look_up(200)); assert_eq!(None, cache.look_up(300)); assert_eq!(1, cache.deleted_kv.borrow().len()); cache.assert_deleted_kv(0, (100, 101)); } #[test] fn test_erase() { let cache = CacheTest::new(CACHE_SIZE); cache.erase(200); assert_eq!(0, cache.deleted_kv.borrow().len()); cache.insert(100, 101); cache.insert(200, 201); cache.erase(100); assert_eq!(None, cache.look_up(100)); assert_eq!(Some(201), cache.look_up(200)); assert_eq!(1, cache.deleted_kv.borrow().len()); cache.assert_deleted_kv(0, (100, 101)); cache.erase(100); assert_eq!(None, cache.look_up(100)); assert_eq!(Some(201), cache.look_up(200)); assert_eq!(1, cache.deleted_kv.borrow().len()); } #[test] fn test_entries_are_pinned() { let cache = CacheTest::new(CACHE_SIZE); cache.insert(100, 101); let v1 = cache.assert_get(100, 101); assert_eq!(*v1, 101); cache.insert(100, 102); let v2 = cache.assert_get(100, 102); assert_eq!(1, cache.deleted_kv.borrow().len()); cache.assert_deleted_kv(0, (100, 101)); assert_eq!(*v1, 102); assert_eq!(*v2, 102); cache.erase(100); assert_eq!(*v1, 102); assert_eq!(*v2, 102); assert_eq!(None, cache.look_up(100)); assert_eq!(2, cache.deleted_kv.borrow().len()); cache.assert_deleted_kv(1, (100, 102)); } #[test] fn test_eviction_policy() { let cache = CacheTest::new(CACHE_SIZE); cache.insert(100, 101); cache.insert(200, 201); cache.insert(300, 301); // frequently used entry must be kept around for i in 0..(CACHE_SIZE + 100) as u32 { cache.insert(1000 + i, 2000 + i); assert_eq!(Some(2000 + i), cache.look_up(1000 + i)); assert_eq!(Some(101), cache.look_up(100)); } assert_eq!(cache.cache.mutex.lock().unwrap().table.len(), CACHE_SIZE); assert_eq!(Some(101), cache.look_up(100)); assert_eq!(None, cache.look_up(200)); assert_eq!(None, cache.look_up(300)); } #[test] fn test_use_exceeds_cache_size() { let cache = CacheTest::new(CACHE_SIZE); let extra = 100; let total = CACHE_SIZE + extra; // overfill the cache, keeping handles on all inserted entries for i in 0..total as u32 { cache.insert(1000 + i, 2000 + i) } // check that all the entries can be found in the cache for i in 0..total as u32 { if i < extra as u32 { assert_eq!(None, cache.look_up(1000 + i)) } else { assert_eq!(Some(2000 + i), cache.look_up(1000 + i)) } } } #[test] fn test_heavy_entries() { let cache = CacheTest::new(CACHE_SIZE); let light = 1; let heavy = 10; let mut added = 0; let mut index = 0; while added < 2 * CACHE_SIZE { let weight = if index & 1 == 0 { light } else { heavy }; cache.insert_with_charge(index, 1000 + index, weight); added += weight; index += 1; } let mut cache_weight = 0; for i in 0..index { let weight = if index & 1 == 0 { light } else { heavy }; if let Some(val) = cache.look_up(i) { cache_weight += weight; assert_eq!(1000 + i, val); } } assert!(cache_weight < CACHE_SIZE); } #[test] fn test_zero_size_cache() { let cache = CacheTest::new(0); cache.insert(100, 101); assert_eq!(None, cache.look_up(100)); } }
#[derive(Debug, Clone)] pub struct Board { pieces: u32, grid: [char; 42] } impl Board { pub fn drop_piece(&mut self, colour:char, position:i32) -> bool { let mut i=position+35; loop { if i<0 { break; } if self.grid[i as usize]=='0' { self.grid[i as usize]=colour; return true; } i-=7; } return false; } pub fn check_winner(&self) -> Option<char> { let lines: [[i32;7]; 25] = [ //Horizontals [0,1,2,3,4,5,6], [7,8,9,10,11,12,13], [14,15,16,17,18,19,20], [21,22,23,24,25,26,27], [28,29,30,31,32,33,34], [35,36,37,38,39,40,41], //Verticals [0,7,14,21,28,35,-1], [1,8,15,22,29,36,-1], [2,9,16,23,30,37,-1], [3,10,17,24,31,38,-1], [4,11,18,25,32,39,-1], [5,12,19,26,33,40,-1], [6,13,20,27,34,41,-1], //Diagonals left to right [3,11,19,27,-1,-1,-1], [2,10,18,26,34,-1,-1], [1,9,17,25,33,41,-1], [0,8,16,24,32,40,-1], [7,15,23,31,39,-1,-1], [14,22,30,38,-1,-1,-1], //Diagonals right to left [3,9,15,21,-1,-1,-1], [4,10,16,22,28,-1,-1], [5,11,17,23,29,35,-1], [6,12,18,24,30,36,-1], [13,19,25,31,37,-1,-1], [20,26,32,36,-1,-1,-1], ]; for i in 0..lines.len() { let mut c=1; let mut p='0'; for j in 0..lines[i].len() { let index=lines[i][j]; if index>=0 { let v=self.grid[index as usize]; if p==v { c+=1; } else { c=1; p=v; } if c==4 && p!='0' { return Some(p); } } } } return None; } pub fn is_full(&self) -> bool { self.pieces==6*7 } pub fn is_col_full(&self, col: usize) -> bool { self.grid[col]!='0' } pub fn get_grid(&self) -> &[char;6*7] { &self.grid } pub fn new() -> Self { Board { pieces: 0, grid: ['0';6*7] } } }
use hyper::{header, Body, Method, Request, Response}; use super::routes; use super::util; /// This is our service handler. It receives a Request, routes on its /// path, and returns a Future of a Response. pub async fn service_handler(req: Request<Body>) -> Result<Response<Body>, hyper::Error> { let path_frags = req .uri() .path() .split('/') .filter(|x| !x.is_empty()) .collect::<Vec<&str>>(); println!( "responding to: {} ({:?}) ({})", req.uri().path(), path_frags, req.method() ); match (req.method(), path_frags.as_slice()) { // Serve hard-coded images (&Method::GET, ["images", name]) => routes::image_serve::handle_get(name), (method, frags) => handle_pages(method, frags), } } fn handle_pages(method: &Method, frags: &[&str]) -> Result<Response<Body>, hyper::Error> { match (method, frags) { // Serve some instructions at / (&Method::GET, []) => routes::index::handle_get(), (&Method::GET, ["maps"]) => routes::map_list::handle_get(), (&Method::GET, ["maps", map_id]) => routes::map_single::handle_get(map_id), (&Method::GET, ["games"]) => routes::game_list::handle_get(), (&Method::POST, ["games"]) => routes::game_list::handle_post(), (&Method::GET, ["games", game_id]) => routes::game_single::handle_get(game_id), (&Method::GET, ["games", game_id, "edit"]) => routes::game_edit::handle_get(game_id), (&Method::POST, ["games", game_id, "edit", "character", character_str]) => { routes::game_edit::handle_post_set_value( game_id, util::TerrainOrCharacter::Character, character_str, ) } (&Method::POST, ["games", game_id, "edit", "terrain", terrain_str]) => { routes::game_edit::handle_post_set_value( game_id, util::TerrainOrCharacter::Terrain, terrain_str, ) } (&Method::POST, ["games", game_id, "edit", "unset", "character"]) => { routes::game_edit::handle_post_unset_value(game_id, util::TerrainOrCharacter::Character) } (&Method::POST, ["games", game_id, "edit", "unset", "terrain"]) => { routes::game_edit::handle_post_unset_value(game_id, util::TerrainOrCharacter::Terrain) } (&Method::POST, ["games", game_id, "edit", "cursor", direction]) => { routes::cursor_move::handle_post(game_id, direction, true) } (&Method::POST, ["games", game_id, "cursor", direction]) => { routes::cursor_move::handle_post(game_id, direction, false) } // Return the 404 Not Found for other routes. _ => util::not_found_response(frags), } .map(|mut resp| { resp.headers_mut().insert( header::CONTENT_TYPE, header::HeaderValue::from_static("text/html"), ); resp }) }
extern crate elevator; extern crate floating_duration; use elevator::buildings::{Building, Building1, Building2, Building3}; use elevator::trip_planning::{FloorRequests, RequestQueue}; use elevator::physics::{ElevatorState, simulate_elevator}; use elevator::motion_controllers::{SmoothMotionController, MotionController}; use elevator::data_recorders::{newSimpleDataRecorder, DataRecorder}; use std::collections::VecDeque; use std::time::Instant; use std::env; use std::fs::File; use std::io::{self, Read, Write}; use std::io::prelude::*; use std::cmp; pub fn run_simulation() { //1. Store location, velocity, and acceleration state //2. Store motor input target force let mut est = ElevatorState { timestamp: 0.0, location: 0.0, velocity: 0.0, acceleration: 0.0, motor_input: 0.0 }; //3. Store input building description and floor requests let mut esp: Box<Building> = Box::new(Building1); let mut floor_requests: Box<RequestQueue> = Box::new(FloorRequests { requests: VecDeque::new() }); //4. Parse input and store as building description and floor requests match env::args().nth(1) { Some(ref fp) if *fp == "-".to_string() => { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer) .expect("read_to_string failed"); for (li,l) in buffer.lines().enumerate() { if li==0 { let building = l.parse::<u64>().unwrap(); if building==0 { esp = Box::new(Building1); } else if building==1 { esp = Box::new(Building2); } else if building==2 { esp = Box::new(Building3); } else { panic!("unknown building code: {}", building); } } else { floor_requests.add_request(l.parse::<u64>().unwrap()); } } }, None => { let fp = "test1.txt"; let mut buffer = String::new(); File::open(fp) .expect("File::open failed") .read_to_string(&mut buffer) .expect("read_to_string failed"); for (li,l) in buffer.lines().enumerate() { if li==0 { let building = l.parse::<u64>().unwrap(); if building==0 { esp = Box::new(Building1); } else if building==1 { esp = Box::new(Building2); } else if building==2 { esp = Box::new(Building3); } else { panic!("unknown building code: {}", building); } } else { floor_requests.add_request(l.parse::<u64>().unwrap()); } } }, Some(fp) => { let mut buffer = String::new(); File::open(fp) .expect("File::open failed") .read_to_string(&mut buffer) .expect("read_to_string failed"); for (li,l) in buffer.lines().enumerate() { if li==0 { let building = l.parse::<u64>().unwrap(); if building==0 { esp = Box::new(Building1); } else if building==1 { esp = Box::new(Building2); } else if building==2 { esp = Box::new(Building3); } else { panic!("unknown building code: {}", building); } } else { floor_requests.add_request(l.parse::<u64>().unwrap()); } } } } let mut dr: Box<DataRecorder> = newSimpleDataRecorder(esp.clone()); let mut mc: Box<MotionController> = Box::new(SmoothMotionController { timestamp: 0.0, esp: esp.clone() }); simulate_elevator(esp, est, &mut floor_requests, &mut mc, &mut dr); dr.summary(); } fn main() { run_simulation() }
//! The plic module contains the platform-level interrupt controller (PLIC). //! The plic connects all external interrupts in the system to all hart //! contexts in the system, via the external interrupt source in each hart. //! It's the global interrupt controller in a RISC-V system. use crate::bus::*; use crate::trap::*; /// The address of interrupt pending bits. pub const PLIC_PENDING: u64 = PLIC_BASE + 0x1000; /// The address of the regsiters to enable interrupts for S-mode. pub const PLIC_SENABLE: u64 = PLIC_BASE + 0x2080; /// The address of the registers to set a priority for S-mode. pub const PLIC_SPRIORITY: u64 = PLIC_BASE + 0x201000; /// The address of the claim/complete registers for S-mode. pub const PLIC_SCLAIM: u64 = PLIC_BASE + 0x201004; /// The platform-level-interrupt controller (PLIC). pub struct Plic { pending: u64, senable: u64, spriority: u64, sclaim: u64, } impl Device for Plic { fn load(&mut self, addr: u64, size: u64) -> Result<u64, Exception> { match size { 32 => Ok(self.load32(addr)), _ => Err(Exception::LoadAccessFault), } } fn store(&mut self, addr: u64, size: u64, value: u64) -> Result<(), Exception> { match size { 32 => Ok(self.store32(addr, value)), _ => Err(Exception::StoreAMOAccessFault), } } } impl Plic { /// Create a new `Plic` object. pub fn new() -> Self { Self { pending: 0, senable: 0, spriority: 0, sclaim: 0, } } fn load32(&self, addr: u64) -> u64 { match addr { PLIC_PENDING => self.pending, PLIC_SENABLE => self.senable, PLIC_SPRIORITY => self.spriority, PLIC_SCLAIM => self.sclaim, _ => 0, } } fn store32(&mut self, addr: u64, value: u64) { match addr { PLIC_PENDING => self.pending = value, PLIC_SENABLE => self.senable = value, PLIC_SPRIORITY => self.spriority = value, PLIC_SCLAIM => self.sclaim = value, _ => {} } } }
//! Tests auto-converted from "sass-spec/spec/libsass-todo-issues/issue_1801" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-todo-issues/issue_1801/simple-import-loop.hrx" // Ignoring "simple_import_loop", error tests are not supported yet.
use futures::channel::mpsc; use futures::StreamExt; use log::*; use sphinx::SphinxPacket; use std::net::SocketAddr; use std::time::Duration; use tokio::runtime::Handle; use tokio::task::JoinHandle; pub(crate) struct MixMessage(SocketAddr, SphinxPacket); pub(crate) type MixMessageSender = mpsc::UnboundedSender<MixMessage>; pub(crate) type MixMessageReceiver = mpsc::UnboundedReceiver<MixMessage>; impl MixMessage { pub(crate) fn new(address: SocketAddr, packet: SphinxPacket) -> Self { MixMessage(address, packet) } } pub(crate) struct MixTrafficController { tcp_client: multi_tcp_client::Client, mix_rx: MixMessageReceiver, } impl MixTrafficController { pub(crate) fn new( initial_reconnection_backoff: Duration, maximum_reconnection_backoff: Duration, mix_rx: MixMessageReceiver, ) -> Self { let tcp_client_config = multi_tcp_client::Config::new( initial_reconnection_backoff, maximum_reconnection_backoff, ); MixTrafficController { tcp_client: multi_tcp_client::Client::new(tcp_client_config), mix_rx, } } async fn on_message(&mut self, mix_message: MixMessage) { debug!("Got a mix_message for {:?}", mix_message.0); self.tcp_client // TODO: possibly we might want to get an actual result here at some point .send(mix_message.0, mix_message.1.to_bytes(), false) .await .unwrap(); // if we're not waiting for response, we MUST get an Ok } pub(crate) async fn run(&mut self) { while let Some(mix_message) = self.mix_rx.next().await { self.on_message(mix_message).await; } } pub(crate) fn start(mut self, handle: &Handle) -> JoinHandle<()> { handle.spawn(async move { self.run().await; }) } }
use serde_json::{Value, Map}; pub fn translate_annotations(m : &Map<String, Value>) -> Vec<Value> { let mut annotations = Vec::new(); for (k, v) in m { let property = Value::String(String::from(k)); match v { //traverse list of objects Value::Array(array) => { for object in array { let value = encode_value(&object); //TODO: //(horned OWL currently doesn't support recrusive annotations) //1. check whether object has an annotation //2. translate annotation recursively //3. insert annotation at the second index let annotation_operator = Value::String(String::from("Annotation")); let annotation = vec![annotation_operator, property.clone(), value]; annotations.push(Value::Array(annotation)); } } _ => panic!("Not an array"), }; } annotations } pub fn encode_value(object : &Value) -> Value { let value = object["object"].clone(); let datatype = object["datatype"].clone(); let datatype = datatype.as_str().unwrap(); let value_str = value.as_str().unwrap(); let value_res = if datatype.eq("_IRI") { format!("{}", value_str) } else if datatype.eq("_plain") { format!("\"{}\"", value_str) } else if datatype[..1].eq("@") { format!("\"{}{}\"", value_str, datatype) } else { format!("\"{}^^{}\"", value_str, datatype) }; Value::String(value_res) } pub fn translate_annotation(m : &Map<String, Value>) -> Value { let operator = Value::String(String::from("Annotation")); let mut annotation = vec![operator]; for (k, v) in m { let property = Value::String(String::from(k)); annotation.push(property); match v { //traverse list of objects Value::Array(array) => { for object in array { let value = encode_value(&object); //TODO: //(horned OWL currently doesn't support recrusive annotations) //1. check whether object has an annotation //2. translate annotation recursively //3. insert annotation at the second index annotation.push(value); } } _ => panic!("Not an array"), }; } Value::Array(annotation) } pub fn translate(annotation : &Value) -> Vec<Value> { match annotation { Value::Object(x) => translate_annotations(&x), Value::Null => Vec::new(), _ => panic!("Not a valid annotation map"), } }
use actix::prelude::{Message, Recipient}; use drogue_cloud_integration_common::stream::EventStream; use drogue_cloud_service_common::error::ServiceError; use uuid::Uuid; // Service sends the kafka events in this message to WSHandler #[derive(Message)] #[rtype(result = "()")] pub struct WsEvent(pub String); // WsHandler sends this to service to subscribe to the stream #[derive(Message)] #[rtype(result = "()")] pub struct Subscribe { pub addr: Recipient<WsEvent>, pub err_addr: Recipient<StreamError>, pub application: String, pub consumer_group: Option<String>, pub id: Uuid, } // WsHandler sends this to the service to disconnect from the stream #[derive(Message)] #[rtype(result = "()")] pub struct Disconnect { pub id: Uuid, } // Service sends this to itself to run the stream #[derive(Message)] #[rtype(result = "()")] pub struct RunStream<'s> { pub sub: Subscribe, pub stream: EventStream<'s>, } // Service sends this to WSHandler if an error happens while subscribing or running the stream #[derive(Message)] #[rtype(result = "()")] pub struct StreamError { pub error: ServiceError, pub id: Uuid, }
//! Rasterizer use crate::POLY_SUBPIXEL_SHIFT; use crate::POLY_SUBPIXEL_SCALE; //use crate::POLY_SUBPIXEL_MASK; use crate::clip::Clip; use crate::scan::ScanlineU8; use crate::cell::RasterizerCell; use crate::paths::PathCommand; use crate::paths::Vertex; //use crate::Rasterize; use crate::VertexSource; use std::cmp::min; use std::cmp::max; struct RasConvInt { } impl RasConvInt { pub fn upscale(v: f64) -> i64 { (v * POLY_SUBPIXEL_SCALE as f64).round() as i64 } //pub fn downscale(v: i64) -> i64 { // v //} } /// Winding / Filling Rule /// /// See (Non-Zero Filling Rule)[https://en.wikipedia.org/wiki/Nonzero-rule] and /// (Even-Odd Filling)[https://en.wikipedia.org/wiki/Even%E2%80%93odd_rule] #[derive(Debug,PartialEq,Copy,Clone)] pub enum FillingRule { NonZero, EvenOdd, } impl Default for FillingRule { fn default() -> FillingRule { FillingRule::NonZero } } /// Path Status #[derive(Debug,PartialEq,Copy,Clone)] pub enum PathStatus { Initial, Closed, MoveTo, LineTo } impl Default for PathStatus { fn default() -> PathStatus { PathStatus::Initial } } /// Rasterizer Anti-Alias using Scanline #[derive(Debug)] pub struct RasterizerScanline { /// Clipping Region pub(crate) clipper: Clip, /// Collection of Rasterizing Cells outline: RasterizerCell, /// Status of Path pub(crate) status: PathStatus, /// Current x position pub(crate) x0: i64, /// Current y position pub(crate) y0: i64, /// Current y row being worked on, for output scan_y: i64, /// Filling Rule for Polygons filling_rule: FillingRule, /// Gamma Corection Values gamma: Vec<u64>, } impl RasterizerScanline { /// Reset Rasterizer /// /// Reset the RasterizerCell and set PathStatus to Initial pub fn reset(&mut self) { self.outline.reset(); self.status = PathStatus::Initial; } /// Add a Path /// /// Walks the path from the VertexSource and rasterizes it pub fn add_path<VS: VertexSource>(&mut self, path: &VS) { //path.rewind(); if ! self.outline.sorted_y.is_empty() { self.reset(); } for seg in path.xconvert() { match seg.cmd { PathCommand::LineTo => self.line_to(seg.x, seg.y), PathCommand::MoveTo => self.move_to(seg.x, seg.y), PathCommand::Close => self.close_polygon(), PathCommand::Stop => unimplemented!("stop encountered"), } } } /// Rewind the Scanline /// /// Close active polygon, sort the Rasterizer Cells, set the /// scan_y value to the minimum y value and return if any cells /// are present pub(crate) fn rewind_scanlines(&mut self) -> bool { self.close_polygon(); self.outline.sort_cells(); if self.outline.total_cells() == 0 { false } else { self.scan_y = self.outline.min_y; true } } /// Sweep the Scanline /// /// For individual y rows adding any to the input Scanline /// /// Returns true if data exists in the input Scanline pub(crate) fn sweep_scanline(&mut self, sl: &mut ScanlineU8) -> bool { loop { if self.scan_y < 0 { self.scan_y += 1; continue; } if self.scan_y > self.outline.max_y { return false; } sl.reset_spans(); let mut num_cells = self.outline.scanline_num_cells( self.scan_y ); let cells = self.outline.scanline_cells( self.scan_y ); let mut cover = 0; let mut iter = cells.iter(); if let Some(mut cur_cell) = iter.next() { while num_cells > 0 { let mut x = cur_cell.x; let mut area = cur_cell.area; cover += cur_cell.cover; num_cells -= 1; //accumulate all cells with the same X while num_cells > 0 { cur_cell = iter.next().unwrap(); if cur_cell.x != x { break; } area += cur_cell.area; cover += cur_cell.cover; num_cells -= 1; } if area != 0 { let alpha = self.calculate_alpha((cover << (POLY_SUBPIXEL_SHIFT + 1)) - area); if alpha > 0 { sl.add_cell(x, alpha); } x += 1; } if num_cells > 0 && cur_cell.x > x { let alpha = self.calculate_alpha(cover << (POLY_SUBPIXEL_SHIFT + 1)); if alpha > 0 { sl.add_span(x, cur_cell.x - x, alpha); } } } } if sl.num_spans() != 0 { break; } self.scan_y += 1; } sl.finalize(self.scan_y); self.scan_y += 1; true } /// Return minimum x value from the RasterizerCell pub fn min_x(&self) -> i64 { self.outline.min_x } /// Return maximum x value from the RasterizerCell pub fn max_x(&self) -> i64 { self.outline.max_x } /// Create a new RasterizerScanline pub fn new() -> Self { Self { clipper: Clip::new(), status: PathStatus::Initial, outline: RasterizerCell::new(), x0: 0, y0: 0, scan_y: 0, filling_rule: FillingRule::NonZero, gamma: (0..256).collect(), } } /// Set the gamma function /// /// Values are set as: ///```ignore /// gamma = gfunc( v / mask ) * mask ///``` /// where v = 0 to 255 pub fn gamma<F>(&mut self, gfunc: F) where F: Fn(f64) -> f64 { let aa_shift = 8; let aa_scale = 1 << aa_shift; let aa_mask = f64::from(aa_scale - 1); self.gamma = (0..256) .map(|i| gfunc(f64::from(i) / aa_mask )) .map(|v| (v * aa_mask).round() as u64) .collect(); } /// Create a new RasterizerScanline with a gamma function /// /// See gamma() function for description /// pub fn new_with_gamma<F>(gfunc: F) -> Self where F: Fn(f64) -> f64 { let mut new = Self::new(); new.gamma( gfunc ); new } /// Set Clip Box pub fn clip_box(&mut self, x1: f64, y1: f64, x2: f64, y2: f64) { self.clipper.clip_box(RasConvInt::upscale(x1), RasConvInt::upscale(y1), RasConvInt::upscale(x2), RasConvInt::upscale(y2)); } /// Move to point (x,y) /// /// Sets point as the initial point pub fn move_to(&mut self, x: f64, y: f64) { self.x0 = RasConvInt::upscale( x ); self.y0 = RasConvInt::upscale( y ); self.clipper.move_to(self.x0,self.y0); self.status = PathStatus::MoveTo; } /// Draw line from previous point to point (x,y) pub fn line_to(&mut self, x: f64, y: f64) { let x = RasConvInt::upscale( x ); let y = RasConvInt::upscale( y ); self.clipper.line_to(&mut self.outline, x,y); self.status = PathStatus::LineTo; } /// Close the current polygon /// /// Draw a line from current point to initial "move to" point pub fn close_polygon(&mut self) { if self.status == PathStatus::LineTo { self.clipper.line_to(&mut self.outline, self.x0, self.y0); self.status = PathStatus::Closed; } } /// Calculate alpha term based on area /// /// fn calculate_alpha(&self, area: i64) -> u64 { let aa_shift = 8; let aa_scale = 1 << aa_shift; let aa_scale2 = aa_scale * 2; let aa_mask = aa_scale - 1; let aa_mask2 = aa_scale2 - 1; let mut cover = area >> (POLY_SUBPIXEL_SHIFT*2 + 1 - aa_shift); cover = cover.abs(); if self.filling_rule == FillingRule::EvenOdd { cover *= aa_mask2; if cover > aa_scale { cover = aa_scale2 - cover; } } cover = max(0, min(cover, aa_mask)); self.gamma[cover as usize] } } pub(crate) fn len_i64(a: &Vertex<i64>, b: &Vertex<i64>) -> i64 { len_i64_xy(a.x, a.y, b.x, b.y) } pub(crate) fn len_i64_xy(x1: i64, y1: i64, x2: i64, y2: i64) -> i64 { let dx = x1 as f64 - x2 as f64; let dy = y1 as f64 - y2 as f64; (dx*dx + dy*dy).sqrt().round() as i64 } // #[derive(Debug,PartialEq,Copy,Clone)] // pub enum LineJoin { // Round, // None, // Miter, // MiterAccurate, // }
#[doc = "Register `C2EMR2` reader"] pub type R = crate::R<C2EMR2_SPEC>; #[doc = "Register `C2EMR2` writer"] pub type W = crate::W<C2EMR2_SPEC>; #[doc = "Field `EM40` reader - Wakeup with event generation Mask on Event input"] pub type EM40_R = crate::BitReader<EM40_A>; #[doc = "Wakeup with event generation Mask on Event input\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum EM40_A { #[doc = "0: Interrupt request line is masked"] Masked = 0, #[doc = "1: Interrupt request line is unmasked"] Unmasked = 1, } impl From<EM40_A> for bool { #[inline(always)] fn from(variant: EM40_A) -> Self { variant as u8 != 0 } } impl EM40_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> EM40_A { match self.bits { false => EM40_A::Masked, true => EM40_A::Unmasked, } } #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn is_masked(&self) -> bool { *self == EM40_A::Masked } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn is_unmasked(&self) -> bool { *self == EM40_A::Unmasked } } #[doc = "Field `EM40` writer - Wakeup with event generation Mask on Event input"] pub type EM40_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, EM40_A>; impl<'a, REG, const O: u8> EM40_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Interrupt request line is masked"] #[inline(always)] pub fn masked(self) -> &'a mut crate::W<REG> { self.variant(EM40_A::Masked) } #[doc = "Interrupt request line is unmasked"] #[inline(always)] pub fn unmasked(self) -> &'a mut crate::W<REG> { self.variant(EM40_A::Unmasked) } } #[doc = "Field `EM41` reader - Wakeup with event generation Mask on Event input"] pub use EM40_R as EM41_R; #[doc = "Field `EM41` writer - Wakeup with event generation Mask on Event input"] pub use EM40_W as EM41_W; impl R { #[doc = "Bit 8 - Wakeup with event generation Mask on Event input"] #[inline(always)] pub fn em40(&self) -> EM40_R { EM40_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Wakeup with event generation Mask on Event input"] #[inline(always)] pub fn em41(&self) -> EM41_R { EM41_R::new(((self.bits >> 9) & 1) != 0) } } impl W { #[doc = "Bit 8 - Wakeup with event generation Mask on Event input"] #[inline(always)] #[must_use] pub fn em40(&mut self) -> EM40_W<C2EMR2_SPEC, 8> { EM40_W::new(self) } #[doc = "Bit 9 - Wakeup with event generation Mask on Event input"] #[inline(always)] #[must_use] pub fn em41(&mut self) -> EM41_W<C2EMR2_SPEC, 9> { EM41_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "wakeup with event mask register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c2emr2::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`c2emr2::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C2EMR2_SPEC; impl crate::RegisterSpec for C2EMR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c2emr2::R`](R) reader structure"] impl crate::Readable for C2EMR2_SPEC {} #[doc = "`write(|w| ..)` method takes [`c2emr2::W`](W) writer structure"] impl crate::Writable for C2EMR2_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets C2EMR2 to value 0"] impl crate::Resettable for C2EMR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
// Copyright (C) 2020 Sebastian Dröge <sebastian@centricular.com> // // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! RTSP header definitions. //! //! See [RFC 7826 section 18](https://tools.ietf.org/html/rfc7826#section-18) for the standardized //! headers and their semantics. mod types; pub use types::*; mod constants; pub use constants::*; mod parser_helpers; pub mod accept; pub mod accept_ranges; pub mod allow; pub mod content_length; pub mod content_type; pub mod cseq; pub mod features; pub mod media_properties; pub mod media_range; pub mod notify_reason; pub mod pipelined_requests; pub mod public; pub mod range; pub mod require; pub mod rtp_info; pub mod scale; pub mod seek_style; pub mod session; pub mod speed; pub mod supported; pub mod transport; pub mod unsupported; pub use accept::{Accept, MediaType, MediaTypeRange}; pub use accept_ranges::{AcceptRanges, RangeUnit}; pub use allow::Allow; pub use content_length::ContentLength; pub use content_type::ContentType; pub use cseq::CSeq; pub use media_properties::{MediaProperties, MediaProperty}; pub use media_range::MediaRange; pub use notify_reason::NotifyReason; pub use pipelined_requests::PipelinedRequests; pub use public::Public; pub use range::{NptRange, NptTime, Range, SmpteRange, SmpteTime, SmpteType, UtcRange, UtcTime}; pub use require::Require; pub use rtp_info::RtpInfos; pub use scale::Scale; pub use seek_style::SeekStyle; pub use session::Session; pub use speed::Speed; pub use supported::Supported; pub use transport::{ OtherTransport, RtpLowerTransport, RtpProfile, RtpTransport, RtpTransportParameters, Transport, TransportMode, TransportParameters, Transports, }; pub use unsupported::Unsupported;
fn sum(a: i32, b: i32) -> i32 { a + b } fn display_result(result: i32) { println!("{:?}", result); } fn main() { let result_sum = sum(6, 999999); display_result(result_sum); }
use std::collections::BTreeMap; fn main() { // my test inputs: 236491 to 713787. let p = all_possibilities(236_491, 713_787); println!("Checking {} possibilities", p.len()); let candidate_pws: Vec<&i32> = p .iter() .filter(|x| has_double(**x) && !has_decreasing_digits(**x)) .collect(); println!("Candidate count: {}", candidate_pws.len()); } fn all_possibilities(start: i32, end: i32) -> Vec<i32> { let mut v = Vec::new(); for i in start..=end { // println!("pushing {}", i); v.push(i); } v } // has two adjacent digits that are the same fn has_double(input: i32) -> bool { let mut dbls: BTreeMap<char, i32> = BTreeMap::new(); let s = format!("{}", input); let mut last_seen: char = ' '; for i in s.chars() { if last_seen == ' ' { last_seen = i; continue; } if last_seen == i { // a double! *dbls.entry(i).or_insert(0) += 1; } last_seen = i; } // do we see anything in the btreemap with a count greater than one? // as long as we have at least one with a value of 1 we're good: let dbl_count: BTreeMap<&char, &i32> = dbls.iter().filter(|x| x.1 == &1).collect(); !dbl_count.is_empty() } // numbers go down, such as 2230 or 5676 fn has_decreasing_digits(input: i32) -> bool { let s = format!("{}", input); let mut highest_number = 10; let mut at_first_char = true; for i in s.chars() { if at_first_char { at_first_char = false; highest_number = i.to_digit(10).unwrap() } // https://stackoverflow.com/questions/43983414/how-to-convert-a-rust-char-to-an-integer-so-that-1-becomes-1 if i.to_digit(10).unwrap() >= highest_number { highest_number = i.to_digit(10).unwrap(); } else { // this digit is smaller than something we've seen before return true; } } false } #[cfg(test)] mod tests { use super::*; #[test] fn test_doubles() { assert_eq!(has_double(123456), false); assert_eq!(has_double(1232456), false); assert_eq!(has_double(122), true); assert_eq!(has_double(123789), false); assert_eq!(has_double(111111), false); assert_eq!(has_double(123444), false); assert_eq!(has_double(111122), true); } #[test] fn test_decreasing() { assert_eq!(has_decreasing_digits(123456), false); assert_eq!(has_decreasing_digits(122), false); assert_eq!(has_decreasing_digits(1221), true); assert_eq!(has_decreasing_digits(12210), true); assert_eq!(has_decreasing_digits(10), true); assert_eq!(has_decreasing_digits(223450), true); } #[test] fn test_possibilty_generator() { assert_eq!(all_possibilities(0, 2), vec!(0, 1, 2)); assert_eq!(all_possibilities(1, 2), vec!(1, 2)); } }
use crate::database::*; use crate::ShowResult; use serde::{Deserialize, Serialize}; use std::path::PathBuf; #[derive(Debug, Deserialize, Serialize)] pub struct Show { pub id: i64, pub name: String, pub path: PathBuf, pub episodes: Vec<Episode>, pub name_pattern: Vec<String>, } #[derive(Debug, Deserialize, Serialize)] pub struct Episode { pub id: i64, pub name: String, pub season: i32, pub episode: i32, pub is_special: bool, } impl From<ShowResult> for Show { fn from(show: ShowResult) -> Self { Self { id: show.id, episodes: Vec::new(), path: Default::default(), name: show.name.clone(), name_pattern: show .name .split_whitespace() .map(|x| x.to_lowercase()) .collect(), } } } impl From<EpisodeResult> for Episode { fn from(episode: EpisodeResult) -> Self { Self { id: episode.id, name: episode.name.clone(), season: episode.season, episode: episode.number.unwrap_or(0), is_special: episode.episode_type != "regular", } } }
use ring::digest::{digest, Context, SHA256}; use ring::hmac::{sign, Key, HMAC_SHA256}; use std::convert::TryInto; use std::fmt::{Debug, Formatter}; use std::{fmt, mem}; #[derive(Clone)] pub struct ContentSet { /// HOTP generated name pub name: String, /// Current size of the DNS record pub size: usize, /// Typed string entries pub entries: Vec<ContentEntry>, /// Context that will generate the final hash pub hash_context: Option<Context>, } impl PartialEq for ContentSet { fn eq(&self, other: &Self) -> bool { self.name.eq(&other.name) && self.entries.eq(&other.entries) } } impl Debug for ContentSet { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { f.debug_struct("ContentSet") .field("name", &self.name) .field("size", &self.size) .field("entries", &self.entries) .finish() } } impl ContentSet { pub fn new(name: String) -> ContentSet { ContentSet { name, // Start with integrity hash size size: 44, hash_context: Some(Context::new(&SHA256)), entries: vec![ContentEntry::Hash([0; 32])], } } /// Calculate the final hash pub fn calculate_hash(&mut self) { if let ContentEntry::Hash(hash) = &mut self.entries[0] { let old = mem::replace(&mut self.hash_context, None); if let Some(ctx) = old { hash.copy_from_slice(&ctx.finish().as_ref()); } } else { panic!("First entry of ContentSet should be a hash") } } /// Add an entry to this ContentSet pub fn add_entry(&mut self, entry: ContentEntry) -> Result<(), ContentEntry> { if self.size + entry.dns_size() > u16::MAX as usize { return Err(entry); } self.size += entry.dns_size(); if let Some(ctx) = &mut self.hash_context { ctx.update(entry.to_string().as_bytes()); } self.entries.push(entry); Ok(()) } } #[derive(Debug, Clone, Eq, PartialEq)] pub enum ContentEntry { Hash([u8; 32]), Content(String), EOF([u8; 32]), } impl ContentEntry { fn dns_size(&self) -> usize { 1 + match self { ContentEntry::Hash(_) | ContentEntry::EOF(_) => 44, ContentEntry::Content(data) if data.is_ascii() => data.len(), _ => panic!("Non-ASCII characters in base64 output?"), } } } impl ToString for ContentEntry { fn to_string(&self) -> String { match self { ContentEntry::Hash(hash) | ContentEntry::EOF(hash) => base64::encode(hash), ContentEntry::Content(data) => data.clone(), } } } pub struct PolysemeBuilder { shared_key: Vec<u8>, hmac_key: Key, counter: u64, base64_buffer: Vec<u8>, current_chunk: String, current_set: ContentSet, } pub(crate) fn next_ahotp(counter: &mut u64, shared_key: &Key) -> String { let hash = sign(shared_key, counter.to_be_bytes().as_ref()); *counter += 1; base32::encode(base32::Alphabet::Crockford, hash.as_ref()).to_ascii_lowercase() } impl PolysemeBuilder { pub fn new(shared_key: &[u8]) -> PolysemeBuilder { let key = Key::new(HMAC_SHA256, shared_key); let mut counter = 0; let current_set = ContentSet::new(next_ahotp(&mut counter, &key)); PolysemeBuilder { shared_key: shared_key.to_vec(), hmac_key: key, counter, current_chunk: String::new(), base64_buffer: Vec::new(), current_set, } } fn next_chunk(&mut self) -> Option<String> { if self.current_chunk.len() < 255 { return None; } let (chunk, rest) = self.current_chunk.split_at(255); let chunk = chunk.to_string(); self.current_chunk = rest.to_string(); Some(chunk) } fn add_content_entry(&mut self, content_entry: ContentEntry) -> Option<ContentSet> { let mut return_val = None; if let Err(entry) = self.current_set.add_entry(content_entry) { let mut next_set = ContentSet::new(next_ahotp(&mut self.counter, &self.hmac_key)); next_set .add_entry(entry) .expect("New record set immediately full? this should not happen"); self.current_set.calculate_hash(); return_val = Some(mem::replace(&mut self.current_set, next_set)); } return_val } fn add_eof(&mut self) -> Option<ContentSet> { self.add_content_entry(ContentEntry::EOF( digest(&SHA256, &self.shared_key) .as_ref() .try_into() .unwrap(), )) } fn add_chunk(&mut self, chunk: String) -> Option<ContentSet> { debug_assert!( chunk.len() == 255, "Chunk given to PolysemeBuilder::add_chunk should be exactly 255 bytes long" ); self.add_unchecked_chunk(chunk) } #[inline] fn add_unchecked_chunk(&mut self, chunk: String) -> Option<ContentSet> { return self.add_content_entry(ContentEntry::Content(chunk)); } pub fn consume(&mut self, input: &[u8]) -> Vec<ContentSet> { self.base64_buffer.append(&mut input.to_vec()); let (to_decode, rest) = self .base64_buffer .split_at(self.base64_buffer.len() - (self.base64_buffer.len() % 3)); self.current_chunk += &base64::encode(to_decode); self.base64_buffer = rest.to_vec(); let mut buffer = vec![]; while let Some(chunk) = self.next_chunk() { if let Some(content_set) = self.add_chunk(chunk) { buffer.push(content_set) } } buffer } pub fn finalize(mut self) -> Vec<ContentSet> { let mut buffer = vec![]; self.current_chunk += &base64::encode(&self.base64_buffer); let chunk = self.current_chunk.split_off(0); if let Some(set) = self.add_unchecked_chunk(chunk) { buffer.push(set); } assert!( self.add_eof().is_none(), "EOF should only add 1 entry and never overflow the current buffer" ); self.current_set.calculate_hash(); buffer.push(self.current_set); buffer } } pub fn create_polyseme(shared_key: &[u8], input: &[u8]) -> Vec<ContentSet> { let mut builder = PolysemeBuilder::new(shared_key); let mut sets = builder.consume(input); sets.append(&mut builder.finalize()); sets }
/* Copyright 2020 <盏一 w@hidva.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::access::clog::SessionExt as ClogSessionExt; use crate::access::clog::WorkerExt as ClogWorkerExt; use crate::access::csmvcc::TabMVCC; use crate::access::fd::{SessionExt as FDSessionExt, WorkerExt as FDWorkerExt}; use crate::access::lmgr; use crate::access::{ckpt, sv}; use crate::access::{clog, wal, xact}; use crate::catalog::namespace::SessionStateExt as NameSpaceSessionStateExt; use crate::Oid; use crate::{guc, kbensure, protocol, GlobalState, SockWriter}; use anyhow::anyhow; use chrono::offset::Local; use chrono::DateTime; use crossbeam_channel::{unbounded, Receiver}; use nix::libc::off_t; use nix::sys::uio::IoVec; use nix::unistd::SysconfVar::IOV_MAX; use std::alloc::Layout; use std::fs::File; use std::io::Write; use std::num::NonZeroU16; use std::os::unix::io::RawFd; use std::path::Path; use std::ptr::NonNull; use std::sync::{atomic::AtomicBool, atomic::AtomicU32, atomic::Ordering::Relaxed, Arc}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tempfile::NamedTempFile; use threadpool::ThreadPool; pub mod adt; pub mod err; pub mod fmgr; pub mod marc; pub mod sb; pub mod ser; pub struct WorkerState { pub wal: Option<&'static wal::GlobalStateExt>, pub clog: clog::WorkerStateExt, pub xact: xact::WorkerStateExt, pub fmgr_builtins: &'static fmgr::FmgrBuiltinsMap, pub sessid: u32, pub reqdb: Oid, pub termreq: Arc<AtomicBool>, pub gucstate: Arc<guc::GucState>, } pub struct WorkerExit { pub xact: xact::WorkerExitExt, } impl WorkerState { pub fn new(session: &SessionState) -> WorkerState { WorkerState { fmgr_builtins: session.fmgr_builtins, sessid: session.sessid, reqdb: session.reqdb, termreq: session.termreq.clone(), gucstate: session.gucstate.clone(), clog: session.clog, xact: xact::WorkerStateExt::new(session), wal: session.wal, } } pub fn init_thread_locals(&self) { self.resize_clog_l1cache(); self.resize_fdcache(); } pub fn exit(&self) -> WorkerExit { WorkerExit { xact: self.xact.exit(), } } } pub struct SessionState { thdpool: Option<threadpool::ThreadPool>, pub clog: clog::WorkerStateExt, pub fmgr_builtins: &'static fmgr::FmgrBuiltinsMap, pub sessid: u32, pub reqdb: Oid, pub db: String, pub termreq: Arc<AtomicBool>, pub gucstate: Arc<guc::GucState>, pub metaconn: sqlite::Connection, pub xact: xact::SessionStateExt, pub wal: Option<&'static wal::GlobalStateExt>, pub stmt_startts: KBSystemTime, pub dead: bool, pub nsstate: NameSpaceSessionStateExt, pub oid_creator: Option<&'static AtomicU32>, // nextoid pub lmgrg: &'static lmgr::GlobalStateExt, pub lmgrs: lmgr::SessionStateExt<'static>, pub pending_fileops: &'static ckpt::PendingFileOps, pub tabsv: &'static sv::TabSupVer, pub tabmvcc: &'static TabMVCC, } pub struct WorkerExitGuard<'a, T> { rec: &'a Receiver<T>, } impl<'a, T> WorkerExitGuard<'a, T> { pub fn new(rec: &'a Receiver<T>) -> Self { Self { rec } } } impl<'a, T> Drop for WorkerExitGuard<'a, T> { fn drop(&mut self) { for _item in self.rec.iter() {} } } impl SessionState { pub fn init_thread_locals(&self) { self.resize_clog_l1cache(); self.resize_fdcache(); } pub fn new( sessid: u32, reqdb: Oid, db: String, termreq: Arc<AtomicBool>, metaconn: sqlite::Connection, gstate: GlobalState, ) -> Self { let now = KBSystemTime::now(); Self { thdpool: None, sessid, reqdb, db, termreq, fmgr_builtins: gstate.fmgr_builtins, gucstate: gstate.gucstate, metaconn, dead: false, nsstate: NameSpaceSessionStateExt::default(), clog: clog::WorkerStateExt::new(gstate.clog), stmt_startts: now.into(), xact: xact::SessionStateExt::new(gstate.xact, now), wal: gstate.wal, lmgrg: gstate.lmgr, lmgrs: lmgr::SessionStateExt::new(), oid_creator: gstate.oid_creator, pending_fileops: gstate.pending_fileops, tabsv: gstate.tabsv, tabmvcc: gstate.tabmvcc, } } pub fn on_error(&self, err: &anyhow::Error, stream: &mut SockWriter) { let lvl = if self.dead { protocol::SEVERITY_FATAL } else { protocol::SEVERITY_ERR }; crate::on_error(lvl, err, stream); } pub fn update_stmt_startts(&mut self) { self.stmt_startts = KBSystemTime::now(); } pub fn new_worker(&self) -> WorkerState { WorkerState::new(self) } // Only invokded when commit. pub fn exit_worker(&mut self, e: WorkerExit) { self.xact.exit_worker(e.xact); } fn pool(&self) -> &ThreadPool { // unsafe {self.thdpool.as_ref().unwrap_unchecked()} self.thdpool.as_ref().unwrap() } fn resize_pool(&mut self, parallel: usize) { match self.thdpool.as_mut() { None => { self.thdpool = Some(ThreadPool::new(parallel)); } Some(p) => { debug_assert_eq!(p.queued_count(), 0); p.set_num_threads(parallel); } } } pub fn exec<Args: Send + 'static, Ret: Send + 'static>( &mut self, parallel: usize, args_gene: impl Fn(usize) -> Args, body: impl FnOnce(Args, &mut WorkerState) -> Ret + Send + 'static + Clone, ) -> Receiver<(WorkerExit, Ret)> { debug_assert!(parallel > 0); self.resize_pool(parallel); let (send, receiver) = unbounded::<(WorkerExit, Ret)>(); let lastno = parallel - 1; for idx in 0..lastno { let args = args_gene(idx); let mut worker = self.new_worker(); let body2 = body.clone(); let send2 = send.clone(); self.pool().execute(move || { worker.init_thread_locals(); let ret = body2(args, &mut worker); send2.send((worker.exit(), ret)).unwrap(); }); } let args = args_gene(lastno); let mut worker = self.new_worker(); self.pool().execute(move || { worker.init_thread_locals(); let ret = body(args, &mut worker); send.send((worker.exit(), ret)).unwrap(); }); return receiver; } pub fn check_termreq(&self) -> anyhow::Result<()> { kbensure!( !self.termreq.load(Relaxed), ERRCODE_ADMIN_SHUTDOWN, "terminating connection due to administrator command" ); return Ok(()); } } pub struct ExecSQLOnDrop<'a, 'b> { conn: &'a sqlite::Connection, sql: &'b str, } impl<'a, 'b> ExecSQLOnDrop<'a, 'b> { pub fn new(conn: &'a sqlite::Connection, sql: &'b str) -> ExecSQLOnDrop<'a, 'b> { Self { conn, sql } } } impl<'a, 'b> Drop for ExecSQLOnDrop<'a, 'b> { fn drop(&mut self) { if let Err(err) = self.conn.execute(self.sql) { log::warn!( "ExecSQLOnDrop: failed to execute sql: sql={} err={}", self.sql, err ); } } } pub type AttrNumber = NonZeroU16; pub type Xid = std::num::NonZeroU64; pub fn inc_xid(v: Xid) -> Xid { Xid::new(v.get() + 1).unwrap() } pub fn dec_xid(v: Xid) -> Xid { Xid::new(v.get() - 1).unwrap() } pub fn sync_dir<P: AsRef<Path>>(path: P) -> std::io::Result<()> { File::open(path)?.sync_data() } // Path::new(file).parent().unwrap() must not be empty. pub fn persist<P: AsRef<Path>>(file: P, d: &[u8]) -> anyhow::Result<()> { let path = file.as_ref(); { let mut tempf = NamedTempFile::new_in(".")?; tempf.write_all(d)?; tempf.flush()?; let targetfile = tempf.persist(path)?; targetfile.sync_data()?; } let dir = path .parent() .ok_or_else(|| anyhow!("persist: invalid filepath. file={:?}", path))?; sync_dir(dir)?; Ok(()) } // just for implementing Display trait #[derive(Clone, Copy)] pub struct KBSystemTime(SystemTime); impl std::fmt::Display for KBSystemTime { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let t: DateTime<Local> = self.0.into(); write!(f, "{}", t) } } impl std::fmt::Debug for KBSystemTime { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let t: DateTime<Local> = self.0.into(); write!(f, "{:?}", t) } } impl std::convert::From<SystemTime> for KBSystemTime { fn from(v: SystemTime) -> Self { Self(v) } } impl std::convert::From<KBSystemTime> for SystemTime { fn from(v: KBSystemTime) -> Self { v.0 } } impl KBSystemTime { pub fn now() -> Self { Self(SystemTime::now()) } } impl std::convert::From<u64> for KBSystemTime { fn from(v: u64) -> Self { UNIX_EPOCH.checked_add(Duration::new(v, 0)).unwrap().into() } } impl std::convert::From<KBSystemTime> for u64 { fn from(v: KBSystemTime) -> Self { v.0.duration_since(UNIX_EPOCH).unwrap().as_secs() } } fn valid_layout(size: usize, align: usize) -> bool { // align is the typalign that has been checked at CRAETE TYPE. debug_assert!(align.is_power_of_two()); size <= usize::MAX - (align - 1) } // Use std::alloc::Allocator instead. // Just like Vec and HashMap, out-of-memory is not considered here.. pub fn doalloc(mut size: usize, align: usize) -> NonNull<u8> { if size == 0 { // GlobalAlloc: undefined behavior can result if the caller does not ensure // that layout has non-zero size. size = 2; } debug_assert!(Layout::from_size_align(size, align).is_ok()); let ret = unsafe { std::alloc::alloc(Layout::from_size_align_unchecked(size, align)) }; return NonNull::new(ret).expect("alloc failed"); } pub fn alloc(size: usize, align: usize) -> NonNull<u8> { assert!( valid_layout(size, align), "valid_layout failed: size: {}, align: {}", size, align ); return doalloc(size, align); } pub fn dealloc(ptr: NonNull<u8>, mut size: usize, align: usize) { if size == 0 { size = 2; } debug_assert!(Layout::from_size_align(size, align).is_ok()); unsafe { std::alloc::dealloc(ptr.as_ptr(), Layout::from_size_align_unchecked(size, align)); } } pub fn realloc(ptr: NonNull<u8>, align: usize, mut osize: usize, mut nsize: usize) -> NonNull<u8> { if osize == 0 { osize = 2; } if nsize == 0 { nsize = 2; } assert!( valid_layout(nsize, align), "valid_layout failed: size: {}, align: {}", nsize, align ); debug_assert!(Layout::from_size_align(osize, align).is_ok()); let ret = unsafe { std::alloc::realloc( ptr.as_ptr(), Layout::from_size_align_unchecked(osize, align), nsize, ) }; return NonNull::new(ret).expect("realloc failed"); } #[cfg(target_os = "linux")] fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], offset: off_t) -> nix::Result<usize> { use nix::sys::uio::pwritev as _pwritev; _pwritev(fd, iov, offset) } #[cfg(target_os = "macos")] fn pwritev(fd: RawFd, iov: &[IoVec<&[u8]>], offset: off_t) -> nix::Result<usize> { use nix::sys::uio::pwrite; let mut buff = Vec::<u8>::new(); for iv in iov { buff.extend_from_slice(iv.as_slice()); } pwrite(fd, buff.as_slice(), offset) } pub fn pwritevn<'a>( fd: RawFd, iov: &'a mut [IoVec<&'a [u8]>], mut offset: off_t, ) -> nix::Result<usize> { let orig_offset = offset; let iovmax = IOV_MAX as usize; let iovlen = iov.len(); let mut sidx: usize = 0; while sidx < iovlen { let eidx = std::cmp::min(iovlen, sidx + iovmax); let wplan = &mut iov[sidx..eidx]; let mut part = pwritev(fd, wplan, offset)?; offset += part as off_t; for wiov in wplan { let wslice = wiov.as_slice(); let wiovlen = wslice.len(); if wiovlen > part { let wpartslice = unsafe { std::slice::from_raw_parts(wslice.as_ptr().add(part), wiovlen - part) }; *wiov = IoVec::from_slice(wpartslice); break; } sidx += 1; part -= wiovlen; if part <= 0 { break; } } } Ok((offset - orig_offset) as usize) }
//! Read and write entities. use crate::world::{self, World, ENTITY_COUNT}; use std::io; use std::path::{Path, PathBuf}; /// The name of entity folder. pub const FOLDER: &str = "entities"; /// Gets a list of all entity files. pub fn files(project_folder: &str) -> io::Result<Vec<PathBuf>> { use std::fs::read_dir; let mut result = Vec::with_capacity(ENTITY_COUNT); let project_folder: PathBuf = PathBuf::from(project_folder); let entities_folder = project_folder.join(FOLDER); for entry in read_dir(entities_folder)? { let entry = entry?; // Ignore files that starts with ".". if let Some(file_name) = entry.file_name().to_str() { if file_name.starts_with('.') { continue; } } let metadata = entry.metadata()?; if metadata.is_file() { result.push(entry.path()); } } Ok(result) } /// Get entities folder. pub fn folder(project_folder: &str) -> PathBuf { let project_folder: PathBuf = PathBuf::from(project_folder); project_folder.join(FOLDER) } /// Loads entities from files. pub fn load(w: &mut World, files: &[PathBuf]) -> Result<(), io::Error> { use crate::math::{Vec3, AABB}; use piston_meta::bootstrap::Convert; use piston_meta::*; use range::Range; use std::fs::File; use std::io::Read; use std::sync::Arc; use world::Mask; fn read_header(mut convert: Convert) -> Result<(Range, (Option<Arc<String>>, usize)), ()> { let start = convert; let header = "header"; let range = convert.start_node(header)?; convert.update(range); let mut name = None; let mut entity_id = None; loop { if let Ok((range, val)) = convert.meta_string("name") { name = Some(val); convert.update(range); } else if let Ok((range, val)) = convert.meta_f64("entity_id") { entity_id = Some(val as usize); convert.update(range); } else if let Ok(range) = convert.end_node(header) { convert.update(range); break; } else { return Err(()); } } let entity_id = match entity_id { None => { return Err(()); } Some(x) => x, }; Ok((convert.subtract(start), (name, entity_id))) } fn read_vec3(name: &str, mut convert: Convert) -> Result<(Range, Vec3), ()> { let start = convert; let range = convert.start_node(name)?; convert.update(range); let mut x = 0.0; let mut y = 0.0; let mut z = 0.0; loop { if let Ok((range, val)) = convert.meta_f64("x") { x = val as f32; convert.update(range); } else if let Ok((range, val)) = convert.meta_f64("y") { y = val as f32; convert.update(range); } else if let Ok((range, val)) = convert.meta_f64("z") { z = val as f32; convert.update(range); } else if let Ok(range) = convert.end_node(name) { convert.update(range); break; } else { return Err(()); } } Ok((convert.subtract(start), [x, y, z])) } fn read_aabb(mut convert: Convert) -> Result<(Range, AABB), ()> { let start = convert; let name = "aabb"; let range = convert.start_node(name)?; convert.update(range); let mut min = None; let mut max = None; loop { if let Ok((range, val)) = read_vec3("min", convert) { min = Some(val); convert.update(range); } else if let Ok((range, val)) = read_vec3("max", convert) { max = Some(val); convert.update(range); } else if let Ok(range) = convert.end_node(name) { convert.update(range); break; } else { return Err(()); } } let min = match min { None => { return Err(()); } Some(x) => x, }; let max = match max { None => { return Err(()); } Some(x) => x, }; Ok((convert.subtract(start), AABB { min, max })) } let syntax_source = include_str!("../../assets/entity/syntax.txt"); let syntax = stderr_unwrap(syntax_source, syntax(syntax_source)); let mut data = vec![]; let mut entity_source = String::new(); for f in files { data.clear(); entity_source.clear(); let mut file = File::open(f)?; file.read_to_string(&mut entity_source)?; // TODO: Return an error message. stderr_unwrap(&entity_source, parse(&syntax, &entity_source, &mut data)); let mut convert = Convert::new(&data); let mut header = None; let mut position = None; let mut aabb = None; loop { if let Ok((range, val)) = read_header(convert) { header = Some(val); convert.update(range); } else if let Ok((range, val)) = read_vec3("position", convert) { position = Some(val); convert.update(range); } else if let Ok((range, val)) = read_aabb(convert) { aabb = Some(val); convert.update(range); } else { break; } } // TODO: Return an error message if header is missing. let (name, id) = match header { None => { panic!("header is missing in file `{}`", f.to_str().unwrap()); } Some(x) => x, }; w.mask[id].insert(Mask::ALIVE); w.name[id] = name; if let Some(pos) = position { w.init.position[id] = pos; w.prev.position[id] = pos; w.current.position[id] = pos; w.next.position[id] = pos; } if let Some(aabb) = aabb { w.aabb[id] = aabb; w.mask[id].insert(world::Mask::AABB); } info!("Loaded entity {}", f.file_name().unwrap().to_str().unwrap()); } Ok(()) } /// Saves entities data. pub fn save<P: AsRef<Path>>(w: &World, entities_folder: P) -> Result<(), io::Error> { use std::fs::File; use std::io::Write; use world::Mask; let entities_folder = entities_folder.as_ref(); for id in 0..ENTITY_COUNT { if !w.mask[id].contains(Mask::ALIVE) { continue; } let f = entities_folder.join(format!("{}.txt", id)); let mut file = File::create(f)?; // Header if let Some(ref name) = w.name[id] { writeln!(file, "{}", name)?; } else { writeln!(file, "<name>")?; } writeln!(file, "{}", id)?; // Position. writeln!(file, "position")?; let pos = w.init.position[id]; for i in 0..3 { writeln!(file, "\t{}", pos[i])?; } // AABB. if w.mask[id].contains(world::Mask::AABB) { let aabb = w.aabb[id]; writeln!(file, "aabb")?; writeln!(file, " min")?; for i in 0..3 { writeln!(file, " {}", aabb.min[i])?; } writeln!(file, " max")?; for i in 0..3 { writeln!(file, " {}", aabb.max[i])?; } } info!("Saved entity id {}", id); } Ok(()) }
#[doc = "Reader of register FC0_RESULT"] pub type R = crate::R<u32, super::FC0_RESULT>; #[doc = "Reader of field `KHZ`"] pub type KHZ_R = crate::R<u32, u32>; #[doc = "Reader of field `FRAC`"] pub type FRAC_R = crate::R<u8, u8>; impl R { #[doc = "Bits 5:29"] #[inline(always)] pub fn khz(&self) -> KHZ_R { KHZ_R::new(((self.bits >> 5) & 0x01ff_ffff) as u32) } #[doc = "Bits 0:4"] #[inline(always)] pub fn frac(&self) -> FRAC_R { FRAC_R::new((self.bits & 0x1f) as u8) } }
//! Tests auto-converted from "sass-spec/spec/non_conformant/errors/interpolation" #[allow(unused)] use super::rsass; // From "sass-spec/spec/non_conformant/errors/interpolation/error-1.hrx" // Ignoring "error_1", error tests are not supported yet.
use crate::{ options::{BuildMode, BuildOptions, FuzzDirWrapper}, project::FuzzProject, RunCommand, }; use anyhow::Result; use clap::Parser; #[derive(Clone, Debug, Parser)] pub struct Check { #[command(flatten)] pub build: BuildOptions, #[command(flatten)] pub fuzz_dir_wrapper: FuzzDirWrapper, /// Name of the fuzz target to check, or check all targets if not supplied pub target: Option<String>, } impl RunCommand for Check { fn run_command(&mut self) -> Result<()> { let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?; project.exec_build(BuildMode::Check, &self.build, self.target.as_deref()) } }
use std::fs::*; use std::io::Read; pub enum LoadError { NotFound(String), CouldntOpen(String), } pub fn load_file(file_name: impl Into<String>) -> Result<(std::path::PathBuf, String), LoadError> { let file_name = file_name.into(); let path = std::path::Path::new(&file_name); //.with_extension("rb"); let absolute_path = match path.canonicalize() { Ok(path) => path, Err(ioerr) => { let msg = format!("{}", ioerr); return Err(LoadError::NotFound(msg)); } }; let mut file_body = String::new(); match OpenOptions::new().read(true).open(&absolute_path) { Ok(mut file) => match file.read_to_string(&mut file_body) { Ok(_) => {} Err(ioerr) => { let msg = format!("{}", ioerr); return Err(LoadError::CouldntOpen(msg)); } }, Err(ioerr) => { let msg = format!("{}", ioerr); return Err(LoadError::CouldntOpen(msg)); } }; Ok((absolute_path, file_body)) }
use sqlx::{query_file, query_file_as, Error, PgPool}; use time::OffsetDateTime; use uuid::Uuid; use super::{category::Category, rating::Rating}; /// New image without ID pub struct NewImage { pub title: String, pub description: Option<String>, } pub struct Image { pub id: Uuid, pub created: OffsetDateTime, pub upload_date: Option<OffsetDateTime>, pub title: String, pub description: Option<String>, pub app_user_id: Uuid, } impl Image { pub async fn by_id(id: Uuid, pool: &PgPool) -> Result<Option<Image>, sqlx::Error> { let res = query_file_as!(Image, "queries/image/by_id.sql", id) .fetch_one(pool) .await; match res { Ok(image) => Ok(Some(image.into())), Err(e) => match e { Error::RowNotFound => Ok(None), _ => Err(e.into()), }, } } pub async fn by_app_user_id( app_user_id: Uuid, pool: &PgPool, ) -> Result<Vec<Image>, sqlx::Error> { Ok( query_file_as!(Image, "queries/image/by_app_user_id.sql", app_user_id) .fetch_all(pool) .await?, ) } pub async fn new( app_user_id: Uuid, image: NewImage, pool: &PgPool, ) -> Result<Uuid, sqlx::Error> { Ok(query_file!( "queries/image/create.sql", app_user_id, image.title, image.description ) .fetch_one(pool) .await .map(|v| v.id)?) } pub async fn search( s: Option<&str>, offset: Option<i64>, limit: Option<i64>, pool: &PgPool, ) -> Result<Vec<Image>, sqlx::Error> { match s { Some(s) => query_file_as!( Image, "queries/image/search.sql", s, offset.unwrap_or(0), limit.unwrap_or(10) ) .fetch_all(pool) .await .map(|images| images.into_iter().map(Into::into).collect()), None => query_file_as!( Image, "queries/image/search_no_str.sql", offset.unwrap_or(0), limit.unwrap_or(10) ) .fetch_all(pool) .await .map(|images| images.into_iter().map(Into::into).collect()), } } } impl Image { pub async fn save(&self, pool: &PgPool) -> Result<(), sqlx::Error> { query_file!( "queries/image/update.sql", self.id, self.upload_date, self.title, self.description ) .execute(pool) .await?; Ok(()) } pub async fn rate(&self, user_id: Uuid, rating: i32, pool: &PgPool) -> Result<(), sqlx::Error> { Rating::new(user_id, self.id, rating).save(pool).await } pub async fn ratings(&self, pool: &PgPool) -> Result<Vec<Rating>, sqlx::Error> { Rating::by_image(self.id, pool).await } pub async fn categories(&self, pool: &PgPool) -> Result<Vec<Category>, sqlx::Error> { Category::by_image_id(self.id, pool).await } }
use crate::*; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::path::PathBuf; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Recording { pub device_info: DeviceInfo, #[serde(with = "serde_transaction_map")] pub transactions: HashMap<RecordedHttpRequest, RecordedHttpResponse>, } impl Default for Recording { fn default() -> Self { Self { device_info: DeviceInfo::default(), transactions: HashMap::new(), } } } mod serde_transaction_map { use super::*; use serde::de::SeqAccess; use serde::ser::SerializeSeq; pub(crate) fn serialize<S>( map: &HashMap<RecordedHttpRequest, RecordedHttpResponse>, ser: S, ) -> Result<S::Ok, S::Error> where S: serde::ser::Serializer, { let sorted_requests = { let mut vec = map.keys().collect::<Vec<_>>(); vec.sort_by(|left, right| left.sort_key().cmp(&right.sort_key())); vec }; let mut seq = ser.serialize_seq(Some(map.len()))?; for req in sorted_requests { let resp = &map[req]; let tx = RecordedTransaction { request: req.clone(), response: resp.clone(), }; seq.serialize_element(&tx)?; } seq.end() } pub(crate) fn deserialize<'de, D>( de: D, ) -> Result<HashMap<RecordedHttpRequest, RecordedHttpResponse>, D::Error> where D: serde::de::Deserializer<'de>, { struct V; impl<'de> serde::de::Visitor<'de> for V { type Value = HashMap<RecordedHttpRequest, RecordedHttpResponse>; fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a sequence of recorded transactions") } fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, <A as SeqAccess<'de>>::Error> where A: SeqAccess<'de>, { let mut map = HashMap::new(); while let Some(tx) = seq.next_element::<RecordedTransaction>()? { map.insert(tx.request, tx.response); } Ok(map) } } de.deserialize_seq(V) } } impl Recording { pub fn find<'a>(&'a self, req: &http::Request<Vec<u8>>) -> Option<&'a RecordedHttpResponse> { let req = RecordedHttpRequest::new(req); self.transactions.get(&req) } } pub fn fixture_dir() -> std::path::PathBuf { let root = std::env::var_os("CARGO_MANIFEST_DIR") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(".")); root.join("fixtures").join("recordings") } pub fn fixture_filename(device_info: &DeviceInfo) -> std::path::PathBuf { let filename = PathBuf::from(format!( "{} v{}.json", &device_info.serial_number, &device_info.firmware_version, )); fixture_dir().join(&filename) } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RecordedTransaction { pub request: RecordedHttpRequest, pub response: RecordedHttpResponse, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Hash)] pub struct RecordedHttpRequest { pub method: String, pub path: String, pub headers: RecordedHeaders, #[serde(skip_serializing_if = "Option::is_none")] pub body: Option<RecordedBody>, } impl RecordedHttpRequest { pub fn new<T: AsRef<[u8]>>(req: &http::Request<T>) -> Self { let body = req.body().as_ref(); let body = match (req.method(), std::str::from_utf8(body)) { (&http::Method::GET, _) => None, (_, Ok(str)) => Some(RecordedBody::String(str.to_string())), (_, Err(_)) => Some(RecordedBody::Binary(body.to_vec())), }; Self { method: req.method().to_string(), path: req .uri() .path_and_query() .map(|pq| pq.to_string()) .unwrap_or("".into()), headers: RecordedHeaders::new(req.headers()), body, } } fn sort_key(&self) -> (&str, &str, &[u8]) { ( &self.path, &self.method, self.body.as_ref().map(|b| b.as_slice()).unwrap_or(&[]), ) } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct RecordedHttpResponse { pub status_code: u16, pub headers: RecordedHeaders, pub body: RecordedBody, } impl RecordedHttpResponse { pub fn http_response_builder(&self) -> http::response::Builder { let mut b = http::response::Builder::new() .status(http::StatusCode::from_u16(self.status_code).unwrap()); for (key, value) in &self.headers { b = b.header(key, value); } b } } pub struct RecordedHttpResponseBuilder { pub status_code: u16, pub headers: RecordedHeaders, pub body: Vec<u8>, } impl RecordedHttpResponseBuilder { pub fn new(resp: &http::response::Parts) -> Self { Self { status_code: resp.status.as_u16(), headers: RecordedHeaders::new(&resp.headers), body: Vec::new(), } } pub fn add_body_chunk(&mut self, body: &[u8]) { self.body.extend_from_slice(body); } pub fn build(self) -> RecordedHttpResponse { RecordedHttpResponse { status_code: self.status_code, headers: self.headers, body: match std::str::from_utf8(&self.body) { Ok(str) => RecordedBody::String(str.to_string()), Err(_) => RecordedBody::Binary(self.body), }, } } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, Hash)] pub struct RecordedHeaders { #[serde(skip_serializing_if = "Option::is_none")] pub accept: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub content_type: Option<String>, } impl RecordedHeaders { pub fn new(headers: &http::HeaderMap) -> Self { Self { accept: headers .get(http::header::ACCEPT) .map(|v| v.to_str().unwrap().to_string()), content_type: headers .get(http::header::CONTENT_TYPE) .map(|v| v.to_str().unwrap().to_string()), } } } impl<'a> IntoIterator for &'a RecordedHeaders { type Item = (http::header::HeaderName, http::header::HeaderValue); type IntoIter = std::vec::IntoIter<Self::Item>; fn into_iter(self) -> Self::IntoIter { let mut h = Vec::new(); fn header( h: &mut Vec<(http::header::HeaderName, http::header::HeaderValue)>, name: http::header::HeaderName, value: &Option<String>, ) { if let Some(value) = value { h.push((name, http::header::HeaderValue::from_str(value).unwrap())) } } header(&mut h, http::header::ACCEPT, &self.accept); header(&mut h, http::header::CONTENT_TYPE, &self.content_type); h.into_iter() } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum RecordedBody { String(String), Binary(Vec<u8>), } impl RecordedBody { pub fn as_slice(&self) -> &[u8] { match &self { RecordedBody::String(s) => s.as_bytes(), RecordedBody::Binary(v) => v.as_slice(), } } } impl Hash for RecordedBody { fn hash<H: Hasher>(&self, state: &mut H) { self.as_slice().hash(state) } }
use crate::types::{BoardPosition, PieceType}; use nom; use nom::{bytes::complete::tag, combinator::map_res, IResult}; use std::collections::HashMap; // Brief detour, writing a parser. // A Matrix parser takes input of the following form: // 8 .. .. .B BR .K .. .. .. // 7 .P .. .. .P .. .. .P .. // 6 .. PP .. .. .N QR .. .. // 5 BB .. .. NP .. .P .. .P // 4 P. PN .. .. .. PP .. P. // 3 .. .. .. .. .Q .. .. .. // 2 .. .. N. P. .. P. P. .. // 1 .. R. .. .. .. R. K. .. // * A B C D E F G H #[derive(Debug)] pub struct Matrix(pub HashMap<BoardPosition, Square>); #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Square { pub white: Option<PieceType>, pub black: Option<PieceType>, } impl Square { pub fn pair(white: PieceType, black: PieceType) -> Self { Square { white: Some(white), black: Some(black), } } pub fn white(white: PieceType) -> Self { Square { white: Some(white), black: None, } } pub fn black(black: PieceType) -> Self { Square { white: None, black: Some(black), } } pub fn flip(&self) -> Square { Square { black: self.white, white: self.black, } } pub fn is_empty(&self) -> bool { self.white.is_none() && self.black.is_none() } } fn matrix_transform(input: Vec<(u8, Vec<Square>)>) -> Matrix { let mut matrix = HashMap::new(); for (row, entries) in input { for (x, square) in entries.iter().enumerate() { if square.white.is_some() || square.black.is_some() { if let Some(pos) = BoardPosition::new_checked(x as i8, row as i8 - 1) { matrix.insert(pos, square.clone()); } } } } Matrix(matrix) } pub fn matrix(input: &str) -> IResult<&str, Matrix> { let (input, raw) = nom::multi::separated_list0(tag("\n"), row)(input)?; Ok((input, matrix_transform(raw))) } fn exchange_notation(input: &str) -> IResult<&str, Matrix> { let (input, raw) = nom::multi::separated_list0(tag("\n"), unlabeled_row)(input)?; let row_indices: Vec<u8> = vec![8, 7, 6, 5, 4, 3, 2, 1]; let labeled_rows: Vec<(u8, Vec<Square>)> = row_indices.into_iter().zip(raw.into_iter()).collect(); Ok((input, matrix_transform(labeled_rows))) } pub fn try_exchange_notation(input: &str) -> Option<Matrix> { exchange_notation(input).map(|x| x.1).ok() } fn row(input: &str) -> IResult<&str, (u8, Vec<Square>)> { let (input, index) = nom::character::streaming::one_of("12345678")(input)?; let (input, _) = tag(" ")(input)?; let (input, content) = nom::multi::separated_list0(tag(" "), square)(input)?; Ok((input, (index.to_digit(10).unwrap_or(0) as u8, content))) } fn unlabeled_row(input: &str) -> IResult<&str, Vec<Square>> { let (input, content) = nom::multi::separated_list0(tag(" "), square)(input)?; Ok((input, content)) } fn square(input: &str) -> IResult<&str, Square> { let (input, white) = piece(input)?; let (input, black) = piece(input)?; Ok((input, Square { white, black })) } // Parses a single character into a piece type. fn piece(input: &str) -> IResult<&str, Option<PieceType>> { map_res(nom::character::streaming::one_of(".PRNBQK"), from_piece)(input) } // Converts a character into a piece type fn from_piece(input: char) -> Result<Option<PieceType>, &'static str> { use PieceType::*; match input { '.' => Ok(None), 'P' => Ok(Some(Pawn)), 'R' => Ok(Some(Rook)), 'N' => Ok(Some(Knight)), 'B' => Ok(Some(Bishop)), 'Q' => Ok(Some(Queen)), 'K' => Ok(Some(King)), _ => Err("invalid token"), } }
use std::collections::HashMap; use std::collections::hash_map::Entry; use std::fmt; use std::io; use futures::{self, Future, Sink, Stream, Poll, Async, AsyncSink}; use futures::unsync::mpsc; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::codec::{Framed, FramedParts}; use codec::Codec; use message::{Message, Flag}; use stream::MultiplexStream; pub struct Multiplexer<S> where S: AsyncRead + AsyncWrite { session_stream: futures::stream::SplitStream<Framed<S, Codec>>, is_initiator: bool, next_id: u64, stream_senders: HashMap<u64, mpsc::Sender<Message>>, busy_streams: Vec<u64>, out_sender: mpsc::Sender<Message>, forward: futures::stream::Forward<futures::stream::MapErr<mpsc::Receiver<Message>, fn(()) -> io::Error>, futures::stream::SplitSink<Framed<S, Codec>>>, } impl<S> Multiplexer<S> where S: AsyncRead + AsyncWrite { pub fn from_parts(parts: FramedParts<S>, is_initiator: bool) -> Multiplexer<S> { fn unreachable(_: ()) -> io::Error { unreachable!() } let (out_sender, out_receiver) = mpsc::channel(16); let session = Framed::from_parts(parts, Codec::new()); let (session_sink, session_stream) = session.split(); let forward = out_receiver.map_err(unreachable as _).forward(session_sink); Multiplexer { next_id: 0, stream_senders: Default::default(), busy_streams: Default::default(), session_stream, is_initiator, out_sender, forward, } } fn next_id(&mut self) -> u64 { let id = self.next_id; self.next_id += 2; if self.is_initiator { id } else { id + 1 } } pub fn new_stream(&mut self) -> impl Future<Item=MultiplexStream, Error=io::Error> { let id = self.next_id(); let (in_sender, in_receiver) = mpsc::channel(16); self.stream_senders.insert(id, in_sender); MultiplexStream::initiate(id, in_receiver, self.out_sender.clone()) } pub fn close(self) -> impl Future<Item=(), Error=io::Error> { // Maybe? I think a wave of closure should propagate through from dropping everything else // in self. self.forward.map(|_| ()) } } impl<S> Stream for Multiplexer<S> where S: AsyncRead + AsyncWrite { type Item = MultiplexStream; type Error = io::Error; fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { loop { // Check if we have an incoming message from our peer to handle match self.session_stream.poll()? { Async::Ready(Some(msg)) => { let stream_id = msg.stream_id; match self.stream_senders.entry(stream_id) { Entry::Occupied(mut entry) => { match entry.get_mut().start_send(msg) { Ok(AsyncSink::Ready) => { self.busy_streams.push(stream_id); } Ok(AsyncSink::NotReady(msg)) => { println!("Dropping incoming message {:?} as stream is busy", msg); } Err(err) => { println!("Multiplexer stream {} was closed: {:?}", stream_id, err); entry.remove(); } } } Entry::Vacant(entry) => { if msg.flag == Flag::NewStream { let (in_sender, in_receiver) = mpsc::channel(16); entry.insert(in_sender); return Ok(Async::Ready(Some(MultiplexStream::receive(msg.stream_id, in_receiver, self.out_sender.clone())))); } else { println!("Dropping incoming message {:?} as stream was not opened/is closed", msg); } } } // We need to loop back to give self.session a chance to park itself continue; } Async::Ready(None) => { // The transport was closed, by dropping all the stream senders the streams // will close self.stream_senders.drain(); return Ok(Async::Ready(None)); } Async::NotReady => (), } // For each stream that is dealing with an incoming message we need to check if they're // finished let stream_senders = &mut self.stream_senders; self.busy_streams.retain(|&stream_id| { if let Some(ref mut stream_sender) = stream_senders.get_mut(&stream_id) { if let Ok(Async::NotReady) = stream_sender.poll_complete() { // Not finished yet, will have been parked and we need to check it again // next loop. true } else { // Either it finished and we no longer need to poll, or it has errored..., // I think we're ok to ignore the error here and it will be handled // elsewhere. false } } else { // The stream has closed and been removed elsewhere false } }); // Let the forwarder propagate any message from the streams to the session match self.forward.poll()? { Async::Ready(_) => { // Incoming stream was closed? return Ok(Async::Ready(None)); } Async::NotReady => { return Ok(Async::NotReady); } } } } } impl<S> fmt::Debug for Multiplexer<S> where S: AsyncRead + AsyncWrite + fmt::Debug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if f.alternate() { f.debug_struct("Multiplexer") .field("is_initiator", &self.is_initiator) .field("next_id", &self.next_id) .field("streams", &self.stream_senders.keys()) .field("busy_streams", &self.busy_streams) .finish() } else { f.debug_struct("Multiplexer") .field("session_stream", &self.session_stream) .field("is_initiator", &self.is_initiator) .field("next_id", &self.next_id) .field("stream_senders", &self.stream_senders) .field("busy_streams", &self.busy_streams) .field("out_sender", &self.out_sender) .field("forward", &self.forward) .finish() } } }
fn function() { nested::function(); } mod nested { fn function() { very_nested::function(); } mod very_nested { fn function() { very_very_nested::function(); } mod very_very_nested { fn function() {} } } }
pub mod ansi; pub mod pos; pub mod padding;
use crate::{bson::Document, error::Result, options::ClientOptions, Client}; use super::options::AutoEncryptionOptions; /// A builder for constructing a `Client` with auto-encryption enabled. /// /// ```no_run /// # use bson::doc; /// # use mongocrypt::ctx::KmsProvider; /// # use mongodb::Client; /// # use mongodb::error::Result; /// # async fn func() -> Result<()> { /// # let client_options = todo!(); /// # let key_vault_namespace = todo!(); /// # let key_vault_client: Client = todo!(); /// # let local_key: bson::Binary = todo!(); /// let encrypted_client = Client::encrypted_builder( /// client_options, /// key_vault_namespace, /// [(KmsProvider::Local, doc! { "key": local_key }, None)], /// )? /// .key_vault_client(key_vault_client) /// .build() /// .await?; /// # Ok(()) /// # } /// ``` pub struct EncryptedClientBuilder { client_options: ClientOptions, enc_opts: AutoEncryptionOptions, } impl EncryptedClientBuilder { pub(crate) fn new(client_options: ClientOptions, enc_opts: AutoEncryptionOptions) -> Self { EncryptedClientBuilder { client_options, enc_opts, } } /// Set the client used for data key queries. Will default to an internal client if not set. pub fn key_vault_client(mut self, client: impl Into<Option<Client>>) -> Self { self.enc_opts.key_vault_client = client.into(); self } /// Specify a JSONSchema locally. /// /// Supplying a `schema_map` provides more security than relying on JSON Schemas obtained from /// the server. It protects against a malicious server advertising a false JSON Schema, which /// could trick the client into sending unencrypted data that should be encrypted. /// /// Schemas supplied in the `schema_map` only apply to configuring automatic encryption for /// client side encryption. Other validation rules in the JSON schema will not be enforced by /// the driver and will result in an error. pub fn schema_map( mut self, map: impl IntoIterator<Item = (impl Into<String>, Document)>, ) -> Self { self.enc_opts.schema_map = Some(map.into_iter().map(|(is, d)| (is.into(), d)).collect()); self } /// Disable automatic encryption and do not spawn mongocryptd. Defaults to false. pub fn bypass_auto_encryption(mut self, bypass: impl Into<Option<bool>>) -> Self { self.enc_opts.bypass_auto_encryption = bypass.into(); self } /// Set options related to mongocryptd. pub fn extra_options(mut self, extra_opts: impl Into<Option<Document>>) -> Self { self.enc_opts.extra_options = extra_opts.into(); self } /// Maps namespace to encrypted fields. /// /// Supplying an `encrypted_fields_map` provides more security than relying on an /// encryptedFields obtained from the server. It protects against a malicious server /// advertising a false encryptedFields. pub fn encrypted_fields_map( mut self, map: impl IntoIterator<Item = (impl Into<String>, Document)>, ) -> Self { self.enc_opts.encrypted_fields_map = Some(map.into_iter().map(|(is, d)| (is.into(), d)).collect()); self } /// Disable serverside processing of encrypted indexed fields, allowing use of explicit /// encryption with queryable encryption. pub fn bypass_query_analysis(mut self, bypass: impl Into<Option<bool>>) -> Self { self.enc_opts.bypass_query_analysis = bypass.into(); self } /// Disable loading crypt_shared. #[cfg(test)] pub(crate) fn disable_crypt_shared(mut self, disable: bool) -> Self { self.enc_opts.disable_crypt_shared = Some(disable); self } /// Constructs a new `Client` using automatic encryption. May perform DNS lookups and/or spawn /// mongocryptd as part of `Client` initialization. pub async fn build(self) -> Result<Client> { let client = Client::with_options(self.client_options)?; *client.inner.csfle.write().await = Some(super::ClientState::new(&client, self.enc_opts).await?); Ok(client) } }
use std::cell::RefCell; extern crate num; extern crate primes; #[macro_use] extern crate itertools; // Perform repeated iterations on a single dimension until all the moons are back to their // original state in that dimension. fn simulate(moons: &[RefCell<MoonDimension>]) -> u64 { let moons = moons.to_owned(); let initial_state = moons.clone(); let mut steps = 0; loop { perform_step(&moons); steps += 1; if moons == initial_state { break steps; } } } // Make a single step for all moons but in one dimension. fn perform_step(moons: &[RefCell<MoonDimension>]) { for this_moon_cell in moons { for other_moon_cell in moons { if this_moon_cell as *const _ == other_moon_cell as *const _ { continue; } calc_vel_change(this_moon_cell, other_moon_cell); } } for this_moon_cell in moons { apply_vel_change(this_moon_cell); } } fn calc_vel_change( this_moon_cell: &RefCell<MoonDimension>, other_moon_cell: &RefCell<MoonDimension>, ) { let mut this_moon = this_moon_cell.borrow_mut(); let other_moon = other_moon_cell.borrow(); if other_moon.pos > this_moon.pos { this_moon.vel += 1; } if other_moon.pos < this_moon.pos { this_moon.vel -= 1; } } fn apply_vel_change(moon_cell: &RefCell<MoonDimension>) { let mut moon = moon_cell.borrow_mut(); moon.pos += moon.vel; } fn main() { let start_time = std::time::Instant::now(); // There's no relationship between the three dimensions - what happens in one is entirely // independent of what happens in the other two. We're going to make use of that to // simulate them independently, so store them independently. let dimensions = vec![ vec![ RefCell::new(MoonDimension { pos: -10, vel: 0 }), RefCell::new(MoonDimension { pos: 5, vel: 0 }), RefCell::new(MoonDimension { pos: 3, vel: 0 }), RefCell::new(MoonDimension { pos: 1, vel: 0 }), ], vec![ RefCell::new(MoonDimension { pos: -10, vel: 0 }), RefCell::new(MoonDimension { pos: 5, vel: 0 }), RefCell::new(MoonDimension { pos: 8, vel: 0 }), RefCell::new(MoonDimension { pos: 3, vel: 0 }), ], vec![ RefCell::new(MoonDimension { pos: -13, vel: 0 }), RefCell::new(MoonDimension { pos: -9, vel: 0 }), RefCell::new(MoonDimension { pos: -16, vel: 0 }), RefCell::new(MoonDimension { pos: -3, vel: 0 }), ], ]; // We're going to mutate the data, so use a different copy for each part. let part_1_data = dimensions.clone(); let part_2_data = dimensions; // Part 1 - just perform a thousand iterations on the whole thing. for _ in 0..1_000 { for dimension in &part_1_data { perform_step(dimension); } } let total_energy: i32 = transpose_data(&part_1_data) .iter() .map(Moon::total_energy) .sum(); // Part 2 - figure out how many steps required in each dimension to return to the initial // state (the dimensions are independent, rememeber). The total steps for a complete // return to the initial state is then the lowest common multiple of the steps for each // individual dimension. Because the dimensions are independent, let's run the // simulations on separate threads for a bit more juicy speed. let threads = part_2_data.iter().map(move |dimension| { let moved_dimension = dimension.to_vec(); std::thread::spawn(move || simulate(&moved_dimension)) }).collect::<Vec<_>>(); let steps = threads.into_iter().map(|thread| thread.join().unwrap()).collect::<Vec<_>>(); let iterations_to_reset = lowest_common_multiple(&steps); println!( "Part 1: {}\nPart 2: {}\nTime: {}ms", total_energy, iterations_to_reset, start_time.elapsed().as_millis() ); } // It was better for part 2 to have dimensions containing moons. But part 1 wants moons containing // dimensions, so switch them round. fn transpose_data(data: &[Vec<RefCell<MoonDimension>>]) -> Vec<Moon> { izip!(data[0].clone(), data[1].clone(), data[2].clone()) .map(|(x, y, z)| Moon { x: x.into_inner(), y: y.into_inner(), z: z.into_inner(), }) .collect() } // Yuck, maths. Stole this. fn lowest_common_multiple(nums: &[u64]) -> u64 { let mut lcm = 1; let mut prime_factors = Vec::new(); let mut unique_prime_factors = Vec::new(); for num in nums { let factors = primes::factors(*num); unique_prime_factors.append(&mut factors.clone()); prime_factors.push(factors); } unique_prime_factors.sort_unstable(); unique_prime_factors.dedup(); for unique_factor in unique_prime_factors { let mut max_count = 1; for factor_set in &prime_factors { let mut count = 0; for factor in factor_set { if *factor == unique_factor { count += 1; } } if count > max_count { max_count = count; } } lcm *= num::pow::pow(unique_factor, max_count); } lcm } #[derive(Clone, Copy, PartialEq, Eq)] struct MoonDimension { pos: i32, vel: i32, } struct Moon { x: MoonDimension, y: MoonDimension, z: MoonDimension, } impl Moon { fn potential_energy(&self) -> i32 { self.x.pos.abs() + self.y.pos.abs() + self.z.pos.abs() } fn kinetic_energy(&self) -> i32 { self.x.vel.abs() + self.y.vel.abs() + self.z.vel.abs() } fn total_energy(&self) -> i32 { self.potential_energy() * self.kinetic_energy() } }
#[doc = "Register `AFRCR` reader"] pub type R = crate::R<AFRCR_SPEC>; #[doc = "Register `AFRCR` writer"] pub type W = crate::W<AFRCR_SPEC>; #[doc = "Field `FRL` reader - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] pub type FRL_R = crate::FieldReader; #[doc = "Field `FRL` writer - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] pub type FRL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `FSALL` reader - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] pub type FSALL_R = crate::FieldReader; #[doc = "Field `FSALL` writer - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] pub type FSALL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 7, O>; #[doc = "Field `FSDEF` reader - Frame synchronization definition. This bit is set and cleared by software. When the bit is set, the number of slots defined in the SAI_xSLOTR register has to be even. It means that half of this number of slots are dedicated to the left channel and the other slots for the right channel (e.g: this bit has to be set for I2S or MSB/LSB-justified protocols...). This bit is meaningless and is not used in AC’97 or SPDIF audio block configuration. It must be configured when the audio block is disabled."] pub type FSDEF_R = crate::BitReader; #[doc = "Field `FSPOL` reader - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] pub type FSPOL_R = crate::BitReader<FSPOL_A>; #[doc = "Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FSPOL_A { #[doc = "0: FS is active low (falling edge)"] FallingEdge = 0, #[doc = "1: FS is active high (rising edge)"] RisingEdge = 1, } impl From<FSPOL_A> for bool { #[inline(always)] fn from(variant: FSPOL_A) -> Self { variant as u8 != 0 } } impl FSPOL_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FSPOL_A { match self.bits { false => FSPOL_A::FallingEdge, true => FSPOL_A::RisingEdge, } } #[doc = "FS is active low (falling edge)"] #[inline(always)] pub fn is_falling_edge(&self) -> bool { *self == FSPOL_A::FallingEdge } #[doc = "FS is active high (rising edge)"] #[inline(always)] pub fn is_rising_edge(&self) -> bool { *self == FSPOL_A::RisingEdge } } #[doc = "Field `FSPOL` writer - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] pub type FSPOL_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FSPOL_A>; impl<'a, REG, const O: u8> FSPOL_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "FS is active low (falling edge)"] #[inline(always)] pub fn falling_edge(self) -> &'a mut crate::W<REG> { self.variant(FSPOL_A::FallingEdge) } #[doc = "FS is active high (rising edge)"] #[inline(always)] pub fn rising_edge(self) -> &'a mut crate::W<REG> { self.variant(FSPOL_A::RisingEdge) } } #[doc = "Field `FSOFF` reader - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] pub type FSOFF_R = crate::BitReader<FSOFF_A>; #[doc = "Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum FSOFF_A { #[doc = "0: FS is asserted on the first bit of the slot 0"] OnFirst = 0, #[doc = "1: FS is asserted one bit before the first bit of the slot 0"] BeforeFirst = 1, } impl From<FSOFF_A> for bool { #[inline(always)] fn from(variant: FSOFF_A) -> Self { variant as u8 != 0 } } impl FSOFF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> FSOFF_A { match self.bits { false => FSOFF_A::OnFirst, true => FSOFF_A::BeforeFirst, } } #[doc = "FS is asserted on the first bit of the slot 0"] #[inline(always)] pub fn is_on_first(&self) -> bool { *self == FSOFF_A::OnFirst } #[doc = "FS is asserted one bit before the first bit of the slot 0"] #[inline(always)] pub fn is_before_first(&self) -> bool { *self == FSOFF_A::BeforeFirst } } #[doc = "Field `FSOFF` writer - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] pub type FSOFF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, FSOFF_A>; impl<'a, REG, const O: u8> FSOFF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "FS is asserted on the first bit of the slot 0"] #[inline(always)] pub fn on_first(self) -> &'a mut crate::W<REG> { self.variant(FSOFF_A::OnFirst) } #[doc = "FS is asserted one bit before the first bit of the slot 0"] #[inline(always)] pub fn before_first(self) -> &'a mut crate::W<REG> { self.variant(FSOFF_A::BeforeFirst) } } impl R { #[doc = "Bits 0:7 - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] pub fn frl(&self) -> FRL_R { FRL_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:14 - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] pub fn fsall(&self) -> FSALL_R { FSALL_R::new(((self.bits >> 8) & 0x7f) as u8) } #[doc = "Bit 16 - Frame synchronization definition. This bit is set and cleared by software. When the bit is set, the number of slots defined in the SAI_xSLOTR register has to be even. It means that half of this number of slots are dedicated to the left channel and the other slots for the right channel (e.g: this bit has to be set for I2S or MSB/LSB-justified protocols...). This bit is meaningless and is not used in AC’97 or SPDIF audio block configuration. It must be configured when the audio block is disabled."] #[inline(always)] pub fn fsdef(&self) -> FSDEF_R { FSDEF_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fspol(&self) -> FSPOL_R { FSPOL_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] pub fn fsoff(&self) -> FSOFF_R { FSOFF_R::new(((self.bits >> 18) & 1) != 0) } } impl W { #[doc = "Bits 0:7 - Frame length. These bits are set and cleared by software. They define the audio frame length expressed in number of SCK clock cycles: the number of bits in the frame is equal to FRL\\[7:0\\] + 1. The minimum number of bits to transfer in an audio frame must be equal to 8, otherwise the audio block behaves in an unexpected way. This is the case when the data size is 8 bits and only one slot 0 is defined in NBSLOT\\[4:0\\] of SAI_xSLOTR register (NBSLOT\\[3:0\\] = 0000). In master mode, if the master clock (available on MCLK_x pin) is used, the frame length should be aligned with a number equal to a power of 2, ranging from 8 to 256. When the master clock is not used (NODIV = 1), it is recommended to program the frame length to an value ranging from 8 to 256. These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] #[must_use] pub fn frl(&mut self) -> FRL_W<AFRCR_SPEC, 0> { FRL_W::new(self) } #[doc = "Bits 8:14 - Frame synchronization active level length. These bits are set and cleared by software. They specify the length in number of bit clock (SCK) + 1 (FSALL\\[6:0\\] + 1) of the active level of the FS signal in the audio frame These bits are meaningless and are not used in AC’97 or SPDIF audio block configuration. They must be configured when the audio block is disabled."] #[inline(always)] #[must_use] pub fn fsall(&mut self) -> FSALL_W<AFRCR_SPEC, 8> { FSALL_W::new(self) } #[doc = "Bit 17 - Frame synchronization polarity. This bit is set and cleared by software. It is used to configure the level of the start of frame on the FS signal. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] #[must_use] pub fn fspol(&mut self) -> FSPOL_W<AFRCR_SPEC, 17> { FSPOL_W::new(self) } #[doc = "Bit 18 - Frame synchronization offset. This bit is set and cleared by software. It is meaningless and is not used in AC’97 or SPDIF audio block configuration. This bit must be configured when the audio block is disabled."] #[inline(always)] #[must_use] pub fn fsoff(&mut self) -> FSOFF_W<AFRCR_SPEC, 18> { FSOFF_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "SAI frame configuration register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`afrcr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`afrcr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct AFRCR_SPEC; impl crate::RegisterSpec for AFRCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`afrcr::R`](R) reader structure"] impl crate::Readable for AFRCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`afrcr::W`](W) writer structure"] impl crate::Writable for AFRCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets AFRCR to value 0x07"] impl crate::Resettable for AFRCR_SPEC { const RESET_VALUE: Self::Ux = 0x07; }
#![feature(asm)] #![feature(naked_functions)] #![allow(dead_code)] #![allow(incomplete_features)] #![feature(const_generics)] #![feature(once_cell)] mod bitflags; mod alloc; mod arch; mod fault; pub mod flexarray; pub mod refs; //pub mod gate; //mod libtwz; pub mod event; pub mod name; pub mod obj; mod persist; pub mod ptr; //pub mod queue; //#[cfg(feature = "expose_sapi")] //pub mod sapi; pub mod sys; //pub mod bstream; pub mod device; pub mod kso; //pub mod log; pub mod mutex; //pub mod pslice; pub mod thread; //pub mod vec; pub fn use_runtime() {} #[no_mangle] pub extern "C" fn __twz_libtwz_runtime_init() { fault::__twz_fault_runtime_init(); } #[derive(Debug)] pub enum TxResultErr<E> { UserErr(E), OSError(i32), OutOfLog, } #[derive(Debug)] pub enum TwzErr { NameResolve(i32), OSError(i32), Invalid, OutOfSlots, } pub fn foo() {}
pub mod sort; pub mod heap; pub mod list;
#[doc = "Register `IPCC_C1SCR` reader"] pub type R = crate::R<IPCC_C1SCR_SPEC>; #[doc = "Register `IPCC_C1SCR` writer"] pub type W = crate::W<IPCC_C1SCR_SPEC>; #[doc = "Field `CHxC` reader - CHxC"] pub type CHX_C_R = crate::FieldReader; #[doc = "Field `CHxC` writer - CHxC"] pub type CHX_C_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; #[doc = "Field `CHxS` reader - CHxS"] pub type CHX_S_R = crate::FieldReader; #[doc = "Field `CHxS` writer - CHxS"] pub type CHX_S_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 6, O>; impl R { #[doc = "Bits 0:5 - CHxC"] #[inline(always)] pub fn chx_c(&self) -> CHX_C_R { CHX_C_R::new((self.bits & 0x3f) as u8) } #[doc = "Bits 16:21 - CHxS"] #[inline(always)] pub fn chx_s(&self) -> CHX_S_R { CHX_S_R::new(((self.bits >> 16) & 0x3f) as u8) } } impl W { #[doc = "Bits 0:5 - CHxC"] #[inline(always)] #[must_use] pub fn chx_c(&mut self) -> CHX_C_W<IPCC_C1SCR_SPEC, 0> { CHX_C_W::new(self) } #[doc = "Bits 16:21 - CHxS"] #[inline(always)] #[must_use] pub fn chx_s(&mut self) -> CHX_S_W<IPCC_C1SCR_SPEC, 16> { CHX_S_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "Reading this register will always return 0x0000 0000.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ipcc_c1scr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ipcc_c1scr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IPCC_C1SCR_SPEC; impl crate::RegisterSpec for IPCC_C1SCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ipcc_c1scr::R`](R) reader structure"] impl crate::Readable for IPCC_C1SCR_SPEC {} #[doc = "`write(|w| ..)` method takes [`ipcc_c1scr::W`](W) writer structure"] impl crate::Writable for IPCC_C1SCR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets IPCC_C1SCR to value 0"] impl crate::Resettable for IPCC_C1SCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use reqwest::Error; use reqwest::header; use reqwest::Client; use crate::suika::product::Response; use crate::suika::product::ResponseCollection; #[tokio::main] pub async fn get() -> Result<ResponseCollection, Error> { let mut headers = header::HeaderMap::new(); headers.insert(header::ACCEPT, header::HeaderValue::from_static("application/json")); headers.insert(header::CONTENT_TYPE, header::HeaderValue::from_static("application/json")); let client = Client::builder() .default_headers(headers) .build()?; let total: String = client .get("https://www.vinbudin.is/addons/origo/module/ajaxwebservices/search.asmx/DoSearch") .query(&[ ("category", "beer"), ("count", "0"), ("skip", "0") ]) .send() .await? .json::<Response>() .await? .result .total .to_string(); let response: ResponseCollection = client .get("https://www.vinbudin.is/addons/origo/module/ajaxwebservices/search.asmx/DoSearch") .query(&[ ("category", "beer"), ("count", &total), ("skip", "0") ]) .send() .await? .json::<Response>() .await? .result; Ok(response) }
// Copyright 2021-2023 Sebastian Ramacher // SPDX-License-Identifier: Apache-2.0 OR MIT #![no_std] #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![doc = include_str!("../README.md")] #![doc( html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" )] #![warn(missing_docs)] //! ## Usage //! //! Simple usage (allocating, no associated data): //! //! ``` //! use ascon_aead::{Ascon128, Key, Nonce}; // Or `Ascon128a` //! use ascon_aead::aead::{Aead, KeyInit}; //! //! let key = Key::<Ascon128>::from_slice(b"very secret key."); //! let cipher = Ascon128::new(key); //! //! let nonce = Nonce::<Ascon128>::from_slice(b"unique nonce 012"); // 128-bits; unique per message //! //! let ciphertext = cipher.encrypt(nonce, b"plaintext message".as_ref()) //! .expect("encryption failure!"); // NOTE: handle this error to avoid panics! //! //! let plaintext = cipher.decrypt(nonce, ciphertext.as_ref()) //! .expect("decryption failure!"); // NOTE: handle this error to avoid panics! //! //! assert_eq!(&plaintext, b"plaintext message"); //! ``` //! //! With randomly sampled keys and nonces (requires `getrandom` feature): //! //! ``` //! # #[cfg(feature = "getrandom")] { //! use ascon_aead::Ascon128; // Or `Ascon128a` //! use ascon_aead::aead::{Aead, AeadCore, KeyInit, OsRng}; //! //! let key = Ascon128::generate_key(&mut OsRng); //! let cipher = Ascon128::new(&key); //! //! let nonce = Ascon128::generate_nonce(&mut OsRng); // 128 bits; unique per message //! //! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref()) //! .expect("encryption failure!"); // NOTE: handle this error to avoid panics! //! //! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()) //! .expect("decryption failure!"); // NOTE: handle this error to avoid panics! //! //! assert_eq!(&plaintext, b"plaintext message"); //! # } //! ``` //! //! ## In-place Usage (eliminates `alloc` requirement) //! //! This crate has an optional `alloc` feature which can be disabled in e.g. //! microcontroller environments that don't have a heap. //! //! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`] //! methods accept any type that impls the [`aead::Buffer`] trait which //! contains the plaintext for encryption or ciphertext for decryption. //! //! Note that if you enable the `heapless` feature of this crate, //! you will receive an impl of [`aead::Buffer`] for `heapless::Vec` //! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]), //! which can then be passed as the `buffer` parameter to the in-place encrypt //! and decrypt methods: //! //! ``` //! # #[cfg(feature = "heapless")] { //! use ascon_aead::{Ascon128, Key, Nonce}; // Or `Ascon128a` //! use ascon_aead::aead::{AeadInPlace, KeyInit}; //! use ascon_aead::aead::heapless::Vec; //! //! let key = Key::<Ascon128>::from_slice(b"very secret key."); //! let cipher = Ascon128::new(key); //! //! let nonce = Nonce::<Ascon128>::from_slice(b"unique nonce 012"); // 128-bits; unique per message //! //! let mut buffer: Vec<u8, 128> = Vec::new(); // Buffer needs 16-bytes overhead for authentication tag //! buffer.extend_from_slice(b"plaintext message"); //! //! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext //! cipher.encrypt_in_place(nonce, b"", &mut buffer).expect("encryption failure!"); //! //! // `buffer` now contains the message ciphertext //! assert_ne!(&buffer, b"plaintext message"); //! //! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext //! cipher.decrypt_in_place(nonce, b"", &mut buffer).expect("decryption failure!"); //! assert_eq!(&buffer, b"plaintext message"); //! # } //! ``` //! //! Similarly, enabling the `arrayvec` feature of this crate will provide an impl of //! [`aead::Buffer`] for `arrayvec::ArrayVec`. pub use aead::{self, Error, Key, Nonce, Tag}; use aead::{ consts::{U0, U16, U20}, AeadCore, AeadInPlace, KeyInit, KeySizeUser, }; mod asconcore; use asconcore::{AsconCore, Parameters, Parameters128, Parameters128a, Parameters80pq}; /// Ascon generic over some Parameters /// /// This type is generic to support substituting various Ascon parameter sets. It is not intended to /// be uses directly. Use the [`Ascon128`], [`Ascon128a`], [`Ascon80pq`] type aliases instead. #[derive(Clone)] struct Ascon<P: Parameters> { key: P::InternalKey, } impl<P: Parameters> KeySizeUser for Ascon<P> { type KeySize = P::KeySize; } impl<P: Parameters> KeyInit for Ascon<P> { fn new(key: &Key<Self>) -> Self { Self { key: P::InternalKey::from(key), } } } impl<P: Parameters> AeadCore for Ascon<P> { type NonceSize = U16; type TagSize = U16; type CiphertextOverhead = U0; } impl<P: Parameters> AeadInPlace for Ascon<P> { fn encrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], ) -> Result<Tag<Self>, Error> { if (buffer.len() as u64) .checked_add(associated_data.len() as u64) .is_none() { return Err(Error); } let mut core = AsconCore::<P>::new(&self.key, nonce); Ok(core.encrypt_inplace(buffer, associated_data)) } fn decrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], tag: &Tag<Self>, ) -> Result<(), Error> { if (buffer.len() as u64) .checked_add(associated_data.len() as u64) .is_none() { return Err(Error); } let mut core = AsconCore::<P>::new(&self.key, nonce); core.decrypt_inplace(buffer, associated_data, tag) } } /// Ascon-128 pub struct Ascon128(Ascon<Parameters128>); /// Key for Ascon-128 pub type Ascon128Key = Key<Ascon128>; /// Nonce for Ascon-128 pub type Ascon128Nonce = Nonce<Ascon128>; /// Tag for Ascon-128 pub type Ascon128Tag = Tag<Ascon128>; impl KeySizeUser for Ascon128 { type KeySize = U16; } impl KeyInit for Ascon128 { fn new(key: &Key<Self>) -> Self { Self(Ascon::<Parameters128>::new(key)) } } impl AeadCore for Ascon128 { type NonceSize = U16; type TagSize = U16; type CiphertextOverhead = U0; } impl AeadInPlace for Ascon128 { #[inline(always)] fn encrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], ) -> Result<Tag<Self>, Error> { self.0 .encrypt_in_place_detached(nonce, associated_data, buffer) } #[inline(always)] fn decrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], tag: &Tag<Self>, ) -> Result<(), Error> { self.0 .decrypt_in_place_detached(nonce, associated_data, buffer, tag) } } /// Ascon-128a pub struct Ascon128a(Ascon<Parameters128a>); /// Key for Ascon-128a pub type Ascon128aKey = Key<Ascon128a>; /// Nonce for Ascon-128a pub type Ascon128aNonce = Nonce<Ascon128a>; /// Tag for Ascon-128a pub type Ascon128aTag = Tag<Ascon128a>; impl KeySizeUser for Ascon128a { type KeySize = U16; } impl KeyInit for Ascon128a { fn new(key: &Key<Self>) -> Self { Self(Ascon::<Parameters128a>::new(key)) } } impl AeadCore for Ascon128a { type NonceSize = U16; type TagSize = U16; type CiphertextOverhead = U0; } impl AeadInPlace for Ascon128a { #[inline(always)] fn encrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], ) -> Result<Tag<Self>, Error> { self.0 .encrypt_in_place_detached(nonce, associated_data, buffer) } #[inline(always)] fn decrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], tag: &Tag<Self>, ) -> Result<(), Error> { self.0 .decrypt_in_place_detached(nonce, associated_data, buffer, tag) } } /// Ascon-80pq pub struct Ascon80pq(Ascon<Parameters80pq>); /// Key for Ascon-80pq pub type Ascon80pqKey = Key<Ascon80pq>; /// Nonce for Ascon-80pq pub type Ascon80pqNonce = Nonce<Ascon80pq>; /// Tag for Ascon-80pq pub type Ascon80pqTag = Tag<Ascon80pq>; impl KeySizeUser for Ascon80pq { type KeySize = U20; } impl KeyInit for Ascon80pq { fn new(key: &Key<Self>) -> Self { Self(Ascon::<Parameters80pq>::new(key)) } } impl AeadCore for Ascon80pq { type NonceSize = U16; type TagSize = U16; type CiphertextOverhead = U0; } impl AeadInPlace for Ascon80pq { #[inline(always)] fn encrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], ) -> Result<Tag<Self>, Error> { self.0 .encrypt_in_place_detached(nonce, associated_data, buffer) } #[inline(always)] fn decrypt_in_place_detached( &self, nonce: &Nonce<Self>, associated_data: &[u8], buffer: &mut [u8], tag: &Tag<Self>, ) -> Result<(), Error> { self.0 .decrypt_in_place_detached(nonce, associated_data, buffer, tag) } }
/// A simple trait for transition between the fetch and processing phases /// of Specs systems. pub trait Gate { /// Transition destination type. type Target; /// Actually pass the gate. This may involve waiting on a ticketed lock. fn pass(self) -> Self::Target; } macro_rules! gate { // use variables to indicate the arity of the tuple ($($from:ident),*) => { impl<$($from: Gate),*> Gate for ($($from,)*) { type Target = ($($from::Target,)*); #[allow(non_snake_case)] fn pass(self) -> Self::Target { let ($($from,)*) = self; ($($from.pass(),)*) } } } } gate!(); gate!(A); gate!(A, B); gate!(A, B, C); gate!(A, B, C, D); gate!(A, B, C, D, E); gate!(A, B, C, D, E, F); gate!(A, B, C, D, E, F, G); gate!(A, B, C, D, E, F, G, H); gate!(A, B, C, D, E, F, G, H, I); gate!(A, B, C, D, E, F, G, H, I, J); gate!(A, B, C, D, E, F, G, H, I, J, K); gate!(A, B, C, D, E, F, G, H, I, J, K, L); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M, N); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q); gate!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R);
use ::Result; extern "C" { pub fn initCfgu() -> Result; pub fn exitCfgu() -> Result; pub fn CFGU_SecureInfoGetRegion(region: *mut u8) -> Result; pub fn CFGU_GenHashConsoleUnique(appIDSalt: u32, hash: *mut u64) -> Result; pub fn CFGU_GetRegionCanadaUSA(value: *mut u8) -> Result; pub fn CFGU_GetSystemModel(model: *mut u8) -> Result; pub fn CFGU_GetModelNintendo2DS(value: *mut u8) -> Result; pub fn CFGU_GetCountryCodeString(code: u16, string: *mut u16) -> Result; pub fn CFGU_GetCountryCodeID(string: u16, code: *mut u16) -> Result; pub fn CFGU_GetConfigInfoBlk2(size: u32, blkID: u32, outData: *mut u8) -> Result; pub fn CFGU_GetSystemLanguage(language: *mut u8) -> Result; }
use crate::lib::environment::Environment; use crate::lib::error::DfxResult; use crate::lib::identity::Identity; use crate::lib::provider::{create_agent_environment, get_network_descriptor}; use crate::lib::root_key::fetch_root_key_if_needed; use anyhow::anyhow; use clap::Clap; use ic_types::principal::Principal as CanisterId; use tokio::runtime::Runtime; /// Installs the wallet WASM to the provided canister id. #[derive(Clap)] pub struct DeployWalletOpts { /// The ID of the canister where the wallet WASM will be deployed. canister_id: String, } pub fn exec(env: &dyn Environment, opts: DeployWalletOpts, network: Option<String>) -> DfxResult { let agent_env = create_agent_environment(env, network.clone())?; let runtime = Runtime::new().expect("Unable to create a runtime"); runtime.block_on(async { fetch_root_key_if_needed(&agent_env).await })?; let identity_name = agent_env .get_selected_identity() .expect("No selected identity.") .to_string(); let network = get_network_descriptor(&agent_env, network)?; let canister_id = opts.canister_id; match CanisterId::from_text(&canister_id) { Ok(id) => { runtime.block_on(async { Identity::create_wallet(&agent_env, &network, &identity_name, Some(id)).await?; DfxResult::Ok(()) })?; } Err(err) => { anyhow!(format!( "Cannot convert {} to a valid canister id. Candid error: {}", canister_id, err )); } }; Ok(()) }
use std::fmt::Display; use chrono::{DateTime, Utc}; use isocountry::CountryCode; use isolanguage_1::LanguageCode; use itertools::Itertools; use serde::{Deserialize, Serialize}; use crate::{ AlbumSimplified, Category, Client, Error, FeaturedPlaylists, Market, Page, PlaylistSimplified, Recommendations, Response, }; /// Endpoint functions related to categories, featured playlists, recommendations, and new /// releases. #[derive(Debug, Clone, Copy)] pub struct Browse<'a>(pub &'a Client); impl Browse<'_> { /// Get information about a category. /// /// If no locale is given or Spotify does not support the given locale, then it will default to /// American English. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-category/). pub async fn get_category( self, name: &str, locale: Option<(LanguageCode, CountryCode)>, country: Option<CountryCode>, ) -> Result<Response<Category>, Error> { self.0 .send_json( self.0 .client .get(endpoint!("/v1/browse/categories/{}", name)) .query(&( locale.map(|locale| ("locale", format_language(locale))), country.map(|c| ("country", c.alpha2())), )), ) .await } /// Get information about several categories. /// /// You do not choose which categories to get. Limit must be in the range [1..50]. If no locale /// is given or Spotify does not support the given locale, then it will default to American /// English. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-categories/). pub async fn get_categories( self, limit: usize, offset: usize, locale: Option<(LanguageCode, CountryCode)>, country: Option<CountryCode>, ) -> Result<Response<Page<Category>>, Error> { #[derive(Deserialize)] struct CategoryPage { categories: Page<Category>, } Ok(self .0 .send_json::<CategoryPage>(self.0.client.get(endpoint!("/v1/browse/categories")).query( &( ("limit", limit.to_string()), ("offset", offset.to_string()), locale.map(|l| ("locale", format_language(l))), country.map(|c| ("country", c.alpha2())), ), )) .await? .map(|res| res.categories)) } /// Get a category's playlists. /// /// Limit must be in the range [1..50]. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-categorys-playlists/). pub async fn get_category_playlists( self, name: &str, limit: usize, offset: usize, country: Option<CountryCode>, ) -> Result<Response<Page<PlaylistSimplified>>, Error> { #[derive(Deserialize)] struct Playlists { playlists: Page<PlaylistSimplified>, } Ok(self .0 .send_json::<Playlists>( self.0 .client .get(endpoint!("/v1/browse/categories/{}/playlists", name)) .query(&( ("limit", limit.to_string()), ("offset", offset.to_string()), country.map(|c| ("country", c.alpha2())), )), ) .await? .map(|res| res.playlists)) } /// Get featured playlists. /// /// Limit must be in the range [1..50]. The locale will default to American English and the /// timestamp will default to the current UTC time. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-featured-playlists/). pub async fn get_featured_playlists( self, limit: usize, offset: usize, locale: Option<(LanguageCode, CountryCode)>, time: Option<DateTime<Utc>>, country: Option<CountryCode>, ) -> Result<Response<FeaturedPlaylists>, Error> { self.0 .send_json( self.0 .client .get(endpoint!("/v1/browse/featured-playlists")) .query(&( ("limit", limit.to_string()), ("offset", offset.to_string()), locale.map(|l| ("locale", format_language(l))), time.map(|t| ("timestamp", t.to_rfc3339())), country.map(|c| ("country", c.alpha2())), )), ) .await } /// Get new releases. /// /// Limit must be in the range [1..50]. The documentation claims to also return a message string, /// but in reality the API does not. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-list-new-releases/). pub async fn get_new_releases( self, limit: usize, offset: usize, country: Option<CountryCode>, ) -> Result<Response<Page<AlbumSimplified>>, Error> { #[derive(Deserialize)] struct NewReleases { albums: Page<AlbumSimplified>, } Ok(self .0 .send_json::<NewReleases>( self.0 .client .get(endpoint!("/v1/browse/new-releases")) .query(&( ("limit", limit.to_string()), ("offset", offset.to_string()), country.map(|c| ("country", c.alpha2())), )), ) .await? .map(|res| res.albums)) } /// Get recommendations. /// /// Up to 5 seed values may be provided, that can be distributed in `seed_artists`, /// `seed_genres` and `seed_tracks` in any way. Limit must be in the range [1..100] and this /// target number of tracks may not always be met. /// /// `attributes` must serialize to a string to string map or sequence of key-value tuples. See /// the reference for more info on this. /// /// [Reference](https://developer.spotify.com/documentation/web-api/reference/browse/get-recommendations/). pub async fn get_recommendations<AI: IntoIterator, GI: IntoIterator, TI: IntoIterator>( self, seed_artists: AI, seed_genres: GI, seed_tracks: TI, attributes: &impl Serialize, limit: usize, market: Option<Market>, ) -> Result<Response<Recommendations>, Error> where AI::Item: Display, GI::Item: Display, TI::Item: Display, { self.0 .send_json( self.0 .client .get(endpoint!("/v1/recommendations")) .query(&( ("seed_artists", seed_artists.into_iter().join(",")), ("seed_genres", seed_genres.into_iter().join(",")), ("seed_tracks", seed_tracks.into_iter().join(",")), ("limit", limit.to_string()), market.map(Market::query), )) .query(attributes), ) .await } } fn format_language(locale: (LanguageCode, CountryCode)) -> String { format!("{}_{}", locale.0.code(), locale.1.alpha2()) } #[cfg(test)] mod tests { use chrono::DateTime; use isocountry::CountryCode; use isolanguage_1::LanguageCode; use crate::endpoints::client; use crate::{Market, SeedType}; #[tokio::test] async fn test_get_category() { let category = client() .browse() .get_category( "pop", Some((LanguageCode::En, CountryCode::GBR)), Some(CountryCode::GBR), ) .await .unwrap() .data; assert_eq!(category.id, "pop"); assert_eq!(category.name, "Pop"); } #[tokio::test] async fn test_get_categories() { let categories = client() .browse() .get_categories(2, 0, None, None) .await .unwrap() .data; assert_eq!(categories.limit, 2); assert_eq!(categories.offset, 0); assert!(categories.items.len() <= 2); } #[tokio::test] async fn test_get_category_playlists() { let playlists = client() .browse() .get_category_playlists("chill", 1, 3, Some(CountryCode::GBR)) .await .unwrap() .data; assert_eq!(playlists.limit, 1); assert_eq!(playlists.offset, 3); assert!(playlists.items.len() <= 1); } #[tokio::test] async fn test_get_featured_playlists() { let playlists = client() .browse() .get_featured_playlists( 2, 0, None, Some( DateTime::parse_from_rfc3339("2015-05-02T19:25:47Z") .unwrap() .into(), ), None, ) .await .unwrap() .data .playlists; assert_eq!(playlists.limit, 2); assert_eq!(playlists.offset, 0); assert!(playlists.items.len() <= 2); } #[tokio::test] async fn test_get_new_releases() { let releases = client() .browse() .get_new_releases(1, 0, None) .await .unwrap() .data; assert_eq!(releases.limit, 1); assert_eq!(releases.offset, 0); assert!(releases.items.len() <= 1); } #[tokio::test] async fn test_get_recommendations() { let recommendations = client() .browse() .get_recommendations( &["unused"; 0], &["rock"], &["2RTkebdbPFyg4AMIzJZql1", "6fTt0CH2t0mdeB2N9XFG5r"], &[ ("max_acousticness", "0.8"), ("min_loudness", "-40"), ("target_popularity", "100"), ], 3, Some(Market::Country(CountryCode::GBR)), ) .await .unwrap() .data; assert!(recommendations.seeds.len() <= 3); assert_eq!( recommendations .seeds .iter() .filter(|seed| seed.entity_type == SeedType::Artist) .count(), 0 ); assert_eq!( recommendations .seeds .iter() .filter(|seed| seed.entity_type == SeedType::Genre) .count(), 1 ); assert_eq!( recommendations .seeds .iter() .filter(|seed| seed.entity_type == SeedType::Track) .count(), 2 ); assert!(recommendations.tracks.len() <= 3); } }
fn main() { // 浮動小数点 let x = 2.0; // f64 let y: f32 = 3.0; // f32 // 足し算 let sum = 5 + 10; // 引き算 let difference = 95.5 - 4.3; // 掛け算 let product = 4 * 30; // 割り算 let quotient = 56.7 / 32.2; // 余り let remainder = 43 % 5; // 複合型 let tup: (i32, f64, u8) = (100, 6.4, 1); let (a, b, c) = tup; println!("The value of a is {}", a); println!("The value of tup.1 is {}", tup.1); // 配列型 let l = [1, 2, 3, 4, 5]; let first = l[0]; let second = l[1]; println!("first is {}. second is {}", first, second); // 別関数の呼び出し another_func(5, 10); // 戻り値のある関数呼び出し let plus_one_val = plus_one(10); println!("plus_one_val is {}", plus_one_val); // if文 let condition = true; let number = if condition { 5 } else { 10 }; println!("The number is {}", number); // while文,for文 let list_2 = [10, 20, 30, 40, 50]; let mut index = 0; println!("=======while文で書いた場合======="); while index < 5 { // 値は{}です println!("the value is: {}", list_2[index]); index = index + 1; } println!("=======for文で書いた場合======="); for element in list_2.iter() { // 値は{}です println!("the value is: {}", element); } } fn another_func(x: i32, y: i64) { println!("x is {}, y is {}", x, y); } fn plus_one(x: i32) -> i32 { x + 1 }
mod create_table_response; mod delete_entity_response; mod delete_table_response; mod get_entity_response; mod insert_entity_response; mod list_tables_response; mod operation_on_entity_response; mod query_entity_response; mod submit_transaction_response; pub use create_table_response::CreateTableResponse; pub use delete_entity_response::DeleteEntityResponse; pub use delete_table_response::DeleteTableResponse; pub use get_entity_response::GetEntityResponse; pub use insert_entity_response::InsertEntityResponse; pub use list_tables_response::ListTablesResponse; pub use operation_on_entity_response::OperationOnEntityResponse; pub use query_entity_response::QueryEntityResponse; pub use submit_transaction_response::SubmitTransactionResponse;
use std::convert::Infallible; use std::net::SocketAddr; use std::sync::Arc; use tokio::sync::RwLock; use hyper::server::conn::AddrStream; use hyper::{Body, Request, Response, Server, Error}; use hyper::service::{service_fn, make_service_fn}; pub async fn run_proxy(local_port: u16, forward_uri_lock: Arc<RwLock<String>>) -> Result<(), Error> { let addr: SocketAddr = ([0, 0, 0, 0], local_port).into(); let svc_fn = make_service_fn(|conn: &AddrStream| { let remote_addr = conn.remote_addr(); let forward_uri_lock = forward_uri_lock.clone(); async move { let svc_fn = service_fn(move |req: Request<Body>| { let lock = forward_uri_lock.clone(); async move { // Don't lock longer than needed (like, for the whole request) let forward_uri = { lock.read().await }; let res = hyper_reverse_proxy::call(remote_addr.ip(), &forward_uri, req).await; Ok::<Response<Body>,Infallible>(res) } }); Ok::<_, Infallible>(svc_fn) } }); Server::bind(&addr) .serve(svc_fn) .await }
use sack::{SackType, SackBacker}; /// The most generic sack collision imaginable. Truly anything is possible /// with enough specialization pub trait Collider<'a, C1, C2, C3, C4, D1, D2, D3, D4, B1, B2, B3, B4, T1, T2, T3, T4> where B1: SackBacker, B2: SackBacker, B3: SackBacker, B4: SackBacker { fn collide(s1: &'a SackType<C1, D1, B1>, s2: &'a SackType<C2, D2, B2>) -> (&'a SackType<C3, D3, B3>, &'a SackType<C4, D4, B4>); }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// SyntheticsWarningType : User locator used. /// User locator used. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum SyntheticsWarningType { #[serde(rename = "user_locator")] USER_LOCATOR, } impl ToString for SyntheticsWarningType { fn to_string(&self) -> String { match self { Self::USER_LOCATOR => String::from("user_locator"), } } }
use crate::{ auth::{Authenticator, UserDetail}, server::{ chancomms::ProxyLoopSender, controlchan::{command::Command, error::ControlChanError, Reply}, ftpserver::options::{PassiveHost, SiteMd5}, session::SharedSession, ControlChanMsg, }, storage::{Metadata, StorageBackend}, }; use async_trait::async_trait; use std::{ops::Range, result::Result, sync::Arc}; use tokio::sync::mpsc::Sender; // Common interface for all handlers of `Commands` #[async_trait] pub(crate) trait CommandHandler<Storage, User>: Send + Sync + std::fmt::Debug where Storage: StorageBackend<User> + 'static, Storage::Metadata: Metadata, User: UserDetail, { async fn handle(&self, args: CommandContext<Storage, User>) -> Result<Reply, ControlChanError>; // Returns the name of the command handler fn name(&self) -> &str { std::any::type_name::<Self>() } } /// Represents arguments passed to a `CommandHandler` #[derive(Debug)] pub(crate) struct CommandContext<Storage, User> where Storage: StorageBackend<User> + 'static, Storage::Metadata: Metadata + Sync, User: UserDetail + 'static, { pub parsed_command: Command, pub session: SharedSession<Storage, User>, pub authenticator: Arc<dyn Authenticator<User>>, pub tls_configured: bool, pub passive_ports: Range<u16>, pub passive_host: PassiveHost, pub tx_control_chan: Sender<ControlChanMsg>, pub local_addr: std::net::SocketAddr, pub storage_features: u32, pub tx_proxyloop: Option<ProxyLoopSender<Storage, User>>, pub logger: slog::Logger, pub sitemd5: SiteMd5, }
use std::fmt::{Debug, Formatter, Result}; use std::ops::{Index, IndexMut}; pub struct Array<T: Clone>(Box<[T]>); impl<T: Clone> Array<T> { pub fn new(value: T, size: usize) -> Self { Array(Box::from(vec![value; size])) } pub fn len(&self) -> usize { self.0.len() } } impl<T: Clone> Index<usize> for Array<T> { type Output = T; fn index(&self, index: usize) -> &T { &self.0[index] } } impl<T: Clone> IndexMut<usize> for Array<T> { fn index_mut(&mut self, index: usize) -> &mut T { &mut self.0[index] } } impl<T: Clone + Debug> Debug for Array<T> { fn fmt(&self, f: &mut Formatter) -> Result { write!(f, "{:?}", self.0) } }
use crate::script::{Script, Event, Requirement, Argument, Offset}; use crate::script; use std::iter::Iterator; use std::slice; use std::f32; pub mod variable_ast; use variable_ast::VariableAst; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ScriptAst { pub block: Block, pub offset: i32, } impl ScriptAst { pub fn new(script: &Script) -> ScriptAst { let block = if let ProcessedBlock::Finished(events) = process_block(&mut script.events.iter().peekable()) { events } else { error!("A block in the script did not terminate."); Block { events: vec!() } }; ScriptAst { block, offset: script.offset } } } fn process_block(events: &mut std::iter::Peekable<slice::Iter<Event>>) -> ProcessedBlock { let mut event_asts = vec!(); while let Some(event) = events.next() { let args = &event.arguments; use crate::script::Argument::*; let event_ast = match (event.namespace, event.code, args.get(0), args.get(1), args.get(2)) { (0x00, 0x01, Some(&Scalar(v0)), None, None) => EventAst::SyncWait (v0), (0x00, 0x02, None, None, None) => EventAst::Nop, (0x00, 0x02, Some(&Scalar(v0)), None, None) => EventAst::AsyncWait (v0), (0x00, 0x04, Some(&Value(v0)), None, None) => { // Loop let iterations = if v0 == -1 { Iterations::Infinite } else { Iterations::Finite (v0) }; match process_block(events) { ProcessedBlock::EndForLoop (block) => EventAst::ForLoop (ForLoop { iterations, block }), _ => { error!("ForLoop did not terminate"); EventAst::Unknown (event.clone()) } } } (0x00, 0x05, None, None, None) => { // End loop return ProcessedBlock::EndForLoop (Block { events: event_asts }) } (0x00, 0x07, Some(&Offset(ref v0)), None, None) => EventAst::Subroutine (v0.clone()), (0x00, 0x07, Some(&Value (ref v0)), None, None) => EventAst::Subroutine (script::Offset { offset: *v0, origin: -1 }), (0x00, 0x08, None, None, None) => EventAst::Return, (0x00, 0x09, Some(&Offset(ref v0)), None, None) => EventAst::Goto (v0.clone()), (0x00, 0x09, Some(&Value (ref v0)), None, None) => EventAst::Goto (script::Offset { offset: *v0, origin: -1 }), (0x00, 0x0A, Some(&Requirement { ref ty, flip }), v1, v2) => { // If if let Some(test) = Expression::from_args(ty, flip, v1, v2, args.get(3)) { match process_block(events) { ProcessedBlock::EndIf { then_branch } => { EventAst::IfStatement (IfStatement { test, then_branch, else_branch: None }) } ProcessedBlock::EndIfAndElse { then_branch, else_branch } => { EventAst::IfStatement (IfStatement { test, then_branch, else_branch }) } _ => { error!("IfStatement did not terminate"); EventAst::Unknown (event.clone()) } } } else { EventAst::Unknown (event.clone()) } } (0x00, 0x0E, None, None, None) => { // Else match process_block(events) { ProcessedBlock::EndIf { then_branch: else_branch } => { let then_branch = Block { events: event_asts }; let else_branch = Some(Box::new(else_branch)); return ProcessedBlock::EndIfAndElse { then_branch, else_branch } } _ => { error!("IfStatement did not terminate"); EventAst::Unknown (event.clone()) } } } (0x00, 0x0B, Some(&Requirement { ref ty, flip }), v1, v2) => { // And // It is tempting to combine this event with the previous IfStatement event. // However that is a terrible idea, as an And/Or will alter the execution of the // current IfStatement even if other events have occured since the IfStatement. // // e.g. If an IfStatement branch is currently running and an `And` is ran that // means it would not have started running, execution of the block will end immediately. // All events before the `And` are still executed. // While all events after the `And` are not executed. // // I have tested this with Nop and FrameSpeedModifier events in between the IfStatement and And/Or. // It would probably also occur with an And/Or at a Goto/Subroutine destination if let Some(test) = Expression::from_args(ty, flip, v1, v2, args.get(3)) { EventAst::IfStatementAnd (test) } else { EventAst::Unknown (event.clone()) } } (0x00, 0x0C, Some(&Requirement { ref ty, flip }), v1, v2) => { // Or if let Some(test) = Expression::from_args(ty, flip, v1, v2, args.get(3)) { EventAst::IfStatementOr (test) } else { EventAst::Unknown (event.clone()) } } (0x00, 0x0D, Some(&Requirement { ref ty, flip }), v1, v2) => { // Else If if let Some(test) = Expression::from_args(ty, flip, v1, v2, args.get(3)) { let event = match process_block(events) { ProcessedBlock::EndIf { then_branch } => { EventAst::IfStatement (IfStatement { test, then_branch, else_branch: None }) } ProcessedBlock::EndIfAndElse { then_branch, else_branch } => { EventAst::IfStatement (IfStatement { test, then_branch, else_branch }) } _ => { error!("IfStatement did not terminate"); return ProcessedBlock::Finished (Block { events: event_asts }); } }; let else_branch = Some(Box::new(Block { events: vec!(event) })); let then_branch = Block { events: event_asts }; return ProcessedBlock::EndIfAndElse { then_branch, else_branch }; } else { EventAst::Unknown (event.clone()) } } (0x00, 0x0F, None, None, None) => { return ProcessedBlock::EndIf { then_branch: Block { events: event_asts } } } (0x00, 0x10, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::Switch (v0, v1), (0x00, 0x11, Some(&Value(v0)), None, None) => EventAst::Case (v0), (0x00, 0x11, None, None, None) => EventAst::DefaultCase, (0x00, 0x13, None, None, None) => EventAst::EndSwitch, (0x01, 0x01, None, None, None) => EventAst::LoopRest, (0x0D, 0x00, Some(&Value(v0)), Some(&Offset(ref v1)), None) => EventAst::CallEveryFrame { thread_id: v0, offset: v1.clone() }, (0x0D, 0x01, Some(&Value(v0)), None, None) => EventAst::RemoveCallEveryFrame { thread_id: v0 }, (0x0D, 0x05, Some(&Value(v0)), Some(&Offset(ref v1)), None) => EventAst::IndependentSubroutine { thread_id: v0, offset: v1.clone() }, (0x0D, 0x06, Some(&Value(v0)), None, None) => EventAst::RemoveIndependentSubroutine { thread_id: v0 }, (0x0D, 0x07, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::SetIndependentSubroutineThreadType { thread_id: v0, thread_type: v1 }, // change action (0x02, 0x00, Some(&Value(v0)), Some(&Value(v1)), Some(&Requirement { ref ty, flip })) => { if let Some(test) = Expression::from_args(ty, flip, args.get(3), args.get(4), args.get(5)) { EventAst::CreateInterrupt (Interrupt { interrupt_id: Some(v0), action: v1, test }) } else { EventAst::Unknown (event.clone()) } } (0x02, 0x01, Some(&Value(v0)), Some(&Requirement { ref ty, flip }), v2) => { if let Some(test) = Expression::from_args(ty, flip, v2, args.get(3), args.get(4)) { EventAst::CreateInterrupt (Interrupt { interrupt_id: None, action: v0, test }) } else { EventAst::Unknown (event.clone()) } } (0x02, 0x04, Some(&Requirement { ref ty, flip }), v1, v2) => { // It is tempting to combine this event with the previous CreateInterrupt event. // However that is a terrible idea as a InterruptAddRequirement will // modify the last CreateInterrupt regardless of any events in between. // I have tested this with Nop and FrameSpeedModifier events in between. // It would probably also occur with a InterruptAddRequirement in an IfStatement, at a Goto/Subroutine if let Some(test) = Expression::from_args(ty, flip, v1, v2, args.get(3)) { EventAst::PreviousInterruptAddRequirement { test } } else { EventAst::Unknown (event.clone()) } } (0x02, 0x05, Some(&Value(v0)), Some(&Value(v1)), Some(&Requirement { ref ty, flip })) => { if let Some(test) = Expression::from_args(ty, flip, args.get(3), args.get(4), args.get(5)) { EventAst::InterruptAddRequirement { interrupt_type: InterruptType::new(v0), interrupt_id: v1, test } } else { EventAst::Unknown (event.clone()) } } (0x02, 0x06, Some(&Value(v0)), None, None) => EventAst::EnableInterrupt (v0), (0x02, 0x08, Some(&Value(v0)), None, None) => EventAst::DisableInterrupt (v0), (0x02, 0x09, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ToggleInterrupt { interrupt_type: InterruptType::new(v0), interrupt_id: v1 }, (0x02, 0x0A, Some(&Value(v0)), None, None) => EventAst::EnableInterruptGroup (InterruptType::new(v0)), (0x02, 0x0B, Some(&Value(v0)), None, None) => EventAst::DisableInterruptGroup (InterruptType::new(v0)), (0x02, 0x0C, Some(&Value(v0)), None, None) => EventAst::ClearInterruptGroup (InterruptType::new(v0)), (0x64, 0x00, None, None, None) => EventAst::AllowInterrupts, (0x64, 0x01, None, None, None) => EventAst::DisallowInterrupts, (0x04, 0x00, Some(&Value(v0)), None, None) => EventAst::ChangeSubactionRestartFrame (v0), (0x04, 0x00, Some(&Value(v0)), Some(&Bool(v1)), None) => if v1 { EventAst::ChangeSubaction (v0) } else { EventAst::ChangeSubactionRestartFrame (v0) } // timing (0x04, 0x06, Some(&Scalar(v0)), None, None) => EventAst::SetAnimationFrame (v0), (0x04, 0x07, Some(&Scalar(v0)), None, None) => EventAst::FrameSpeedModifier { multiplier: v0, unk: 0 }, (0x04, 0x07, Some(&Scalar(v0)), Some(&Value(v1)), None) => EventAst::FrameSpeedModifier { multiplier: v0, unk: v1 }, (0x04, 0x14, Some(&Scalar(v0)), None, None) => EventAst::SetAnimationAndTimerFrame (v0), (0x0c, 0x23, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::TimeManipulation (v0, v1), // misc state (0x0e, 0x00, Some(&Value(v0)), None, None) => EventAst::SetAirGround (v0), (0x08, 0x00, Some(&Value(v0)), None, None) => EventAst::SetEdgeSlide (EdgeSlide::new(v0)), (0x05, 0x00, None, None, None) => EventAst::ReverseDirection, // hitboxes (0x06, 0x04, None, None, None) => EventAst::DeleteAllHitBoxes, (0x06, 0x00, Some(&Value(v0)), Some(v1), Some(&Value(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12)) { (Some(&Value(v3)), Some(&Value(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Scalar(v11)), Some(&Value(v12))) => { let damage = match v1 { Value(constant) => Some(FloatValue::Constant (*constant as f32)), Variable(ref variable) => Some(FloatValue::Variable (VariableAst::new(variable))), _ => None, }; if let Some(damage) = damage { let v12u = v12 as u32; EventAst::CreateHitBox (HitBoxArguments { bone_index: (v0 >> 16) as i16, set_id: (v0 >> 8) as u8, hitbox_id: v0 as u8, damage, trajectory: v2, wdsk: (v3 >> 16) as i16, kbg: v3 as i16, shield_damage: (v4 >> 16) as i16, bkb: v4 as i16, size: v5, x_offset: v6, y_offset: v7, z_offset: v8, tripping_rate: v9, hitlag_mult: v10, sdi_mult: v11, effect: HitBoxEffect::new(v12 & 0b0000_0000_0000_0000_0000_0000_0001_1111), unk1: (v12 & 0b0000_0000_0000_0000_0000_0000_0010_0000) != 0, sound_level: ((v12 & 0b0000_0000_0000_0000_0000_0000_1100_0000) >> 6) as u8, unk2: ((v12 & 0b0000_0000_0000_0000_0000_0001_0000_0000) != 0), sound: HitBoxSound::new((v12 & 0b0000_0000_0000_0000_0011_1110_0000_0000) >> 9), unk3: ((v12 & 0b0000_0000_0000_0000_1100_0000_0000_0000) >> 14) as u8, ground: (v12 & 0b0000_0000_0000_0001_0000_0000_0000_0000) != 0, aerial: (v12 & 0b0000_0000_0000_0010_0000_0000_0000_0000) != 0, unk4: ((v12 & 0b0000_0000_0011_1100_0000_0000_0000_0000) >> 18) as u8, sse_type: HitBoxSseType::new((v12 & 0b0000_0111_1100_0000_0000_0000_0000_0000) >> 22), clang: (v12 & 0b0000_1000_0000_0000_0000_0000_0000_0000) != 0, unk5: (v12 & 0b0001_0000_0000_0000_0000_0000_0000_0000) != 0, direct: (v12 & 0b0010_0000_0000_0000_0000_0000_0000_0000) != 0, unk6: ((v12u & 0b1100_0000_0000_0000_0000_0000_0000_0000) >> 30) as u8, }) } else { EventAst::Unknown (event.clone()) } } _ => EventAst::Unknown (event.clone()) } } (0x06, 0x2B, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12)) { (Some(&Value(v3)), Some(&Value(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Scalar(v11)), Some(&Value(v12))) => { let v12u = v12 as u32; EventAst::ThrownHitBox (HitBoxArguments { bone_index: (v0 >> 16) as i16, set_id: (v0 >> 8) as u8, hitbox_id: v0 as u8, damage: FloatValue::Constant (v1 as f32), trajectory: v2, wdsk: (v3 >> 16) as i16, kbg: v3 as i16, shield_damage: (v4 >> 16) as i16, bkb: v4 as i16, size: v5, x_offset: v6, y_offset: v7, z_offset: v8, tripping_rate: v9, hitlag_mult: v10, sdi_mult: v11, effect: HitBoxEffect::new(v12 & 0b0000_0000_0000_0000_0000_0000_0001_1111), unk1: (v12 & 0b0000_0000_0000_0000_0000_0000_0010_0000) != 0, sound_level: ((v12 & 0b0000_0000_0000_0000_0000_0000_1100_0000) >> 6) as u8, unk2: ((v12 & 0b0000_0000_0000_0000_0000_0001_0000_0000) != 0), sound: HitBoxSound::new((v12 & 0b0000_0000_0000_0000_0011_1110_0000_0000) >> 9), unk3: ((v12 & 0b0000_0000_0000_0000_1100_0000_0000_0000) >> 14) as u8, ground: (v12 & 0b0000_0000_0000_0001_0000_0000_0000_0000) != 0, aerial: (v12 & 0b0000_0000_0000_0010_0000_0000_0000_0000) != 0, unk4: ((v12 & 0b0000_0000_0011_1100_0000_0000_0000_0000) >> 18) as u8, sse_type: HitBoxSseType::new((v12 & 0b0000_0111_1100_0000_0000_0000_0000_0000) >> 22), clang: (v12 & 0b0000_1000_0000_0000_0000_0000_0000_0000) != 0, unk5: (v12 & 0b0001_0000_0000_0000_0000_0000_0000_0000) != 0, direct: (v12 & 0b0010_0000_0000_0000_0000_0000_0000_0000) != 0, unk6: ((v12u & 0b1100_0000_0000_0000_0000_0000_0000_0000) >> 30) as u8, }) } _ => EventAst::Unknown (event.clone()) } } (0x06, 0x15, Some(&Value(v0)), Some(v1), Some(&Value(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12), args.get(13), args.get(14)) { (Some(&Value(v3)), Some(&Value(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Scalar(v11)), Some(&Value(v12)), Some(&Value(v13)), Some(&Value(v14))) => { let damage = match v1 { Value(constant) => Some(FloatValue::Constant (*constant as f32)), Variable(ref variable) => Some(FloatValue::Variable (VariableAst::new(variable))), _ => None, }; if let Some(damage) = damage { let v12u = v12 as u32; let v14u = v14 as u32; EventAst::CreateSpecialHitBox (SpecialHitBoxArguments { hitbox_args: HitBoxArguments { bone_index: (v0 >> 16) as i16, set_id: (v0 >> 8) as u8, hitbox_id: v0 as u8, damage, trajectory: v2, wdsk: (v3 >> 16) as i16, kbg: v3 as i16, shield_damage: (v4 >> 16) as i16, bkb: v4 as i16, size: v5, x_offset: v6, y_offset: v7, z_offset: v8, tripping_rate: v9, hitlag_mult: v10, sdi_mult: v11, effect: HitBoxEffect::new(v12 & 0b0000_0000_0000_0000_0000_0000_0001_1111), unk1: (v12 & 0b0000_0000_0000_0000_0000_0000_0010_0000) != 0, sound_level: ((v12 & 0b0000_0000_0000_0000_0000_0000_1100_0000) >> 6) as u8, unk2: ((v12 & 0b0000_0000_0000_0000_0000_0001_0000_0000) != 0), sound: HitBoxSound::new((v12 & 0b0000_0000_0000_0000_0011_1110_0000_0000) >> 6), unk3: ((v12 & 0b0000_0000_0000_0000_1100_0000_0000_0000) >> 14) as u8, ground: (v12 & 0b0000_0000_0000_0001_0000_0000_0000_0000) != 0, aerial: (v12 & 0b0000_0000_0000_0010_0000_0000_0000_0000) != 0, unk4: ((v12 & 0b0000_0000_0011_1100_0000_0000_0000_0000) >> 18) as u8, sse_type: HitBoxSseType::new((v12 & 0b0000_0111_1100_0000_0000_0000_0000_0000) >> 22), clang: (v12 & 0b0000_1000_0000_0000_0000_0000_0000_0000) != 0, unk5: (v12 & 0b0001_0000_0000_0000_0000_0000_0000_0000) != 0, direct: (v12 & 0b0010_0000_0000_0000_0000_0000_0000_0000) != 0, unk6: ((v12u & 0b1100_0000_0000_0000_0000_0000_0000_0000) >> 30) as u8, }, rehit_rate: v13, angle_flipping: AngleFlip::new(v14 & 0b0000_0000_0000_0000_0000_0000_0000_0111), unk1: (v14 & 0b0000_0000_0000_0000_0000_0000_0000_1000) != 0, stretches_to_bone: (v14 & 0b0000_0000_0000_0000_0000_0000_0001_0000) != 0, unk2: (v14 & 0b0000_0000_0000_0000_0000_0000_0010_0000) != 0, can_hit1: (v14 & 0b0000_0000_0000_0000_0000_0000_0100_0000) != 0, can_hit2: (v14 & 0b0000_0000_0000_0000_0000_0000_1000_0000) != 0, can_hit3: (v14 & 0b0000_0000_0000_0000_0000_0001_0000_0000) != 0, can_hit4: (v14 & 0b0000_0000_0000_0000_0000_0010_0000_0000) != 0, can_hit5: (v14 & 0b0000_0000_0000_0000_0000_0100_0000_0000) != 0, can_hit6: (v14 & 0b0000_0000_0000_0000_0000_1000_0000_0000) != 0, can_hit7: (v14 & 0b0000_0000_0000_0000_0001_0000_0000_0000) != 0, can_hit8: (v14 & 0b0000_0000_0000_0000_0010_0000_0000_0000) != 0, can_hit9: (v14 & 0b0000_0000_0000_0000_0100_0000_0000_0000) != 0, can_hit10: (v14 & 0b0000_0000_0000_0000_1000_0000_0000_0000) != 0, can_hit11: (v14 & 0b0000_0000_0000_0001_0000_0000_0000_0000) != 0, can_hit12: (v14 & 0b0000_0000_0000_0010_0000_0000_0000_0000) != 0, can_hit13: (v14 & 0b0000_0000_0000_0100_0000_0000_0000_0000) != 0, enabled: (v14 & 0b0000_0000_0000_1000_0000_0000_0000_0000) != 0, unk3: ((v14 & 0b0000_0000_0011_0000_0000_0000_0000_0000) >> 20) as u8, can_be_shielded: (v14 & 0b0000_0000_0100_0000_0000_0000_0000_0000) != 0, can_be_reflected: (v14 & 0b0000_0000_1000_0000_0000_0000_0000_0000) != 0, can_be_absorbed: (v14 & 0b0000_0001_0000_0000_0000_0000_0000_0000) != 0, unk4: ((v14 & 0b0000_0110_0000_0000_0000_0000_0000_0000) >> 25) as u8, remain_grabbed: (v14 & 0b0000_1000_0000_0000_0000_0000_0000_0000) != 0, ignore_invincibility: (v14 & 0b0001_0000_0000_0000_0000_0000_0000_0000) != 0, freeze_frame_disable: (v14 & 0b0010_0000_0000_0000_0000_0000_0000_0000) != 0, unk5: (v14 & 0b0100_0000_0000_0000_0000_0000_0000_0000) != 0, flinchless: (v14u & 0b1000_0000_0000_0000_0000_0000_0000_0000) != 0, }) } else { EventAst::Unknown (event.clone()) } } _ => EventAst::Unknown (event.clone()) } } (0x06, 0x17, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { EventAst::DefensiveCollision { ty: DefensiveCollisionType::new(v0), unk: v1, direction: DefensiveCollisionDirection::new(v2), } } (0x06, 0x1B, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4))) = (args.get(3), args.get(4)) { EventAst::MoveHitBox (MoveHitBox { hitbox_id: v0, new_bone: v1, new_x_offset: v2, new_y_offset: v3, new_z_offset: v4, }) } else { EventAst::Unknown (event.clone()) } } (0x06, 0x01, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ChangeHitBoxDamage { hitbox_id: v0, new_damage: v1 }, (0x06, 0x02, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ChangeHitBoxSize { hitbox_id: v0, new_size: v1 }, (0x06, 0x03, Some(&Value(v0)), None, None) => EventAst::DeleteHitBox (v0), (0x06, 0x0A, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Value(v6)), Some(&Value(v7))) = (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7)) { let unk = if let Some(&Value(value)) = args.get(8) { Some(value) } else { None }; assert!(v0 >= 0 && v0 <= 0xFF, "grab boxes shouldn't include any extra data with the hitbox_id"); EventAst::CreateGrabBox(GrabBoxArguments { hitbox_id: v0, bone_index: v1, size: v2, x_offset: v3, y_offset: v4, z_offset: v5, set_action: v6, target: GrabTarget::new(v7), unk }) } else { EventAst::Unknown (event.clone()) } } (0x06, 0x0C, Some(&Value(v0)), None, None) => EventAst::DeleteGrabBox (v0), (0x06, 0x0D, None, None, None) => EventAst::DeleteAllGrabBoxes, (0x06, 0x0E, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12), args.get(13), args.get(14), args.get(15), args.get(16)) { (Some(&Value(v3)), Some(&Value(v4)), Some(&Value(v5)), Some(&Value(v6)), Some(&Value(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Value(v11)), Some(&Value(v12)), Some(&Value(v13)), Some(&Bool(v14)), Some(&Bool(v15)), Some(&Value(v16))) => { EventAst::SpecifyThrow (SpecifyThrow { throw_use: ThrowUse::new(v0), bone: v1, damage: v2, trajectory: v3, kbg: v4, wdsk: v5, bkb: v6, effect: HitBoxEffect::new(v7), unk0: v8, unk1: v9, unk2: v10, unk3: v11, sfx: HitBoxSound::new(v12), grab_target: GrabTarget::new(v13), unk4: v14, unk5: v15, i_frames: v16, }) } _ => EventAst::Unknown(event.clone()) } } (0x06, 0x0F, Some(&Value(v0)), Some(&Value(v1)), Some(&Variable(ref v2))) => { if let (Some(&Variable(ref v3)), Some(&Variable(ref v4))) = (args.get(3), args.get(4)) { EventAst::ApplyThrow (ApplyThrow { unk0: v0, bone: v1, unk1: VariableAst::new(v2), unk2: VariableAst::new(v3), unk3: VariableAst::new(v4), }) } else { EventAst::Unknown(event.clone()) } } (0x06, 0x14, Some(&Value(v0)), Some(v1), None) => { let add_damage = match v1 { Value(constant) => Some(FloatValue::Constant (*constant as f32)), Variable(ref variable) => Some(FloatValue::Variable (VariableAst::new(variable))), _ => None, }; if let Some(add_damage) = add_damage { EventAst::AddHitBoxDamage { hitbox_id: v0, add_damage } } else { EventAst::Unknown(event.clone()) } } (0x06, 0x14, a, b, c, ) => panic!("{:?} {:?} {:?}", a , b, c), // hurtboxes (0x06, 0x05, Some(&Value(v0)), None, None) => EventAst::ChangeHurtBoxStateAll { state: HurtBoxState::new(v0) }, (0x06, 0x08, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ChangeHurtBoxStateSpecific { bone: v0, state: HurtBoxState::new(v1) }, (0x06, 0x06, Some(&Value(v0)), None, None) => { if v0 != 0 { error!("Unsual UnchangeHurtBoxStateSpecific argument: All known cases of this event have an argument of 0") } EventAst::UnchangeHurtBoxStateSpecific } // controller (0x07, 0x00, None, None, None) => EventAst::ControllerClearBuffer, (0x07, 0x01, None, None, None) => EventAst::ControllerUnk01, (0x07, 0x02, None, None, None) => EventAst::ControllerUnk02, (0x07, 0x06, Some(&Bool(v0)), None, None) => EventAst::ControllerUnk06 (v0), (0x07, 0x06, None, None, None) => EventAst::ControllerUnk0C, (0x07, 0x07, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::Rumble { unk1: v0, unk2: v1 }, (0x07, 0x0B, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::RumbleLoop { unk1: v0, unk2: v1 }, // misc (0x18, 0x00, Some(&Value(v0)), None, None) => EventAst::SlopeContourStand { leg_bone_parent: v0 }, (0x18, 0x01, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::SlopeContourFull { hip_n_or_top_n: v0, trans_bone: v1 }, (0x10, 0x00, Some(&Value(v0)), None, None) => EventAst::GenerateArticle { article_id: v0, subaction_only: true }, // TODO: subaction_only? (0x10, 0x00, Some(&Value(v0)), Some(&Bool(v1)), None) => EventAst::GenerateArticle { article_id: v0, subaction_only: v1 }, (0x10, 0x01, Some(&Value(v0)), None, None) => EventAst::ArticleEvent (v0), (0x10, 0x02, Some(&Value(v0)), None, None) => EventAst::ArticleAnimation (v0), (0x10, 0x03, Some(&Value(v0)), None, None) => EventAst::ArticleRemove (v0), (0x10, 0x05, Some(&Value(v0)), Some(&Bool(v1)), None) => EventAst::ArticleVisibility { article_id: v0, visibility: v1 }, (0x0C, 0x06, None, None, None) => EventAst::FinalSmashEnter, (0x0C, 0x07, None, None, None) => EventAst::FinalSmashExit, (0x0C, 0x08, None, None, None) => EventAst::TerminateSelf, (0x0C, 0x09, Some(&Value(v0)), None, None) => EventAst::LedgeGrabEnable (LedgeGrabEnable::new(v0)), (0x0C, 0x25, Some(&Bool(v0)), None, None) => EventAst::TagDisplay (v0), (0x1E, 0x00, Some(&Value(v0)), Some(&Scalar(v1)), None) => EventAst::Armor { armor_type: ArmorType::new(v0), tolerance: v1 }, (0x1E, 0x03, Some(&Scalar(v0)), None, None) => EventAst::AddDamage (v0), // posture (0x05, 0x01, None, None, None) => EventAst::Posture (0x01), (0x05, 0x02, None, None, None) => EventAst::Posture (0x02), (0x05, 0x03, None, None, None) => EventAst::Posture (0x03), (0x05, 0x04, None, None, None) => EventAst::Posture (0x04), (0x05, 0x07, None, None, None) => EventAst::Posture (0x07), (0x05, 0x0D, None, None, None) => EventAst::Posture (0x0D), // movement (0x0E, 0x08, Some(&Scalar(v0)), Some(&Scalar(v1)), Some(&Value(v2))) => { if let Some(&Value(v3)) = args.get(3) { EventAst::SetOrAddVelocity (SetOrAddVelocity { x_vel: v0, y_vel: v1, x_set: v2 != 0, y_set: v3 != 0, }) } else { EventAst::Unknown (event.clone()) } } (0x0E, 0x08, Some(&Scalar(v0)), Some(&Scalar(v1)), None) => EventAst::SetVelocity { x_vel: v0, y_vel: v1 }, (0x0E, 0x01, Some(&Scalar(v0)), Some(&Scalar(v1)), None) => EventAst::AddVelocity { x_vel: FloatValue::Constant(v0), y_vel: FloatValue::Constant(v1) }, (0x0E, 0x01, Some(&Variable(ref v0)), Some(&Scalar(v1)), None) => EventAst::AddVelocity { x_vel: FloatValue::Variable(VariableAst::new(v0)), y_vel: FloatValue::Constant(v1) }, (0x0E, 0x01, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::AddVelocity { x_vel: FloatValue::Constant(v0), y_vel: FloatValue::Variable(VariableAst::new(v1)) }, (0x0E, 0x01, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::AddVelocity { x_vel: FloatValue::Variable(VariableAst::new(v0)), y_vel: FloatValue::Variable(VariableAst::new(v1)) }, (0x0E, 0x06, Some(&Value(v0)), None, None) => EventAst::DisableMovement (DisableMovement::new(v0)), (0x0E, 0x07, Some(&Value(v0)), None, None) => EventAst::DisableMovement2 (DisableMovement::new(v0)), (0x0E, 0x02, Some(&Value(v0)), None, None) => EventAst::ResetVerticalVelocityAndAcceleration (v0 == 1), (0x17, 0x00, None, None, None) => EventAst::NormalizePhysics, // sound (0x0A, 0x00, Some(&Value(v0)), None, None) => EventAst::SoundEffect1 (v0), (0x0A, 0x01, Some(&Value(v0)), None, None) => EventAst::SoundEffect2 (v0), (0x0A, 0x02, Some(&Value(v0)), None, None) => EventAst::SoundEffectTransient (v0), (0x0A, 0x03, Some(&Value(v0)), None, None) => EventAst::SoundEffectStop (v0), (0x0A, 0x05, Some(&Value(v0)), None, None) => EventAst::SoundEffectVictory (v0), (0x0A, 0x07, Some(&Value(v0)), None, None) => EventAst::SoundEffectUnk (v0), (0x0A, 0x09, Some(&Value(v0)), None, None) => EventAst::SoundEffectOther1 (v0), (0x0A, 0x0A, Some(&Value(v0)), None, None) => EventAst::SoundEffectOther2 (v0), (0x0C, 0x0B, None, None, None) => EventAst::SoundVoiceLow, (0x0C, 0x19, None, None, None) => EventAst::SoundVoiceDamage, (0x0C, 0x1D, None, None, None) => EventAst::SoundVoiceOttotto, (0x0C, 0x1F, None, None, None) => EventAst::SoundVoiceEating, // Modify variables (0x12, 0x00, Some(&Value(v0)), Some(&Variable(ref v1)), None) => EventAst::IntVariableSet { value: v0, variable: VariableAst::new(v1) }, (0x12, 0x01, Some(&Value(v0)), Some(&Variable(ref v1)), None) => EventAst::IntVariableAdd { value: v0, variable: VariableAst::new(v1) }, (0x12, 0x02, Some(&Value(v0)), Some(&Variable(ref v1)), None) => EventAst::IntVariableSubtract { value: v0, variable: VariableAst::new(v1) }, (0x12, 0x03, Some(&Variable(ref v0)), None, None) => EventAst::IntVariableIncrement { variable: VariableAst::new(v0) }, (0x12, 0x04, Some(&Variable(ref v0)), None, None) => EventAst::IntVariableDecrement { variable: VariableAst::new(v0) }, (0x12, 0x06, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableSet { value: FloatValue::Constant(v0), variable: VariableAst::new(v1) }, (0x12, 0x06, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableSet { value: FloatValue::Variable(VariableAst::new(v0)), variable: VariableAst::new(v1) }, (0x12, 0x07, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableAdd { value: FloatValue::Constant(v0), variable: VariableAst::new(v1) }, (0x12, 0x07, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableAdd { value: FloatValue::Variable(VariableAst::new(v0)), variable: VariableAst::new(v1) }, (0x12, 0x08, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableSubtract { value: FloatValue::Constant(v0), variable: VariableAst::new(v1) }, (0x12, 0x08, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableSubtract { value: FloatValue::Variable(VariableAst::new(v0)), variable: VariableAst::new(v1) }, (0x12, 0x0F, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableMultiply { value: FloatValue::Constant(v0), variable: VariableAst::new(v1) }, (0x12, 0x0F, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableMultiply { value: FloatValue::Variable(VariableAst::new(v0)), variable: VariableAst::new(v1) }, (0x12, 0x10, Some(&Scalar(v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableDivide { value: FloatValue::Constant(v0), variable: VariableAst::new(v1) }, (0x12, 0x10, Some(&Variable(ref v0)), Some(&Variable(ref v1)), None) => EventAst::FloatVariableDivide { value: FloatValue::Variable(VariableAst::new(v0)), variable: VariableAst::new(v1) }, (0x12, 0x0A, Some(&Variable(ref v0)), None, None) => EventAst::BoolVariableSetTrue { variable: VariableAst::new(v0) }, (0x12, 0x0B, Some(&Variable(ref v0)), None, None) => EventAst::BoolVariableSetFalse { variable: VariableAst::new(v0) }, // graphics (0x0B, 0x00, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ModelChanger { reference: 0, switch_index: v0, bone_group_index: v1 }, (0x0B, 0x01, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ModelChanger { reference: 1, switch_index: v0, bone_group_index: v1 }, (0x11, 0x1A, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) | (0x11, 0x1B, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12), args.get(13), args.get(14), args.get(15)) { (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Scalar(v11)), Some(&Scalar(v12)), Some(&Scalar(v13)), Some(&Scalar(v14)), Some(&Bool(v15))) => { EventAst::GraphicEffect (GraphicEffect { graphic: v0, bone: v1, x_offset: v4, y_offset: v3, z_offset: v2, x_rotation: v7, y_rotation: v6, z_rotation: v5, scale: v8, random_x_offset: v11, random_y_offset: v10, random_z_offset: v9, random_x_rotation: v14, random_y_rotation: v13, random_z_rotation: v12, terminate_with_animation: v15 }) } _ => EventAst::Unknown (event.clone()) } } (0x11, 0x00, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Scalar(v10)), Some(&Scalar(v11)), Some(&Scalar(v12)), Some(&Scalar(v13)), Some(&Scalar(v14)), Some(&Bool(v15))) = (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12), args.get(13), args.get(14), args.get(15)) { EventAst::ExternalGraphicEffect (ExternalGraphicEffect { file: (v0 >> 16) as i16, graphic: v0 as i16, bone: v1, x_offset: v4, y_offset: v3, z_offset: v2, x_rotation: v7, y_rotation: v6, z_rotation: v5, scale: v8, randomize: Some(ExternalGraphicEffectRandomize { random_x_offset: v11, random_y_offset: v10, random_z_offset: v9, random_x_rotation: v14, random_y_rotation: v13, random_z_rotation: v12, }), terminate_with_animation: v15, }) } else { EventAst::Unknown (event.clone()) } } (0x11, 0x01, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) | (0x11, 0x02, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Bool(v9))) = (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9)) { EventAst::ExternalGraphicEffect (ExternalGraphicEffect { file: (v0 >> 16) as i16, graphic: v0 as i16, bone: v1, x_offset: v4, y_offset: v3, z_offset: v2, x_rotation: v7, y_rotation: v6, z_rotation: v5, scale: v8, terminate_with_animation: v9, randomize: None, }) } else { EventAst::Unknown (event.clone()) } } (0x11, 0x17, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6)) { (Some(&Value(v3)), Some(&Value(v4)), Some(&Value(v5)), Some(&Value(v6))) => { EventAst::LimitedScreenTint (LimitedScreenTint { transition_in_time: v0, red: v1, green: v2, blue: v3, alpha: v4, frame_count: v5, transition_out_time: v6, }) } (Some(&Value(v3)), Some(&Value(v4)), Some(&Value(v5)), None) => { EventAst::UnlimitedScreenTint (UnlimitedScreenTint { tint_id: v0, transition_in_time: v1, red: v2, green: v3, blue: v4, alpha: v5, }) } _ => EventAst::Unknown (event.clone()) } } (0x11, 0x18, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::EndUnlimitedScreenTint { tint_id: v0, transition_out_time: v1 }, (0x11, 0x03, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Value(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Scalar(v9)), Some(&Bool(v10)), Some(&Value(v11)), Some(&Value(v12)), Some(&Scalar(v13)), Some(&Scalar(v14)), Some(&Scalar(v15)), Some(&Scalar(v16)), Some(&Scalar(v17)), Some(&Scalar(v18)), Some(&Scalar(v19))) = (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9), args.get(10), args.get(11), args.get(12), args.get(13), args.get(14), args.get(15), args.get(16), args.get(17), args.get(18), args.get(19)) { EventAst::SwordGlow (SwordGlow { color: v0, blur_length: v1, point1_bone: v2, point1_x_offset: v3, point1_y_offset: v4, point1_z_offset: v5, point2_bone: v6, point2_x_offset: v7, point2_y_offset: v8, point2_z_offset: v9, delete_after_subaction: v10, graphic_id: v11, bone_id: v12, x_offset: v13, y_offset: v14, z_offset: v15, x_rotation: v16, y_rotation: v17, z_rotation: v18, glow_length: v19, }) } else { EventAst::Unknown (event.clone()) } } (0x11, 0x05, Some(&Value(v0)), None, None) => EventAst::DeleteSwordGlow { fade_time: v0 }, (0x14, 0x07, Some(&Value(v0)), Some(&Scalar(v1)), Some(&Scalar(v2))) => { match (args.get(3), args.get(4), args.get(5), args.get(6), args.get(7), args.get(8), args.get(9)) { (Some(&Scalar(v3)), Some(&Scalar(v4)), Some(&Scalar(v5)), Some(&Scalar(v6)), Some(&Scalar(v7)), Some(&Scalar(v8)), Some(&Value(v9))) => { EventAst::AestheticWindEffect (AestheticWindEffect { unk1: v0, unk2: v1, stength: v2, speed: v3, size: v4, unk3: v5, unk4: v6, unk5: v7, unk6: v8, unk7: v8, unk8: v9, }) } _ => EventAst::Unknown (event.clone()) } } (0x14, 0x04, Some(&Value(v0)), None, None) => EventAst::EndAestheticWindEffect { unk: v0 }, (0x1A, 0x00, Some(&Value(v0)), None, None) => EventAst::ScreenShake { magnitude: v0 }, (0x1A, 0x04, Some(&Value(v0)), Some(&Value(v1)), Some(&Scalar(v2))) => { if let (Some(&Scalar(v3)), Some(&Scalar(v4))) = (args.get(3), args.get(4)) { EventAst::CameraCloseup (CameraCloseup { zoom_time: v0, unk: v1, distance: v2, x_angle: v3, y_angle: v4, }) } else { EventAst::Unknown (event.clone()) } } (0x1A, 0x08, None, None, None) => EventAst::CameraNormal, (0x21, 0x00, None, None, None) => EventAst::RemoveFlashEffect, (0x21, 0x01, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { if let Some(&Value(v3)) = args.get(3) { EventAst::FlashEffectOverlay { red: v0, green: v1, blue: v2, alpha: v3 } } else { EventAst::Unknown (event.clone()) } } (0x21, 0x02, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { if let (Some(&Value(v3)), Some(&Value(v4))) = (args.get(3), args.get(4)) { EventAst::SetColorOfFlashEffectOverlay { transition_time: v0, red: v1, green: v2, blue: v3, alpha: v4 } } else { EventAst::Unknown (event.clone()) } } (0x21, 0x05, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { if let (Some(&Value(v3)), Some(&Scalar(v4)), Some(&Scalar(v5))) = (args.get(3), args.get(4), args.get(5)) { EventAst::FlashEffectLight { red: v0, green: v1, blue: v2, alpha: v3, light_source_x: v4, light_source_y: v5 } } else { EventAst::Unknown (event.clone()) } } (0x21, 0x07, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => { if let (Some(&Value(v3)), Some(&Value(v4))) = (args.get(3), args.get(4)) { EventAst::SetColorOfFlashEffectLight { transition_time: v0, red: v1, green: v2, blue: v3, alpha: v4 } } else { EventAst::Unknown (event.clone()) } } // Items (0x1F, 0x00, Some(&Value(v0)), None, None) => EventAst::ItemPickup { unk1: v0, unk2: None, unk3: None, unk4: None }, (0x1F, 0x00, Some(&Value(v0)), Some(&Value(v1)), None) => EventAst::ItemPickup { unk1: v0, unk2: Some(v1), unk3: None, unk4: None }, (0x1F, 0x00, Some(&Value(v0)), Some(&Value(v1)), Some(&Value(v2))) => if let Some(&Value(v3)) = args.get(3) { EventAst::ItemPickup { unk1: v0, unk2: Some(v1), unk3: Some(v2), unk4: Some(v3) } } else { EventAst::Unknown (event.clone()) }, (0x1F, 0x01, Some(&Variable(ref v0)), Some(&Variable(ref v1)), Some(&Variable(ref v2))) => if let (Some(&Variable(ref v3)), Some(&Variable(ref v4))) = (args.get(3), args.get(4)) { EventAst::ItemThrow { unk1: VariableAst::new(v0), unk2: VariableAst::new(v1), unk3: VariableAst::new(v2), unk4: Some(VariableAst::new(v3)), unk5: Some(VariableAst::new(v4)) } } else { EventAst::Unknown (event.clone()) }, (0x1F, 0x0E, Some(&Variable(ref v0)), Some(&Variable(ref v1)), Some(&Variable(ref v2))) => EventAst::ItemThrow { unk1: VariableAst::new(v0), unk2: VariableAst::new(v1), unk3: VariableAst::new(v2), unk4: None, unk5: None }, (0x1F, 0x01, Some(&Scalar(v0)), Some(&Scalar(v1)), Some(&Variable(ref v2))) => EventAst::ItemThrow2 { unk1: v0, unk2: v1, unk3: VariableAst::new(v2) }, (0x1F, 0x02, None, None, None) => EventAst::ItemDrop, (0x1F, 0x03, Some(&Value(v0)), None, None) => EventAst::ItemConsume { unk: v0 }, (0x1F, 0x04, Some(&Value(v0)), Some(&Scalar(v1)), None) => EventAst::ItemSetProperty { unk1: v0, unk2: v1 }, (0x1F, 0x05, None, None, None) => EventAst::FireWeapon, (0x1F, 0x06, None, None, None) => EventAst::FireProjectile, (0x1F, 0x07, Some(&Value(v0)), None, None) => EventAst::Item1F { unk: v0 }, (0x1F, 0x08, Some(&Value(v0)), None, None) => EventAst::ItemCreate { unk: v0 }, (0x1F, 0x09, Some(&Bool(v0)), None, None) => EventAst::ItemVisibility (v0), (0x1F, 0x0A, None, None, None) => EventAst::ItemDelete, (0x1F, 0x0C, Some(&Value(v0)), None, None) => EventAst::BeamSwordTrail { unk: v0 }, _ => EventAst::Unknown (event.clone()) }; // Brawlbox has some extra parameter types it uses to handle some special cases: // * HitBoxFlags // * Value2Half // * ValueGFX // I dont use them because they are just subtypes of Argument::Value // Instead I handle them in the ast parser // These are the rules brawlbox uses for determining if an argument is one of these special types //let argument = if (event_id == 0x06000D00 || event_id == 0x06150F00 || event_id == 0x062B0D00) && i == 12 { // Argument::HitBoxFlags (data) //} else if (event_id == 0x06000D00 || event_id == 0x05150F00 || event_id == 0x062B0D00) && (i == 0 || i == 3 || i == 4) { // Argument::Value2Half (data) //} else if (event_id == 0x11150300 || event_id == 0x11001000 || event_id == 0x11020A00) && i == 0 { // Argument::ValueGFX (data) // TODO: Delete each comment when actually implemented event_asts.push(event_ast); } ProcessedBlock::Finished(Block { events: event_asts }) } impl Expression { fn from_args(requirement: &Requirement, flip: bool, v1: Option<&Argument>, v2: Option<&Argument>, v3: Option<&Argument>) -> Option<Expression> { let test = match (v1, v2, v3) { (None, None, None) => { Expression::Nullary(requirement.clone()) } (Some(v1), None, None) => { let value = Box::new(match v1 { &Argument::Scalar(v1) => Expression::Scalar(v1), &Argument::Variable(ref v1) => Expression::Variable(VariableAst::new(v1)), &Argument::Value(v1) => Expression::Value(v1), _ => { error!("Unhandled expression case: value: {:?}", v1); return None; } }); Expression::Unary (UnaryExpression { requirement: requirement.clone(), value }) } (Some(v1), Some(&Argument::Value(v2)), Some(v3)) => { let left = Box::new(match v1 { &Argument::Scalar(v1) => Expression::Scalar(v1), &Argument::Variable(ref v1) => Expression::Variable(VariableAst::new(v1)), &Argument::Value(v1) => Expression::Value(v1), _ => { error!("Unhandled expression case: left"); return None; } }); let right = Box::new(match v3 { &Argument::Scalar(v3) => Expression::Scalar(v3), &Argument::Variable(ref v3) => Expression::Variable(VariableAst::new(v3)), &Argument::Value(v3) => Expression::Value(v3), _ => { error!("Unhandled expression case: right"); return None; } }); match requirement { script::Requirement::Comparison => Expression::Binary (BinaryExpression { left, right, operator: ComparisonOperator::from_arg(v2) }), // Seems to be just modders using this as a quick hack. script::Requirement::Always => Expression::Nullary(requirement.clone()), _ => { error!("Unhandled expression case: comparison v0: {:?} v1: {:?} v2: {:?}: v3: {:?}", requirement, v1, v2, v3); return None; } } } (v1, v2, v3) => { error!("Unhandled expression case: {:?} {:?} {:?}", v1, v2, v3); return None; } }; Some(if flip { Expression::Not (Box::new(test)) } else { test }) } } enum ProcessedBlock { Finished (Block), EndForLoop (Block), EndIf { then_branch: Block }, EndIfAndElse { then_branch: Block, else_branch: Option<Box<Block>> }, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum EventAst { ///Pause the current flow of events until the set time is reached. Synchronous timers count down when they are reached in the code. SyncWait (f32), /// Does nothing. Nop, /// Pause the current flow of events until the set time is reached. Asynchronous Timers start counting from the beginning of the animation. AsyncWait (f32), /// Execute the block of code N times. ForLoop (ForLoop), /// Enter the event routine specified and return after ending. Subroutine (Offset), /// Return from a Subroutine. Return, /// Goto the event location specified and execute. Goto (Offset), /// An expression decides which block of code to execute. IfStatement (IfStatement), /// An `And` to an If statement. /// If the expression is false then execution of all events other than IfStatementOr are skipped. /// Execution can be resumed by an IfStatementOr /// /// Has no effect outside of an IfStatement /// Havent tested if it would affect execution when called within a subroutine, but I would assume it is. IfStatementAnd (Expression), /// An `Or` to an If statement. /// If the expression is true then execution of all events is re-enabled /// Execution can be stopped by an IfStatementAnd /// /// Has no effect outside of an IfStatement /// Havent tested if it would affect execution when called within a subroutine, but I would assume it is. IfStatementOr (Expression), /// Begin a multiple case Switch block. Switch (i32, i32), /// Handler for if the variable in the switch statement equals the specified value. Case (i32), /// The case chosen if none of the others are executed. DefaultCase, /// End a Switch block. EndSwitch, /// Briefly return execution back to the system to prevent crashes during infinite loops. LoopRest, /// Runs a subroutine once per frame for the current action. CallEveryFrame { thread_id: i32, offset: Offset }, /// Stops the execution of a loop created with CallEveryFrame RemoveCallEveryFrame { thread_id: i32 }, /// Runs a subroutine once, the subroutine will persist even after the end of the action. /// Requires the Independent Subroutines code by Mawootad. IndependentSubroutine { thread_id: i32, offset: Offset }, /// Stops the execution of a loop created with IndependentSubroutine /// Requires the Independent Subroutines code by Mawootad. RemoveIndependentSubroutine { thread_id: i32 }, /// Sets the thread_id to a custom thread type /// Requires the Independent Subroutines code by Mawootad. SetIndependentSubroutineThreadType { thread_id: i32, thread_type: i32 }, /// Enables the given interrupt ID on any interrupt type. EnableInterrupt (i32), /// Disables the given interrupt ID on any interrupt type. DisableInterrupt (i32), /// Invert the given interrupt ID assosciated with the given interrupt type. ToggleInterrupt { interrupt_type: InterruptType, interrupt_id: i32 }, /// Enables all interrupts associated with the given interrupt type. EnableInterruptGroup (InterruptType), /// Disables all interrupts associated with the given interrupt type. DisableInterruptGroup (InterruptType), /// Remove all actions currently assosciated with an interrupt type. ClearInterruptGroup (InterruptType), /// An interrupt with the given interrupt ID is assosciated with the interrupt type of that action. /// The interrupt type used, seems to be hardcoded to the action somehow. /// The current action will change upon test being true. (the requirement does not have to be met at the time this ID is executed - it can be used anytime after execution.) CreateInterrupt (Interrupt), /// Add an additional requirement to the preceeding CreateInterrupt statement. /// All requirements on the interrupt must be true for the interrupt to occur. PreviousInterruptAddRequirement { test: Expression }, /// Add an additonal requirement to the specified interrupt type and interrupt id. /// All requirements on the interrupt must be true for the interrupt to occur. InterruptAddRequirement { interrupt_type: InterruptType, interrupt_id: i32, test: Expression }, /// Allow the current action to be interrupted by another action. AllowInterrupts, /// Disallow the current action to be interrupted by another action. DisallowInterrupts, /// Change the current subaction. ChangeSubaction (i32), /// Change the current subaction, restarting the frame count. ChangeSubactionRestartFrame (i32), /// Changes the current frame of the animation. Does not change the frame of the subaction (i.e. timers and such are unaffected). SetAnimationFrame (f32), /// Dictates the frame speed of the subaction. Example: setting to 2 makes the animation and timers occur twice as fast. FrameSpeedModifier { multiplier: f32, unk: i32 }, /// Changes the current frame of the animation and the current frame of timers. SetAnimationAndTimerFrame (f32), /// Change the speed of time for various parts of the environment. TimeManipulation (i32, i32), /// Specify whether the character is on or off the ground. SetAirGround (i32), /// Determines whether or not the character will slide off the edge. SetEdgeSlide (EdgeSlide), /// Reverse the direction the character is facing after the animation ends. ReverseDirection, /// Create a hitbox with the specified parameters. CreateHitBox (HitBoxArguments), // brawlbox calls this "Offensive Collision" /// Create a hitbox with the specified parameters on the character to be thrown. The hitbox can not hit the throwing character or the thrown character. /// TODO: I actually dont understand this at all, it seems characters without this still have hitboxes regardless of who throws who. ThrownHitBox (HitBoxArguments), /// Remove all currently present hitboxes. DeleteAllHitBoxes, // brawlbox calls this "Terminate Collisions" /// Create a hitbox with the even more parameters. CreateSpecialHitBox (SpecialHitBoxArguments), // brawlbox calls this "Special Offensive Collision" /// Enables a defensive collision box e.g. links shield DefensiveCollision { ty: DefensiveCollisionType, unk: i32, direction: DefensiveCollisionDirection }, /// Repositions an already-existing hitbox. MoveHitBox (MoveHitBox), /// Changes a specific hitbox's damage to the new amount. Only guaranteed to work on a HitBox ChangeHitBoxDamage { hitbox_id: i32, new_damage: i32 }, /// Changes a specific hitbox's size to the new amount. Only guaranteed to work on a HitBox ChangeHitBoxSize { hitbox_id: i32, new_size: i32 }, /// Deletes a hitbox of the specified ID. Only guaranteed to work on a HitBox DeleteHitBox (i32), /// Generate a grabbox with the specified parameters. CreateGrabBox (GrabBoxArguments), /// Deletes the grabbox with the specified ID. DeleteGrabBox (i32), /// Remove all currently present grabboxes DeleteAllGrabBoxes, /// Specify the throw SpecifyThrow (SpecifyThrow), /// Apply the previously specified throw ApplyThrow (ApplyThrow), /// Adds the specified amount of damage to the specified hitbox. AddHitBoxDamage { hitbox_id: i32, add_damage: FloatValue }, /// Set the state of all of the characters hurtboxes. ChangeHurtBoxStateAll { state: HurtBoxState }, /// Sets the state of a characters specific hurtbox. /// /// Setting HurtBoxState::Invincible state with this command is broken. /// It either has no effect or sets the state to Normal. (I havent confirmed which) ChangeHurtBoxStateSpecific { bone: i32, state: HurtBoxState }, /// Sets the state of a characters specific hurtbox to the global value. UnchangeHurtBoxStateSpecific, /// Possibly clears the controller buffer. ControllerClearBuffer, /// Unknown controller event ControllerUnk01, /// Unknown controller event ControllerUnk02, /// Unknown controller event ControllerUnk06 (bool), /// Unknown controller event ControllerUnk0C, /// Undefined. Affects the rumble feature of the controller. Rumble { unk1: i32, unk2: i32 }, /// Creates a rumble loop on the controller. RumbleLoop { unk1: i32, unk2: i32 }, /// Moves the character's feet if on sloped ground. SlopeContourStand { leg_bone_parent: i32 }, /// Moves entire character to match sloped ground. SlopeContourFull { hip_n_or_top_n: i32, trans_bone: i32 }, /// Generate a pre-made prop effect from the prop library. GenerateArticle { article_id: i32, subaction_only: bool }, /// Makes the article preform an animation when set to 1. ArticleEvent (i32), /// Article Animation. ArticleAnimation (i32), /// Removes an article. ArticleRemove (i32), /// Makes an article visible or invisible. ArticleVisibility { article_id: i32, visibility: bool }, /// Allows use of Final Smash locked articles, variables, etc. Highly unstable. FinalSmashEnter, /// Exit Final Smash state FinalSmashExit, /// Used by certain article instances to remove themselves. TerminateSelf, /// Allow or disallow grabbing ledges during the current subaction. LedgeGrabEnable (LedgeGrabEnable), /// Disables or enables tag display for the current subaction. TagDisplay (bool), /// Begins super armor or heavy armor. Set parameters to None and 0 to end the armor. Armor { armor_type: ArmorType, tolerance: f32 }, /// Adds the specified amount of damage to the character's current percentage. AddDamage (f32), /// ??? Posture (i32), /// Will either set or add the velocity amounts depending on the set_ flags. SetOrAddVelocity (SetOrAddVelocity), /// Sets the character's current velocity. SetVelocity { x_vel: f32, y_vel: f32 }, /// Adds to the character's current velocity. AddVelocity { x_vel: FloatValue, y_vel: FloatValue }, /// Does not allow the specified type of movement. DisableMovement (DisableMovement), /// This must be set to the same value as DisableMovement to work. DisableMovement2 (DisableMovement), /// When set to 1, vertical speed and acceleration are reset back to 0. ResetVerticalVelocityAndAcceleration (bool), /// Returns to normal physics. NormalizePhysics, /// Play a specified sound effect. SoundEffect1 (i32), /// Play a specified sound effect. SoundEffect2 (i32), /// Play a specified sound effect. The sound effect ends with the animation. SoundEffectTransient (i32), /// Stops the specified sound effect immediately. SoundEffectStop (i32), /// Play a specified sound effect. Is used during victory poses. SoundEffectVictory (i32), /// Unknown. SoundEffectUnk (i32), /// Play a specified sound effect. SoundEffectOther1 (i32), /// Play a specified sound effect. SoundEffectOther2 (i32), /// Play a random low voice clip. SoundVoiceLow, /// Play a random damage voice clip. SoundVoiceDamage, /// Play the Ottotto voice clip. SoundVoiceOttotto, /// Play a random eating voice clip. SoundVoiceEating, /// Set a specified value to an int variable. IntVariableSet { value: i32, variable: VariableAst }, /// Add a specified value to an int variable. IntVariableAdd { value: i32, variable: VariableAst }, /// Subtract a specified value from an int variable. IntVariableSubtract { value: i32, variable: VariableAst }, /// Increment an int variable. IntVariableIncrement { variable: VariableAst }, /// Decrement an int variable. IntVariableDecrement { variable: VariableAst }, /// Set a specified value to a float variable. FloatVariableSet { value: FloatValue, variable: VariableAst }, /// Add a specified value to a float variable. FloatVariableAdd { value: FloatValue, variable: VariableAst }, /// Subtract a specified value from a float variable. FloatVariableSubtract { value: FloatValue, variable: VariableAst }, /// Multiply a specified value on a float variable. FloatVariableMultiply { value: FloatValue, variable: VariableAst }, /// Divide a specified value on a float variable. FloatVariableDivide { value: FloatValue, variable: VariableAst }, /// Set a bool variable to true. BoolVariableSetTrue { variable: VariableAst }, /// Set a bool variable to false. BoolVariableSetFalse { variable: VariableAst }, /// Changes the visibility of certain bones attached to objects. Uses bone groups and switches set in the specified Reference of the Model Visibility section. ModelChanger { reference: u8, switch_index: i32, bone_group_index: i32 }, /// Generate a generic graphical effect with the specified parameters. GraphicEffect (GraphicEffect), /// Generate a graphical effect from an external file. (usually the Ef_ file) ExternalGraphicEffect (ExternalGraphicEffect), /// Tint the screen to the specified color. LimitedScreenTint (LimitedScreenTint), /// Tint the screen to the specified color until terminated by `EndUnlimitedScreenTint`. UnlimitedScreenTint (UnlimitedScreenTint), /// Ends an unlimited screen tint with the specified ID. EndUnlimitedScreenTint { tint_id: i32, transition_out_time: i32 }, /// Creates glow of sword. Only usable when the proper effects are loaded by their respective characters. SwordGlow (SwordGlow), /// Remove the sword flow in the specified time DeleteSwordGlow { fade_time: i32 }, /// Moves nearby movable model parts (capes, hair, etc) with a wind specified by the parameters. AestheticWindEffect (AestheticWindEffect), /// Ends the wind effect spawned by the "Aesthetic Wind Effect" event EndAestheticWindEffect { unk: i32 }, /// Shakes the screen. ScreenShake { magnitude: i32 }, /// Zoom the camera on the character. CameraCloseup (CameraCloseup), /// Return the camera to its normal settings. CameraNormal, /// Remove all currently active flash effects RemoveFlashEffect, /// Generate a flash overlay effect over the characer with the specified colors and opacity. /// Replaces any currently active flash effects. FlashEffectOverlay { red: i32, green: i32, blue: i32, alpha: i32 }, /// Change the color of the current flash overlay effect. SetColorOfFlashEffectOverlay { transition_time: i32, red: i32, green: i32, blue: i32, alpha: i32 }, /// Generate a flash lighting effect over the character with the specified colors, opacity and angle. /// Replaces any currently active flash effects. FlashEffectLight { red: i32, green: i32, blue: i32, alpha: i32, light_source_x: f32, light_source_y: f32 }, /// Changes the color of the current flash light effect. SetColorOfFlashEffectLight { transition_time: i32, red: i32, green: i32, blue: i32, alpha: i32 }, /// Cause the character to receive the closest item in range. ItemPickup { unk1: i32, unk2: Option<i32>, unk3: Option<i32>, unk4: Option<i32> }, /// Cause the character to throw the currently held item. ItemThrow { unk1: VariableAst, unk2: VariableAst, unk3: VariableAst, unk4: Option<VariableAst>, unk5: Option<VariableAst> }, /// Cause the character to throw the currently held item. ItemThrow2 { unk1: f32, unk2: f32, unk3: VariableAst }, /// Cause the character to drop any currently held item. ItemDrop, /// Cause the character to consume the currently held item. ItemConsume { unk: i32 }, /// Set a property of the currently held item. ItemSetProperty { unk1: i32, unk2: f32 }, /// Fires a shot from the currently held item. FireWeapon, /// Fires a projectile. FireProjectile, /// Used when firing a cracker launcher. Item1F { unk: i32 }, /// Create an item in the characters hand. ItemCreate { unk: i32 }, /// Determines the visibility of the currently held item. ItemVisibility (bool), /// Deletes the currently held item. ItemDelete, /// Creates a beam sword trail. Probably has more uses among battering weapons. BeamSwordTrail { unk: i32 }, /// Unknown event. Unknown (Event) } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum FloatValue { Variable (VariableAst), Constant (f32), } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Block { pub events: Vec<EventAst> } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ForLoop { pub iterations: Iterations, pub block: Block, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum Iterations { Finite (i32), Infinite } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct IfStatement { pub test: Expression, pub then_branch: Block, pub else_branch: Option<Box<Block>> } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum Expression { Nullary (Requirement), Unary (UnaryExpression), Binary (BinaryExpression), Not (Box<Expression>), Variable (VariableAst), Value (i32), Scalar (f32), } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct BinaryExpression { pub left: Box<Expression>, pub right: Box<Expression>, pub operator: ComparisonOperator } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct UnaryExpression { pub requirement: Requirement, pub value: Box<Expression>, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum ComparisonOperator { LessThan, LessThanOrEqual, Equal, NotEqual, GreaterThanOrEqual, GreaterThan, And, Or, UnknownArg (i32) } impl ComparisonOperator { fn from_arg(value: i32) -> ComparisonOperator { match value { 0 => ComparisonOperator::LessThan, 1 => ComparisonOperator::LessThanOrEqual, 2 => ComparisonOperator::Equal, 3 => ComparisonOperator::NotEqual, 4 => ComparisonOperator::GreaterThanOrEqual, 5 => ComparisonOperator::GreaterThan, v => ComparisonOperator::UnknownArg (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum EdgeSlide { SlideOff, StayOn, Airbourne, Unknown (i32) } impl EdgeSlide { fn new(value: i32) -> EdgeSlide { match value { 0 => EdgeSlide::SlideOff, 1 => EdgeSlide::StayOn, 5 => EdgeSlide::Airbourne, v => EdgeSlide::Unknown (v) } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum HurtBoxState { Normal, Invincible, IntangibleFlashing, IntangibleNoFlashing, IntangibleQuickFlashing, Unknown (i32) } impl HurtBoxState { fn new(value: i32) -> HurtBoxState { match value { 0 => HurtBoxState::Normal, 1 => HurtBoxState::Invincible, 2 => HurtBoxState::IntangibleFlashing, 3 => HurtBoxState::IntangibleNoFlashing, 4 => HurtBoxState::IntangibleQuickFlashing, v => HurtBoxState::Unknown (v) } } pub fn is_normal(&self) -> bool { match self { HurtBoxState::Normal => true, _ => false } } pub fn is_invincible(&self) -> bool { match self { HurtBoxState::Invincible => true, _ => false } } pub fn is_intangible(&self) -> bool { match self { HurtBoxState::IntangibleFlashing => true, HurtBoxState::IntangibleNoFlashing => true, HurtBoxState::IntangibleQuickFlashing => true, _ => false } } } /// The angle specified in the hitbox specifies the angle used when the fighter faces to the right. /// Then one of these modifiers is applied to it to determine when the angle should be flipped across the Y axis #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum AngleFlip { /// The direction from the attacker to the defender. /// flip = attacker_x < defender_x AttackerPosition, /// The direction the attacker is moving. /// flip = if attacker_speed_x == 0.0 { /// attacker_x < defender_x /// } else { /// attacker_speed_x < 0.0 /// } MovementDir, /// Direction is always to the left. /// flip = true LeftDir, /// The direction the attacker is currently facing. /// flip = attacker_direction == left AttackerDir, /// The opposite direction to where the attacker is currently facing. /// flip = attacker_direction == right AttackerDirReverse, /// The direction from the hitbox to the defender. /// flip = hitbox_x < defender_x HitboxPosition, FaceZaxis, Unknown (i32) } impl AngleFlip { fn new(value: i32) -> AngleFlip { match value { 0 => AngleFlip::AttackerPosition, 1 => AngleFlip::MovementDir, 2 => AngleFlip::LeftDir, 3 => AngleFlip::AttackerDir, 4 => AngleFlip::AttackerDirReverse, 5 => AngleFlip::HitboxPosition, 6 | 7 => AngleFlip::FaceZaxis, v => AngleFlip::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum HitBoxEffect { Normal, None, Slash, Electric, Freezing, Flame, Coin, Reverse, Trip, Sleep, //Unk1, Bury, Stun, //Unk2, Flower, //Unk3, //Unk4, Grass, Water, Darkness, Paralyze, Aura, Plunge, Down, Flinchless, Unknown (i32) } impl HitBoxEffect { fn new(value: i32) -> HitBoxEffect { match value { 0 => HitBoxEffect::Normal, 1 => HitBoxEffect::None, 2 => HitBoxEffect::Slash, 3 => HitBoxEffect::Electric, 4 => HitBoxEffect::Freezing, 5 => HitBoxEffect::Flame, 6 => HitBoxEffect::Coin, 7 => HitBoxEffect::Reverse, 8 => HitBoxEffect::Trip, 9 => HitBoxEffect::Sleep, //10 => HitBoxEffect::Unk1, 11 => HitBoxEffect::Bury, 12 => HitBoxEffect::Stun, //13 => HitBoxEffect::Unk2, 14 => HitBoxEffect::Flower, //15 => HitBoxEffect::Unk3, //16 => HitBoxEffect::Unk4, 17 => HitBoxEffect::Grass, 18 => HitBoxEffect::Water, 19 => HitBoxEffect::Darkness, 20 => HitBoxEffect::Paralyze, 21 => HitBoxEffect::Aura, 22 => HitBoxEffect::Plunge, 23 => HitBoxEffect::Down, 24 => HitBoxEffect::Flinchless, v => HitBoxEffect::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum HitBoxSound { Unique, Punch, Kick, Slash, Coin, HomeRunBat, Paper, Shock, Burn, Splash, Explosion, Thud, Slam, Thwomp, MagicZap, Shell, Slap, Pan, Club, Racket, Aura, NessBat, Unknown (i32) } impl HitBoxSound { fn new(value: i32) -> HitBoxSound { match value { 0 => HitBoxSound::Unique, 1 => HitBoxSound::Punch, 2 => HitBoxSound::Kick, 3 => HitBoxSound::Slash, 4 => HitBoxSound::Coin, 5 => HitBoxSound::HomeRunBat, 6 => HitBoxSound::Paper, 7 => HitBoxSound::Shock, 8 => HitBoxSound::Burn, 9 => HitBoxSound::Splash, 11 => HitBoxSound::Explosion, 13 => HitBoxSound::Thud, 14 => HitBoxSound::Slam, 15 => HitBoxSound::Thwomp, 16 => HitBoxSound::MagicZap, 17 => HitBoxSound::Shell, 18 => HitBoxSound::Slap, 19 => HitBoxSound::Pan, 20 => HitBoxSound::Club, 21 => HitBoxSound::Racket, 22 => HitBoxSound::Aura, 27 => HitBoxSound::NessBat, _ => HitBoxSound::Unknown (value) } } } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum HitBoxSseType { None, Head, Body, Butt, Hand, Elbow, Foot, Knee, Throwing, Weapon, Sword, Hammer, Explosive, Spin, Bite, Magic, Pk, Bow, NessBat, Umbrella, Pimin, Water, Whip, Tail, Energy, Unknown (i32) } impl HitBoxSseType { fn new(value: i32) -> HitBoxSseType { match value { 0 => HitBoxSseType::None, 1 => HitBoxSseType::Head, 2 => HitBoxSseType::Body, 3 => HitBoxSseType::Butt, 4 => HitBoxSseType::Hand, 5 => HitBoxSseType::Elbow, 6 => HitBoxSseType::Foot, 7 => HitBoxSseType::Knee, 8 => HitBoxSseType::Throwing, 9 => HitBoxSseType::Weapon, 10 => HitBoxSseType::Sword, 11 => HitBoxSseType::Hammer, 12 => HitBoxSseType::Explosive, 13 => HitBoxSseType::Spin, 14 => HitBoxSseType::Bite, 15 => HitBoxSseType::Magic, 16 => HitBoxSseType::Pk, 17 => HitBoxSseType::Bow, //18 => HitBoxSseType::Unk, 19 => HitBoxSseType::NessBat, 20 => HitBoxSseType::Umbrella, 21 => HitBoxSseType::Pimin, 22 => HitBoxSseType::Water, 23 => HitBoxSseType::Whip, 24 => HitBoxSseType::Tail, 25 => HitBoxSseType::Energy, _ => HitBoxSseType::Unknown (value) } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct HitBoxArguments { pub bone_index: i16, pub hitbox_id: u8, pub set_id: u8, pub damage: FloatValue, pub trajectory: i32, pub wdsk: i16, pub kbg: i16, pub shield_damage: i16, pub bkb: i16, pub size: f32, pub x_offset: f32, pub y_offset: f32, pub z_offset: f32, pub tripping_rate: f32, pub hitlag_mult: f32, pub sdi_mult: f32, pub effect: HitBoxEffect, pub unk1: bool, pub sound_level: u8, pub unk2: bool, pub sound: HitBoxSound, pub unk3: u8, pub ground: bool, pub aerial: bool, pub unk4: u8, pub sse_type: HitBoxSseType, pub clang: bool, pub unk5: bool, pub direct: bool, pub unk6: u8, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SpecialHitBoxArguments { pub hitbox_args: HitBoxArguments, pub rehit_rate: i32, pub angle_flipping: AngleFlip, pub unk1: bool, pub stretches_to_bone: bool, pub unk2: bool, /// Can hit fighters, waddle dee/doo and pikmin pub can_hit1: bool, /// Can hit SSE enemies pub can_hit2: bool, /// Unk pub can_hit3: bool, /// Can hit ROB Gyro, Snake grenade and Mr Saturn pub can_hit4: bool, /// Unk pub can_hit5: bool, /// Unk pub can_hit6: bool, /// Can hit Stage hurtboxes not including wall/ceiling/floor pub can_hit7: bool, /// Can hit wall/ceiling/floor pub can_hit8: bool, /// Link & Toon Link Bomb, Bob-omb pub can_hit9: bool, /// Unk pub can_hit10: bool, /// Link & Toon Link Bomb, Bob-omb, ROB Gyro, Snake grenade, Bob-omb, Mr Saturn, All Stage related hurtboxes? pub can_hit11: bool, /// Waddle Dee/Doo pikmin pub can_hit12: bool, /// Unk pub can_hit13: bool, pub enabled: bool, pub unk3: u8, pub can_be_shielded: bool, pub can_be_reflected: bool, pub can_be_absorbed: bool, pub unk4: u8, pub remain_grabbed: bool, pub ignore_invincibility: bool, pub freeze_frame_disable: bool, pub unk5: bool, pub flinchless: bool, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DefensiveCollisionType { Block, Reflect, Unknown (i32), } impl DefensiveCollisionType { fn new(value: i32) -> Self { match value { 2 => DefensiveCollisionType::Block, 3 => DefensiveCollisionType::Reflect, v => DefensiveCollisionType::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DefensiveCollisionDirection { Front, FrontAndBack, Unknown (i32), } impl DefensiveCollisionDirection { fn new(value: i32) -> Self { match value { 1 => DefensiveCollisionDirection::Front, 2 => DefensiveCollisionDirection::FrontAndBack, v => DefensiveCollisionDirection::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct MoveHitBox { pub hitbox_id: i32, pub new_bone: i32, pub new_x_offset: f32, pub new_y_offset: f32, pub new_z_offset: f32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct GrabBoxArguments { pub hitbox_id: i32, pub bone_index: i32, pub size: f32, pub x_offset: f32, pub y_offset: f32, pub z_offset: f32, pub set_action: i32, pub target: GrabTarget, pub unk: Option<i32>, } #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] pub enum GrabTarget { None, GroundedOnly, AerialOnly, AerialAndGrounded, Unknown (i32), } impl GrabTarget { fn new(value: i32) -> GrabTarget { match value { 0 => GrabTarget::None, 1 => GrabTarget::GroundedOnly, 2 => GrabTarget::AerialOnly, 3 => GrabTarget::AerialAndGrounded, v => GrabTarget::Unknown (v), } } pub fn grounded(&self) -> bool { match self { GrabTarget::GroundedOnly => true, GrabTarget::AerialAndGrounded => true, _ => false, } } pub fn aerial(&self) -> bool { match self { GrabTarget::AerialOnly => true, GrabTarget::AerialAndGrounded => true, _ => false, } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SpecifyThrow { /// ID of throw data. Seemingly, a "0" indicates this is the throw data, while a "1" indicates this is used if the opponent escapes during the throw. "2" has also been seen (by Light Arrow)." pub throw_use: ThrowUse, pub bone: i32, pub damage: i32, pub trajectory: i32, pub kbg: i32, pub wdsk: i32, pub bkb: i32, pub effect: HitBoxEffect, pub unk0: f32, pub unk1: f32, pub unk2: f32, pub unk3: i32, pub sfx: HitBoxSound, pub grab_target: GrabTarget, pub unk4: bool, pub unk5: bool, pub i_frames: i32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum ThrowUse { Throw, GrabInterrupt, Unknown (i32), } impl ThrowUse { fn new(value: i32) -> ThrowUse { match value { 0 => ThrowUse::Throw, 1 => ThrowUse::GrabInterrupt, v => ThrowUse::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ApplyThrow { pub unk0: i32, pub bone: i32, pub unk1: VariableAst, pub unk2: VariableAst, pub unk3: VariableAst, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum LedgeGrabEnable { Disable, EnableInFront, EnableInFrontAndBehind, Unknown (i32), } impl LedgeGrabEnable { fn new(value: i32) -> LedgeGrabEnable { match value { 0 => LedgeGrabEnable::Disable, 1 => LedgeGrabEnable::EnableInFront, 2 => LedgeGrabEnable::EnableInFrontAndBehind, v => LedgeGrabEnable::Unknown (v), } } pub fn enabled(&self) -> bool { match self { LedgeGrabEnable::EnableInFront => true, LedgeGrabEnable::EnableInFrontAndBehind => true, LedgeGrabEnable::Disable => false, LedgeGrabEnable::Unknown (_) => false, } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum ArmorType { None, SuperArmor, HeavyArmorKnockbackBased, HeavyArmorDamageBased, Unknown (i32), } impl ArmorType { fn new(value: i32) -> ArmorType { match value { 0 => ArmorType::None, 1 => ArmorType::SuperArmor, 2 => ArmorType::HeavyArmorKnockbackBased, 3 => ArmorType::HeavyArmorDamageBased, v => ArmorType::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SetOrAddVelocity { pub x_vel: f32, pub y_vel: f32, pub x_set: bool, pub y_set: bool, } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum DisableMovement { Enable, DisableVertical, DisableHorizontal, Unknown (i32), } impl DisableMovement { fn new(value: i32) -> DisableMovement { match value { 0 => DisableMovement::Enable, 1 => DisableMovement::DisableVertical, 2 => DisableMovement::DisableHorizontal, v => DisableMovement::Unknown (v), } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct GraphicEffect { pub graphic: i32, pub bone: i32, pub x_offset: f32, pub y_offset: f32, pub z_offset: f32, pub x_rotation: f32, pub y_rotation: f32, pub z_rotation: f32, pub scale: f32, pub random_x_offset: f32, pub random_y_offset: f32, pub random_z_offset: f32, pub random_x_rotation: f32, pub random_y_rotation: f32, pub random_z_rotation: f32, pub terminate_with_animation: bool } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExternalGraphicEffect { pub file: i16, pub graphic: i16, pub bone: i32, pub x_offset: f32, pub y_offset: f32, pub z_offset: f32, pub x_rotation: f32, pub y_rotation: f32, pub z_rotation: f32, pub scale: f32, pub randomize: Option<ExternalGraphicEffectRandomize>, pub terminate_with_animation: bool, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct ExternalGraphicEffectRandomize { pub random_x_offset: f32, pub random_y_offset: f32, pub random_z_offset: f32, pub random_x_rotation: f32, pub random_y_rotation: f32, pub random_z_rotation: f32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct LimitedScreenTint { pub transition_in_time: i32, pub red: i32, pub green: i32, pub blue: i32, pub alpha: i32, pub frame_count: i32, pub transition_out_time: i32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct UnlimitedScreenTint { pub tint_id: i32, pub transition_in_time: i32, pub red: i32, pub green: i32, pub blue: i32, pub alpha: i32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct SwordGlow { pub color: i32, pub blur_length: i32, pub point1_bone: i32, pub point1_x_offset: f32, pub point1_y_offset: f32, pub point1_z_offset: f32, pub point2_bone: i32, pub point2_x_offset: f32, pub point2_y_offset: f32, pub point2_z_offset: f32, pub delete_after_subaction: bool, pub graphic_id: i32, pub bone_id: i32, pub x_offset: f32, pub y_offset: f32, pub z_offset: f32, pub x_rotation: f32, pub y_rotation: f32, pub z_rotation: f32, pub glow_length: f32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct AestheticWindEffect { pub unk1: i32, pub unk2: f32, pub stength: f32, pub speed: f32, pub size: f32, pub unk3: f32, pub unk4: f32, pub unk5: f32, pub unk6: f32, pub unk7: f32, pub unk8: i32, } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct Interrupt { pub interrupt_id: Option<i32>, pub action: i32, pub test: Expression } #[derive(Serialize, Deserialize, Clone, Debug)] pub enum InterruptType { Main, GroundSpecial, GroundItem, GroundCatch, GroundAttack, GroundEscape, GroundGuard, GroundJump, GroundOther, AirLanding, CliffCatch, AirSpecial, AirItemThrow, AirLasso, AirDodge, AirAttack, AirTreadjump, AirWalljump, AirJump, /// Only works in squat PassThroughPlat, Unknown (i32), } impl InterruptType { pub fn new(value: i32) -> Self { match value { 0x00 => InterruptType::Main, 0x01 => InterruptType::GroundSpecial, 0x02 => InterruptType::GroundItem, 0x03 => InterruptType::GroundCatch, 0x04 => InterruptType::GroundAttack, 0x05 => InterruptType::GroundEscape, 0x06 => InterruptType::GroundGuard, 0x07 => InterruptType::GroundJump, 0x08 => InterruptType::GroundOther, 0x09 => InterruptType::AirLanding, 0x0A => InterruptType::CliffCatch, 0x0B => InterruptType::AirSpecial, 0x0C => InterruptType::AirItemThrow, 0x0D => InterruptType::AirLasso, 0x0E => InterruptType::AirDodge, 0x0F => InterruptType::AirAttack, 0x10 => InterruptType::AirTreadjump, 0x11 => InterruptType::AirWalljump, 0x12 => InterruptType::AirJump, 0x13 => InterruptType::PassThroughPlat, _ => InterruptType::Unknown (value) } } } #[derive(Serialize, Deserialize, Clone, Debug)] pub struct CameraCloseup { pub zoom_time: i32, pub unk: i32, pub distance: f32, pub x_angle: f32, pub y_angle: f32, }
use std::fmt; pub struct Enum<'a> { name: &'static str, members: Vec<EnumMember<'a>>, } pub struct EnumMember<'a> { name: &'a str, value: &'a usize, } impl<'a> fmt::Display for Enum<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { const DERIVES: &str = "#[derive(Debug, Copy, Clone, Eq, PartialEq)]\n"; write!(f, "{}", DERIVES)?; write!(f, "pub enum {} {{\n", self.name)?; for member in &self.members { write!(f, " {},\n", member)?; } write!(f, "{}", "}\n") } } impl<'a> fmt::Display for EnumMember<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let name = to_camelcase(self.name); write!(f, "{} = {}", name, self.value) } } fn to_camelcase(input: &str) -> String { let mut output = String::with_capacity(64); for part in input.split("_") { if part.len() > 0 { output.push_str(&part.get(..1).unwrap().to_uppercase()); } if part.len() > 1 { output.push_str(&part.get(1..).unwrap().to_lowercase()) } } output } pub fn from_slice<'a, D: crate::ToEnum>(name: &'static str, data: &'a [D]) -> Enum<'a> { let members: Vec<_> = data .iter() .map(|d| EnumMember { name: d.name(), value: d.value(), }) .collect(); Enum { name, members } }
use core::f64::consts::FRAC_PI_2; use crate::coord_plane::LatLonPoint; use crate::one_dim_lines::points_between_exclusive_both_ends; use crate::one_dim_lines::points_between_inclusive; pub fn sphere_coords(num_lines: usize, num_points: usize) -> Vec<LatLonPoint> { merids(num_lines, num_points).iter().copied().chain( pars(num_lines, num_points)).collect() } fn merids(num_merids: usize, num_points: usize) -> Vec<LatLonPoint> { points_between_inclusive(0.0, FRAC_PI_2, num_points) .iter().copied() .map(|x| meridian(x, num_merids)).flatten().collect() } fn pars(num_pars: usize, num_points: usize) -> Vec<LatLonPoint> { merids(num_pars, num_points).iter().map( |point| LatLonPoint { lambda: point.phi, phi: point.lambda, }).collect() } // takes radian degree between 0 and π/2 // integral num points // returns meridian with num points on both "sides" fn meridian(deg: f64, num: usize) -> Vec<LatLonPoint> { points_between_inclusive(-(FRAC_PI_2), FRAC_PI_2, num).iter().copied() .map(|x| vec![ LatLonPoint { lambda: x, phi: deg }, LatLonPoint { lambda: x, phi: deg-(FRAC_PI_2) }]) .flatten().collect() } #[allow(dead_code)] pub fn intersections_of_pars_and_merids(num_lines: usize) -> Vec<LatLonPoint> { points_between_exclusive_both_ends(-FRAC_PI_2, FRAC_PI_2, num_lines).iter() .map(|x| points_between_exclusive_both_ends(-FRAC_PI_2, FRAC_PI_2, num_lines).iter() .map(|y| LatLonPoint { lambda: *x, phi: *y } ).collect::<Vec<LatLonPoint>>()) .flatten().collect() }
use ast::*; use std::vec::Vec; use std::f64::consts::PI; type Coord = (f64, f64); pub fn interp<F: FnMut(Coord, Coord) -> ()>(stmnts: &Vec<Stmnt>, mut draw_line: F) -> () { let mut coord: Coord = (0.0, 0.0); let mut angle: f64 = 0.0; let mut pen_down = false; for stmnt in stmnts { match *stmnt { Stmnt::Move(ref length) => { let length = eval(&length); let new_coord = (coord.0 + length * angle.cos(), coord.1 + length * angle.sin()); if pen_down { draw_line(coord, new_coord); } coord = new_coord }, Stmnt::Rotate(ref degrees) => { let radians = eval(degrees) * PI / 180.0; angle += radians; }, Stmnt::PenUp => { if !pen_down { println!("Warning: Pen was already up."); } pen_down = false; } Stmnt::PenDown => { if pen_down { println!("Warning: Pen was already down."); } pen_down = true; } } } } pub fn eval(exp: &Exp) -> f64 { match *exp { Exp::Const(f) => f, Exp::InfixExp(InfixOp::Add, ref lhs, ref rhs) => eval(&*lhs) + eval(&*rhs), Exp::InfixExp(InfixOp::Mul, ref lhs, ref rhs) => eval(&*lhs) * eval(&*rhs), Exp::InfixExp(InfixOp::Div, ref lhs, ref rhs) => eval(&*lhs) / eval(&*rhs) } }
pub fn box_simple_test() { let b = Box::new(5); println!("b = {}", b); let mut b1 = Box::new([1, 2, 3, 4, 5, 6]); b1[0] = 100; println!("b1 = {}", b1[0]); let b2 = Box::new("box_simple_test"); println!("b2 = {}", b2); } enum List { Cons(i32, Box<List>), //Box seems like pointer, so could compute. Nil, } use self::List::{Cons, Nil}; pub fn box_recursive_test() { let _list = Cons(1, Box::new(Cons(2, Box::new(Cons(3, Box::new(Nil)))))); }
pub type Color = palette::LinSrgba; pub fn black() -> Color { Color::new(0., 0., 0., 1.) } pub fn white() -> Color { Color::new(1., 1., 1., 1.) } pub fn encode_color(color: Color) -> [f32; 4] { let nonlinear = palette::Srgba::from_linear(color); let (r, g, b, a) = nonlinear.into_components(); [r, g, b, a] }
#![feature(proc_macro)] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate synom; extern crate syn; #[macro_use] extern crate quote; extern crate rustfmt_nightly as rustfmt; use proc_macro::TokenStream; use proc_macro2::Term; use syn::*; use quote::Tokens; use quote::ToTokens; use std::str; #[proc_macro_attribute] pub fn staged(_: TokenStream, input: TokenStream) -> TokenStream { let input = input.to_string(); let mut item = match syn::parse_str::<Item>(&input) { Ok(item) => item, Err(err) => panic!("{:?}", err), }; let (mut item, block) = match item { Item::Fn(fn_item) => { if let Unsafety::Unsafe(_) = fn_item.unsafety { panic!("Function can't be unsafe."); } if let Constness::Const(_) = fn_item.constness { panic!("Function can't be const."); } if fn_item.abi.is_some() { panic!("Invalid function abi."); } if !fn_item.decl.generics.params.is_empty() { panic!("Generic types are not supported."); } let block = virtualize(&fn_item.block); (fn_item, block) } _ => panic!("Unexpected item kind, expected function: {:?}", item), }; item.vis = syn::Visibility::Inherited(syn::VisInherited { }); let mut outer_attrs = item.attrs.clone(); outer_attrs.push(syn::Attribute { style: syn::AttrStyle::Outer, pound_token: syn::tokens::Pound([Span::default()]), bracket_token: syn::tokens::Bracket(Span::default()), path: syn::Path { leading_colon: None, segments: vec![ syn::PathSegment { ident: syn::Ident::new( Term::intern("proc_macro"), Span::default(), ), parameters: syn::PathParameters::None, } ].into(), }, tts: vec![], is_sugared_doc: false, }); let ident = item.ident.clone(); let outer_ident = item.ident.clone(); let gen_ident = syn::Ident::new(Term::intern(&(item.ident.as_ref().to_owned() + "_gen")), Span::default()); let fn_inputs = &item.decl.inputs; let func = quote!{ | #fn_inputs | #block }; // println!("{:?}", func.to_string()); let outer_item = quote! { #(#outer_attrs)* pub fn #outer_ident (input: proc_macro::TokenStream) -> proc_macro::TokenStream { let generator = #func; // let gen_ident = quote! { #gen_ident }.to_string(); let gen_fn = generator(); let input = input.to_string(); let fn_impl = format!(" {{ || {{ {} }} }} ", gen_fn.to_string()); // panic!("{:?}", fn_impl.to_string()); fn_impl.to_string().parse().unwrap() } }; println!("Generated: {}", formatting(&outer_item.to_string())); outer_item.to_string().parse().unwrap() } fn formatting(input: &str) -> String { let string = input.to_string(); let config = rustfmt::config::Config::default(); let res = rustfmt::format_input::<Vec<u8>>( rustfmt::Input::Text(string), &config, None, ); match res { Ok((summary, file_map, report)) => { file_map[0].1.to_string() } Err(err) => { println!("{:?}", err); "".into() } } } fn virtualize(block: &syn::Block) -> Tokens { let mut tokens = Tokens::new(); block.virtualize(&mut tokens); let virtualized = quote! { { let mut __tokens = ::quote::Tokens::new(); #tokens __tokens } }; let wrapper_tokens = quote! { fn foo() { let mut __tokens = ::quote::Tokens::new(); #tokens __tokens } }; println!("virtualized: {}", formatting(&wrapper_tokens.to_string())); virtualized }
// Copyright (c) 2021, Roel Schut. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use std::borrow::{Borrow, BorrowMut}; use gdnative::api::Area2D; use crate::*; use crate::enemy::*; use crate::utils::convert::TryInstanceFrom; use crate::utils::singleton::SingletonInstance; use crate::utils::utils; use crate::player::{Player, PlayerBullet}; use crate::signals::*; use crate::signals::instance_node::InstanceNodeEmitter; use crate::sound::SoundController; use crate::world::World; #[derive(NativeClass)] #[inherit(Sprite)] #[register_with(Self::register_signals)] pub struct Enemy { #[property(default = 1)] health: u8, #[property(default = 50.0)] speed: f32, #[property(default = 5)] point_value: u32, particles_scene: Ref<PackedScene>, } impl InstanceNodeEmitter<Self> for Enemy {} #[methods] impl Enemy { fn register_signals<'a>(builder: &ClassBuilder<Self>) { Self::add_instance_node_signal(builder); } fn new(_owner: &Sprite) -> Self { Enemy { health: 1, speed: 50.0, point_value: 5, particles_scene: PackedScene::new().into_shared(), } } #[export] pub fn destroy(&self, owner: &Sprite) { SoundController::try_do(owner, |sc, sc_node| { sc.play_sound(sc_node.as_ref(), sound::EXPLOSION) }); self.emit_instance_node( owner, self.particles_scene.borrow(), owner.global_position().clone(), ); owner.queue_free(); } #[export] fn _ready(&mut self, owner: &Sprite) { self.particles_scene = utils::preload(RES_PARTICLES); World::singleton(owner).borrow() .map(|_, target| { owner.connect( instance_node::SIGNAL, target, world::ON_INSTANCE_NODE, VariantArray::new_shared(), 1, ) }) .unwrap() .expect("Failed to connect Enemy1 to World"); } #[export] fn _process(&self, owner: &Sprite, delta: f32) { let mut pos = owner.global_position(); pos.x -= self.speed * delta; owner.set_global_position(pos); if pos.x < -20.0 { owner.queue_free(); } } #[allow(non_snake_case)] #[export] fn _on_Hitbox_area_entered(&mut self, owner: &Sprite, area: Ref<Area2D>) { let area = unsafe { area.assume_safe() }; if !area.is_in_group(GROUP_DAMAGER) { return; } self.health -= PlayerBullet::try_instance_from(area.get_parent()) .expect("Failed to get bullet from Area2D") .borrow() .map(|bullet, bullet_node| { bullet_node.queue_free(); bullet.get_damage() }) .unwrap_or(1); if self.health == 0 { Player::singleton(owner) .borrow_mut() .map_mut(|player, _| { player.add_score(self.point_value); }) .expect("Failed to add score"); self.destroy(owner); } } } impl TryInstanceFrom<Self, Sprite> for Enemy {}
mod address_compute; mod hasher; mod serialize; pub use serialize::{ DefaultAccountDeserializer, DefaultAccountSerializer, DefaultTemplateDeserializer, DefaultTemplateSerializer, }; #[cfg(feature = "default-memory")] mod memory; #[cfg(feature = "default-memory")] pub use memory::{DefaultMemAccountStore, DefaultMemEnvTypes, DefaultMemTemplateStore}; #[cfg(feature = "default-rocksdb")] mod rocksdb; #[cfg(feature = "default-rocksdb")] pub use rocksdb::{DefaultRocksAccountStore, DefaultRocksEnvTypes, DefaultRocksTemplateStore}; pub use address_compute::{DefaultAccountAddressCompute, DefaultTemplateAddressCompute}; pub use hasher::DefaultTemplateHasher;
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_hyper::StandardClient; use aws_sdk_kms::operation::GenerateRandom; use aws_sdk_kms::{Config, Region}; // snippet-start:[kms.rust.kms-helloworld] /// Creates a random byte string that is cryptographically secure in __us-east-1__. #[tokio::main] async fn main() { let config = Config::builder() // region can also be loaded from AWS_DEFAULT_REGION, just remove this line. .region(Region::new("us-east-1")) // creds loaded from environment variables, or they can be hard coded. // Other credential providers not currently supported .build(); // NB: This example uses the "low level internal API" for demonstration purposes // This is sometimes necessary to get precise control over behavior, but in most cases // using `kms::Client` is recommended. let client: StandardClient = aws_hyper::Client::https(); let data = client .call( GenerateRandom::builder() .number_of_bytes(64) .build() .expect("valid operation") .make_operation(&config) .expect("valid operation"), ) .await .expect("failed to generate random data"); println!("{:?}", data); assert_eq!(data.plaintext.expect("should have data").as_ref().len(), 64); } // snippet-end:[kms.rust.kms-helloworld]
use game_rusty::GameRusty; fn main() { let mut m = GameRusty::new(); print!("{:?}", m.next_instruction()) }
use crate::core::{Function, Measurement, PrivacyRelation}; use crate::dist::{MaxDivergence, L1Sensitivity}; use crate::dom::AllDomain; use crate::error::*; use crate::samplers::{SampleBernoulli, SampleGeometric, SampleUniform}; use crate::traits::DistanceCast; use num::{Float, CheckedAdd, CheckedSub, Zero}; pub fn make_base_geometric<T, QO>(scale: QO, min: T, max: T) -> Fallible<Measurement<AllDomain<T>, AllDomain<T>, L1Sensitivity<T>, MaxDivergence<QO>>> where T: 'static + Clone + SampleGeometric + CheckedSub<Output=T> + CheckedAdd<Output=T> + DistanceCast + Zero, QO: 'static + Float + DistanceCast, f64: From<QO> { if scale.is_sign_negative() { return fallible!(MakeMeasurement, "scale must not be negative") } let max_trials: T = max - min; let alpha: f64 = (-f64::from(scale).recip()).exp(); Ok(Measurement::new( AllDomain::new(), AllDomain::new(), Function::new_fallible(move |arg: &T| -> Fallible<T> { // return 0 noise with probability (1-alpha) / (1+alpha), otherwise sample from geometric Ok(if f64::sample_standard_uniform(false)? < (1. - alpha) / (1. + alpha) { arg.clone() } else { let noise = T::sample_geometric(1. - alpha, max_trials.clone(), false)?; if bool::sample_standard_bernoulli()? { arg.clone().checked_add(&noise) } else { arg.clone().checked_sub(&noise) }.unwrap_or_else(T::zero) }) }), L1Sensitivity::default(), MaxDivergence::default(), PrivacyRelation::new_from_constant(scale.recip()))) } #[cfg(test)] mod tests { use super::*; #[test] fn test_make_geometric_mechanism() { let measurement = make_base_geometric::<i32, f64>(10.0, 200, 210).unwrap_test(); let arg = 205; let _ret = measurement.function.eval(&arg).unwrap_test(); assert!(measurement.privacy_relation.eval(&1, &0.5).unwrap_test()); } }
use std::borrow::Cow; use std::default::Default; use std::fs; use std::mem; use std::sync::Mutex; mod dwarf; use fnv::FnvHashMap as HashMap; use object::{self, Object, ObjectSection, ObjectSegment, ObjectSymbol, ObjectSymbolTable}; use crate::cfi::Cfi; use crate::function::{Function, FunctionDetails, FunctionOffset}; use crate::location::Register; use crate::range::{Range, RangeList}; use crate::types::{Enumerator, Type, TypeOffset}; use crate::unit::Unit; use crate::variable::Variable; use crate::{Address, Result, Size}; pub(crate) enum DebugInfo<'input, Endian> where Endian: gimli::Endianity + 'input, { Dwarf(dwarf::DwarfDebugInfo<'input, Endian>), } impl<'input, Endian> DebugInfo<'input, Endian> where Endian: gimli::Endianity + 'input, { fn get_type(&self, offset: TypeOffset) -> Option<Type<'input>> { match self { DebugInfo::Dwarf(dwarf) => dwarf.get_type(offset), } } fn get_enumerators(&self, offset: TypeOffset) -> Vec<Enumerator<'input>> { match self { DebugInfo::Dwarf(dwarf) => dwarf.get_enumerators(offset), } } fn get_function_details( &self, offset: FunctionOffset, hash: &FileHash<'input>, ) -> Option<FunctionDetails<'input>> { match self { DebugInfo::Dwarf(dwarf) => dwarf.get_function_details(offset, hash), } } fn get_cfi(&self, range: Range) -> Vec<Cfi> { match self { DebugInfo::Dwarf(dwarf) => dwarf.get_cfi(range), } } fn get_register_name(&self, machine: Architecture, register: Register) -> Option<&'static str> { match self { DebugInfo::Dwarf(dwarf) => dwarf.get_register_name(machine, register), } } } pub(crate) struct Arena { // TODO: can these be a single `Vec<Box<dyn ??>>`? buffers: Mutex<Vec<Vec<u8>>>, strings: Mutex<Vec<String>>, #[allow(clippy::vec_box)] relocations: Mutex<Vec<Box<dwarf::RelocationMap>>>, } impl Arena { fn new() -> Self { Arena { buffers: Mutex::new(Vec::new()), strings: Mutex::new(Vec::new()), relocations: Mutex::new(Vec::new()), } } fn add_buffer<'input>(&'input self, bytes: Vec<u8>) -> &'input [u8] { let mut buffers = self.buffers.lock().unwrap(); let i = buffers.len(); buffers.push(bytes); let b = &buffers[i]; unsafe { mem::transmute::<&[u8], &'input [u8]>(b) } } fn add_string<'input>(&'input self, bytes: &'input [u8]) -> &'input str { // FIXME: this is effectively leaking strings that require lossy conversion, // fix by avoiding duplicates match String::from_utf8_lossy(bytes) { Cow::Borrowed(s) => s, Cow::Owned(s) => { let mut strings = self.strings.lock().unwrap(); let i = strings.len(); strings.push(s); let s = &strings[i]; unsafe { mem::transmute::<&str, &'input str>(s) } } } } fn add_relocations<'input>( &'input self, entry: Box<dwarf::RelocationMap>, ) -> &'input dwarf::RelocationMap { let mut relocations = self.relocations.lock().unwrap(); let i = relocations.len(); relocations.push(entry); let entry = &relocations[i]; unsafe { mem::transmute::<&dwarf::RelocationMap, &'input dwarf::RelocationMap>(entry) } } } pub use object::Architecture; /// The context needed for a parsed file. /// /// The parsed file references the context, so it is included here as well. pub struct FileContext { // Self-referential, not actually `static. file: File<'static>, _map: memmap::Mmap, _arena: Box<Arena>, } impl FileContext { fn new<F>(map: memmap::Mmap, f: F) -> Result<FileContext> where F: for<'a> FnOnce(&'a [u8], &'a Arena) -> Result<File<'a>>, { let arena = Box::new(Arena::new()); let file = f(&map, &arena)?; Ok(FileContext { // `file` only borrows from `map` and `arena`, which we are preserving // without moving. file: unsafe { mem::transmute::<File<'_>, File<'static>>(file) }, _map: map, _arena: arena, }) } /// Return the parsed debuginfo for the file. pub fn file<'a>(&'a self) -> &'a File<'a> { unsafe { mem::transmute::<&'a File<'static>, &'a File<'a>>(&self.file) } } } /// The parsed debuginfo for a single file. pub struct File<'input> { pub(crate) path: String, pub(crate) machine: Architecture, pub(crate) segments: Vec<Segment<'input>>, pub(crate) sections: Vec<Section<'input>>, pub(crate) symbols: Vec<Symbol<'input>>, pub(crate) relocations: Vec<Relocation<'input>>, pub(crate) units: Vec<Unit<'input>>, debug_info: DebugInfo<'input, gimli::RunTimeEndian>, } impl<'input> File<'input> { pub(crate) fn get_type(&self, offset: TypeOffset) -> Option<Type<'input>> { self.debug_info.get_type(offset) } pub(crate) fn get_enumerators(&self, offset: TypeOffset) -> Vec<Enumerator<'input>> { self.debug_info.get_enumerators(offset) } pub(crate) fn get_function_details( &self, offset: FunctionOffset, hash: &FileHash<'input>, ) -> FunctionDetails<'input> { self.debug_info .get_function_details(offset, hash) .unwrap_or_default() } pub(crate) fn get_register_name(&self, register: Register) -> Option<&'static str> { self.debug_info.get_register_name(self.machine, register) } /// Parse the file with the given path. pub fn parse(path: String) -> Result<FileContext> { let handle = match fs::File::open(&path) { Ok(handle) => handle, Err(e) => { return Err(format!("open failed: {}", e).into()); } }; let map = match unsafe { memmap::Mmap::map(&handle) } { Ok(map) => map, Err(e) => { return Err(format!("memmap failed: {}", e).into()); } }; // TODO: split DWARF // TODO: PDB FileContext::new(map, |data, strings| { let object = object::File::parse(data)?; File::parse_object(&object, &object, path, strings) }) } fn parse_object( object: &object::File<'input>, debug_object: &object::File<'input>, path: String, arena: &'input Arena, ) -> Result<File<'input>> { let machine = object.architecture(); let mut segments = Vec::new(); for segment in object.segments() { if let Ok(bytes) = segment.data() { segments.push(Segment { address: segment.address(), bytes, }); } } let mut sections = Vec::new(); for section in object.sections() { let name = Some(section.name()?).map(|x| Cow::Owned(x.to_string())); let segment = section.segment_name()?.map(|x| Cow::Owned(x.to_string())); let address = if section.address() != 0 { Some(section.address()) } else { None }; let size = section.size(); if size != 0 { sections.push(Section { name, segment, address, size, }); } } // TODO: symbols from debug_object too? let mut symbols = Vec::new(); for symbol in object.symbols() { // TODO: handle relocatable objects let address = symbol.address(); if address == 0 { continue; } let size = symbol.size(); if size == 0 { continue; } // TODO: handle SymbolKind::File let kind = match symbol.kind() { object::SymbolKind::Text => SymbolKind::Function, object::SymbolKind::Data | object::SymbolKind::Unknown => SymbolKind::Variable, _ => continue, }; let name = Some(symbol.name()?); symbols.push(Symbol { name, kind, address, size, }); } let mut relocations = Vec::new(); if let (Some(dynamic_symbols), Some(dynamic_relocations)) = (object.dynamic_symbol_table(), object.dynamic_relocations()) { for (address, relocation) in dynamic_relocations { let size = relocation.size(); match relocation.target() { object::RelocationTarget::Symbol(index) => { if let Ok(symbol) = dynamic_symbols.symbol_by_index(index) { relocations.push(Relocation { address, size, symbol: symbol.name()?, }); } } _ => {} } } } let endian = if debug_object.is_little_endian() { gimli::RunTimeEndian::Little } else { gimli::RunTimeEndian::Big }; let (units, debug_info) = dwarf::parse(endian, debug_object, arena)?; let mut file = File { path, machine, segments, sections, symbols, relocations, units, debug_info, }; file.normalize(); Ok(file) } fn normalize(&mut self) { self.symbols.sort_by(|a, b| a.address.cmp(&b.address)); let mut used_symbols = vec![false; self.symbols.len()]; // Set symbol names on functions/variables. for unit in &mut self.units { for function in &mut unit.functions { if let Some(address) = function.address() { if let Some(symbol) = Self::get_symbol( &self.symbols, &mut used_symbols, address, function.linkage_name().or_else(|| function.name()), ) { function.symbol_name = symbol.name; } // If there are multiple ranges for the function, // mark any symbols for the remaining ranges as used. // TODO: change `Function::symbol_name` to a list instead? for range in function.ranges().iter().skip(1) { Self::get_symbol(&self.symbols, &mut used_symbols, range.begin, None); } } } for variable in &mut unit.variables { if let Some(address) = variable.address() { if let Some(symbol) = Self::get_symbol( &self.symbols, &mut used_symbols, address, variable.linkage_name().or_else(|| variable.name()), ) { variable.symbol_name = symbol.name; } } } } // Create a unit for symbols that don't have debuginfo. let mut unit = Unit { name: Some(Cow::Borrowed("<symtab>")), ..Default::default() }; for (symbol, used) in self.symbols.iter().zip(used_symbols.iter()) { if *used { continue; } unit.ranges.push(Range { begin: symbol.address, end: symbol.address + symbol.size, }); match symbol.kind() { SymbolKind::Variable => { unit.variables.push(Variable { name: symbol.name, linkage_name: symbol.name, address: Address::new(symbol.address), size: Size::new(symbol.size), ..Default::default() }); } SymbolKind::Function => { let mut ranges = Vec::new(); if symbol.size > 0 { ranges.push(Range { begin: symbol.address, end: symbol.address + symbol.size, }); } unit.functions.push(Function { name: symbol.name, linkage_name: symbol.name, address: Address::new(symbol.address), size: Size::new(symbol.size), ranges, ..Default::default() }); } } } unit.ranges.sort(); self.units.push(unit); // Create a unit for all remaining address ranges. let unit = Unit { name: Some(Cow::Borrowed("<unknown>")), ranges: self.unknown_ranges(), ..Default::default() }; self.units.push(unit); } // Determine if the symbol at the given address has the given name. // There may be multiple symbols for the same address. // If none match the given name, then return the first one. fn get_symbol<'sym>( symbols: &'sym [Symbol<'input>], used_symbols: &mut [bool], address: u64, name: Option<&str>, ) -> Option<&'sym Symbol<'input>> { if let Ok(mut index) = symbols.binary_search_by(|x| x.address.cmp(&address)) { while index > 0 && symbols[index - 1].address == address { index -= 1; } let mut found = false; for (symbol, used_symbol) in symbols[index..] .iter() .zip(used_symbols[index..].iter_mut()) { if symbol.address != address { break; } *used_symbol = true; if symbol.name() == name { found = true; } } if found { None } else { Some(&symbols[index]) } } else { None } } /// The file path. #[inline] pub fn path(&self) -> &str { &self.path } /// The machine type that the file contains debuginfo for. #[inline] pub fn machine(&self) -> Architecture { self.machine } /// Find the segment data for the given address range. pub fn segment_bytes(&self, range: Range) -> Option<&'input [u8]> { for segment in &self.segments { if range.begin >= segment.address && range.end <= segment.address + segment.bytes.len() as u64 { let begin = (range.begin - segment.address) as usize; let len = (range.end - range.begin) as usize; return Some(&segment.bytes[begin..][..len]); } } None } /// A list of segments in the file. #[inline] pub fn segments(&self) -> &[Segment<'input>] { &self.segments } /// A list of sections in the file. #[inline] pub fn sections(&self) -> &[Section<'input>] { &self.sections } /// A list of symbols in the file. #[inline] pub fn symbols(&self) -> &[Symbol<'input>] { &self.symbols } /// A list of relocations in the file. #[inline] pub fn relocations(&self) -> &[Relocation<'input>] { &self.relocations } /// A list of compilation units in the file. #[inline] pub fn units(&self) -> &[Unit<'input>] { &self.units } /// A list of address ranges covered by the compilation units. /// /// This includes both `Unit::ranges` and `Unit::unknown_ranges`. pub fn ranges(&self, hash: &FileHash) -> RangeList { let mut ranges = RangeList::default(); for unit in &self.units { for range in unit.ranges(hash).list() { ranges.push(*range); } for range in unit.unknown_ranges(hash).list() { ranges.push(*range); } } ranges.sort(); ranges } // Used to create <unknown> unit. After creation of that unit // this will return an empty range list. fn unknown_ranges(&self) -> RangeList { // FIXME: don't create this hash twice let hash = FileHash::new(self); let unit_ranges = self.ranges(&hash); let mut ranges = RangeList::default(); for section in &self.sections { if let Some(range) = section.address() { ranges.push(range); } } ranges.sort(); ranges.subtract(&unit_ranges) } /// The total size of functions in all compilation units. pub fn function_size(&self) -> u64 { let mut size = 0; for unit in &self.units { size += unit.function_size(); } size } /// The total size of variables in all compilation units. pub fn variable_size(&self, hash: &FileHash) -> u64 { let mut size = 0; for unit in &self.units { size += unit.variable_size(hash); } size } /// Call frame information for the given address range. pub fn cfi(&self, range: Range) -> Vec<Cfi> { self.debug_info.get_cfi(range) } } /// An index of functions and types within a file. pub struct FileHash<'input> { /// The file being indexed. pub file: &'input File<'input>, /// All functions by address. pub functions_by_address: HashMap<u64, &'input Function<'input>>, /// All functions by offset. pub functions_by_offset: HashMap<FunctionOffset, &'input Function<'input>>, /// All variables by address. pub variables_by_address: HashMap<u64, &'input Variable<'input>>, /// All types by offset. pub types: HashMap<TypeOffset, &'input Type<'input>>, // The type corresponding to `TypeOffset::none()`. pub(crate) void: Type<'input>, } impl<'input> FileHash<'input> { /// Create a new `FileHash` for the given `File`. pub fn new(file: &'input File<'input>) -> Self { FileHash { file, functions_by_address: FileHash::functions_by_address(file), functions_by_offset: FileHash::functions_by_offset(file), variables_by_address: FileHash::variables_by_address(file), types: FileHash::types(file), void: Type::void(), } } /// Returns a map from address to function for all functions in the file. fn functions_by_address<'a>(file: &'a File<'input>) -> HashMap<u64, &'a Function<'input>> { let mut functions = HashMap::default(); for unit in &file.units { for function in &unit.functions { if let Some(address) = function.address() { // TODO: handle duplicate addresses functions.insert(address, function); } } } functions } /// Returns a map from offset to function for all functions in the file. fn functions_by_offset<'a>( file: &'a File<'input>, ) -> HashMap<FunctionOffset, &'a Function<'input>> { let mut functions = HashMap::default(); for unit in &file.units { for function in &unit.functions { functions.insert(function.offset, function); } } functions } /// Returns a map from address to function for all functions in the file. fn variables_by_address<'a>(file: &'a File<'input>) -> HashMap<u64, &'a Variable<'input>> { let mut variables = HashMap::default(); for unit in &file.units { for variable in &unit.variables { if let Some(address) = variable.address() { // TODO: handle duplicate addresses variables.insert(address, variable); } } } variables } /// Returns a map from offset to type for all types in the file. fn types<'a>(file: &'a File<'input>) -> HashMap<TypeOffset, &'a Type<'input>> { let mut types = HashMap::default(); for unit in &file.units { for ty in &unit.types { types.insert(ty.offset, ty); } } types } } /// A loadable range of bytes. #[derive(Debug)] pub struct Segment<'input> { /// The address that the bytes should be loaded at. pub address: u64, /// The bytes, which may be code or data. pub bytes: &'input [u8], } /// A named section. #[derive(Debug)] pub struct Section<'input> { pub(crate) name: Option<Cow<'input, str>>, pub(crate) segment: Option<Cow<'input, str>>, pub(crate) address: Option<u64>, pub(crate) size: u64, } impl<'input> Section<'input> { /// The name of this section. pub fn name(&self) -> Option<&str> { self.name.as_deref() } /// The name of the segment containing this section, if applicable. pub fn segment(&self) -> Option<&str> { self.segment.as_deref() } /// The address range covered by this section if it is loadable. pub fn address(&self) -> Option<Range> { self.address.map(|address| Range { begin: address, end: address + self.size, }) } /// The size of the section. #[inline] pub fn size(&self) -> u64 { self.size } } /// A symbol kind. #[derive(Debug, Clone, Copy)] pub enum SymbolKind { /// The symbol is a variable. Variable, /// The symbol is a function. Function, } /// A symbol. #[derive(Debug, Clone)] pub struct Symbol<'input> { pub(crate) name: Option<&'input str>, pub(crate) kind: SymbolKind, pub(crate) address: u64, pub(crate) size: u64, } impl<'input> Symbol<'input> { /// The symbol name. #[inline] pub fn name(&self) -> Option<&str> { self.name } /// The symbol kind. #[inline] pub fn kind(&self) -> SymbolKind { self.kind } /// The symbol address range. #[inline] pub fn address(&self) -> Range { Range { begin: self.address, end: self.address + self.size, } } /// The symbol size range. #[inline] pub fn size(&self) -> u64 { self.size } } /// A relocation. #[derive(Debug, Clone)] pub struct Relocation<'input> { pub(crate) address: u64, pub(crate) size: u8, pub(crate) symbol: &'input str, } impl<'input> Relocation<'input> { /// The relocation address. #[inline] pub fn address(&self) -> u64 { self.address } /// The relocation size. #[inline] pub fn size(&self) -> u8 { self.size } /// The name of the symbol referenced by the relocation. #[inline] pub fn symbol(&self) -> &'input str { self.symbol } }
use lapin::{ExchangeKind, options::{ExchangeDeclareOptions, QueueBindOptions, QueueDeclareOptions}}; use std::env; #[derive(Clone, Debug)] pub struct ConsumerOptions { pub broker_address: String, pub exchange_name: String, pub exchange_type: ExchangeKind, pub exchange_declare_options: ExchangeDeclareOptions, pub queue_name: String, pub queue_declare_options: QueueDeclareOptions, pub queue_bind_options: QueueBindOptions, pub routing_key: String, pub consumer_tag: String } impl ConsumerOptions { pub fn from_environment() -> Self { let broker_address = env::var("BROKER_URL").expect("'BROKER_URL' environment variable"); let consumer_tag = env::var("CONSUMER_TAG").expect("'CONSUMER_TAG' environment variable"); let exchange_name = env::var("EXCHANGE_NAME").expect("'EXCHANGE_NAME' environment variable"); let queue_name = env::var("QUEUE_NAME").expect("'QUEUE_NAME' environment variable"); let routing_key = env::var("ROUTING_KEY").expect("'ROUTING_KEY' environment variable"); Self::new(broker_address, consumer_tag, exchange_name, queue_name, routing_key) } pub fn new( broker_address: String, consumer_tag: String, exchange_name: String, queue_name: String, routing_key: String ) -> Self { ConsumerOptions { broker_address, consumer_tag, exchange_name, exchange_type: ExchangeKind::Topic, exchange_declare_options: ExchangeDeclareOptions::default(), queue_name, queue_declare_options: QueueDeclareOptions::default(), queue_bind_options: QueueBindOptions::default(), routing_key } } }
// Copyright (C) 2021 Subspace Labs, Inc. // SPDX-License-Identifier: Apache-2.0 // 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. //! Pallet feeds, used for storing arbitrary user-provided data combined into feeds. #![cfg_attr(not(feature = "std"), no_std)] #![forbid(unsafe_code)] #![warn(rust_2018_idioms, missing_debug_implementations)] use core::mem; pub use pallet::*; use sp_std::vec; use sp_std::vec::Vec; use subspace_core_primitives::{crypto, Blake2b256Hash}; pub mod feed_processor; #[cfg(all(feature = "std", test))] mod mock; #[cfg(all(feature = "std", test))] mod tests; #[frame_support::pallet] mod pallet { use crate::feed_processor::{FeedMetadata, FeedProcessor as FeedProcessorT}; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; use sp_runtime::traits::{CheckedAdd, Hash, One, StaticLookup}; use sp_runtime::ArithmeticError; use sp_std::prelude::*; #[pallet::config] pub trait Config: frame_system::Config { /// `pallet-feeds` events type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>; // Feed ID uniquely identifies a Feed type FeedId: Parameter + Member + Default + Copy + PartialOrd + CheckedAdd + One; // Type that references to a particular impl of feed processor type FeedProcessorKind: Parameter + Member + Default + Copy; #[pallet::constant] type MaxFeeds: Get<u32>; fn feed_processor( feed_processor_kind: Self::FeedProcessorKind, ) -> Box<dyn FeedProcessorT<Self::FeedId>>; } /// Pallet feeds, used for storing arbitrary user-provided data combined into feeds. #[pallet::pallet] #[pallet::without_storage_info] pub struct Pallet<T>(_); /// User-provided object to store pub(super) type Object = Vec<u8>; /// User provided initial data for validation pub(super) type InitData = Vec<u8>; /// Total amount of data and number of objects stored in a feed #[derive(Debug, Decode, Encode, TypeInfo, Default, PartialEq, Eq)] pub struct TotalObjectsAndSize { /// Total size of objects in bytes pub size: u64, /// Total number of objects pub count: u64, } #[derive(Debug, Decode, Encode, TypeInfo, Default)] pub struct FeedConfig<FeedProcessorId, AccountId> { pub active: bool, pub feed_processor_id: FeedProcessorId, pub owner: AccountId, } #[pallet::storage] #[pallet::getter(fn metadata)] pub(super) type Metadata<T: Config> = StorageMap<_, Identity, T::FeedId, FeedMetadata, OptionQuery>; #[pallet::storage] #[pallet::getter(fn feed_configs)] pub(super) type FeedConfigs<T: Config> = StorageMap< _, Identity, T::FeedId, FeedConfig<T::FeedProcessorKind, T::AccountId>, OptionQuery, >; #[pallet::storage] #[pallet::getter(fn feeds)] pub(super) type Feeds<T: Config> = StorageMap<_, Identity, T::AccountId, BoundedVec<T::FeedId, T::MaxFeeds>, OptionQuery>; #[pallet::storage] #[pallet::getter(fn totals)] pub(super) type Totals<T: Config> = StorageMap<_, Identity, T::FeedId, TotalObjectsAndSize, ValueQuery>; #[pallet::storage] #[pallet::getter(fn next_feed_id)] pub(super) type NextFeedId<T: Config> = StorageValue<_, T::FeedId, ValueQuery>; #[pallet::storage] pub(super) type SuccessfulPuts<T: Config> = StorageValue<_, Vec<T::Hash>, ValueQuery>; /// `pallet-feeds` events #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { /// New object was added. ObjectSubmitted { feed_id: T::FeedId, who: T::AccountId, metadata: FeedMetadata, object_size: u64, }, /// New feed was created. FeedCreated { feed_id: T::FeedId, who: T::AccountId, }, /// An existing feed was updated. FeedUpdated { feed_id: T::FeedId, who: T::AccountId, }, /// Feed was closed. FeedClosed { feed_id: T::FeedId, who: T::AccountId, }, /// Feed was deleted. FeedDeleted { feed_id: T::FeedId, who: T::AccountId, }, /// feed ownership transferred OwnershipTransferred { feed_id: T::FeedId, old_owner: T::AccountId, new_owner: T::AccountId, }, } /// `pallet-feeds` errors #[pallet::error] pub enum Error<T> { /// `FeedId` doesn't exist UnknownFeedId, /// Feed was closed FeedClosed, /// Not a feed owner NotFeedOwner, /// Maximum feeds created by the caller MaxFeedsReached, } macro_rules! ensure_owner { ( $origin:expr, $feed_id:expr ) => {{ let sender = ensure_signed($origin)?; let feed_config = FeedConfigs::<T>::get($feed_id).ok_or(Error::<T>::UnknownFeedId)?; ensure!(feed_config.owner == sender, Error::<T>::NotFeedOwner); (sender, feed_config) }}; } #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> { fn on_initialize(_now: BlockNumberFor<T>) -> Weight { SuccessfulPuts::<T>::kill(); T::DbWeight::get().writes(1) } } #[pallet::call] impl<T: Config> Pallet<T> { // TODO: add proper weights /// Create a new feed #[pallet::call_index(0)] #[pallet::weight((10_000, Pays::No))] pub fn create( origin: OriginFor<T>, feed_processor_id: T::FeedProcessorKind, init_data: Option<InitData>, ) -> DispatchResult { let who = ensure_signed(origin)?; let feed_id = NextFeedId::<T>::get(); let next_feed_id = feed_id .checked_add(&One::one()) .ok_or(ArithmeticError::Overflow)?; let feed_processor = T::feed_processor(feed_processor_id); if let Some(init_data) = init_data { feed_processor.init(feed_id, init_data.as_slice())?; } // check if max feeds are reached let mut owned_feeds = Feeds::<T>::get(who.clone()).unwrap_or_default(); owned_feeds .try_push(feed_id) .map_err(|_| Error::<T>::MaxFeedsReached)?; NextFeedId::<T>::set(next_feed_id); FeedConfigs::<T>::insert( feed_id, FeedConfig { active: true, feed_processor_id, owner: who.clone(), }, ); Feeds::<T>::insert(who.clone(), owned_feeds); Totals::<T>::insert(feed_id, TotalObjectsAndSize::default()); Self::deposit_event(Event::FeedCreated { feed_id, who }); Ok(()) } /// Updates the feed with init data provided. #[pallet::call_index(1)] #[pallet::weight((10_000, Pays::No))] pub fn update( origin: OriginFor<T>, feed_id: T::FeedId, feed_processor_id: T::FeedProcessorKind, init_data: Option<InitData>, ) -> DispatchResult { let (owner, feed_config) = ensure_owner!(origin, feed_id); let feed_processor = T::feed_processor(feed_processor_id); if let Some(init_data) = init_data { feed_processor.init(feed_id, init_data.as_slice())?; } FeedConfigs::<T>::insert( feed_id, FeedConfig { active: feed_config.active, feed_processor_id, owner: owner.clone(), }, ); Self::deposit_event(Event::FeedUpdated { feed_id, who: owner, }); Ok(()) } // TODO: add proper weights // TODO: For now we don't have fees, but we will have them in the future /// Put a new object into a feed #[pallet::call_index(2)] #[pallet::weight((10_000, Pays::No))] pub fn put(origin: OriginFor<T>, feed_id: T::FeedId, object: Object) -> DispatchResult { let (owner, feed_config) = ensure_owner!(origin, feed_id); // ensure feed is active ensure!(feed_config.active, Error::<T>::FeedClosed); let object_size = object.len() as u64; let feed_processor = T::feed_processor(feed_config.feed_processor_id); let metadata = feed_processor .put(feed_id, object.as_slice())? .unwrap_or_default(); Metadata::<T>::insert(feed_id, metadata.clone()); Totals::<T>::mutate(feed_id, |feed_totals| { feed_totals.size += object_size; feed_totals.count += 1; }); Self::deposit_event(Event::ObjectSubmitted { feed_id, who: owner, metadata, object_size, }); // store the call // there could be multiple calls with same hash and that is fine // since we assume the same order let uniq = T::Hashing::hash(Call::<T>::put { feed_id, object }.encode().as_slice()); SuccessfulPuts::<T>::append(uniq); Ok(()) } /// Closes the feed and stops accepting new feed. #[pallet::call_index(3)] #[pallet::weight((T::DbWeight::get().reads_writes(1, 1), Pays::No))] pub fn close(origin: OriginFor<T>, feed_id: T::FeedId) -> DispatchResult { let (owner, mut feed_config) = ensure_owner!(origin, feed_id); feed_config.active = false; FeedConfigs::<T>::insert(feed_id, feed_config); Self::deposit_event(Event::FeedClosed { feed_id, who: owner, }); Ok(()) } /// Transfers feed from current owner to new owner #[pallet::call_index(4)] #[pallet::weight((T::DbWeight::get().reads_writes(3, 3), Pays::No))] pub fn transfer( origin: OriginFor<T>, feed_id: T::FeedId, new_owner: <T::Lookup as StaticLookup>::Source, ) -> DispatchResult { let (owner, mut feed_config) = ensure_owner!(origin, feed_id); let new_owner = T::Lookup::lookup(new_owner)?; // remove current owner details let mut current_owner_feeds = Feeds::<T>::get(owner.clone()).unwrap_or_default(); current_owner_feeds.retain(|x| *x != feed_id); // update new owner details feed_config.owner = new_owner.clone(); let mut new_owner_feeds = Feeds::<T>::get(new_owner.clone()).unwrap_or_default(); new_owner_feeds .try_push(feed_id) .map_err(|_| Error::<T>::MaxFeedsReached)?; // if the owner doesn't own any feed, then reclaim empty storage if current_owner_feeds.is_empty() { Feeds::<T>::remove(owner.clone()); } else { Feeds::<T>::insert(owner.clone(), current_owner_feeds); } Feeds::<T>::insert(new_owner.clone(), new_owner_feeds); FeedConfigs::<T>::insert(feed_id, feed_config); Self::deposit_event(Event::OwnershipTransferred { feed_id, old_owner: owner, new_owner, }); Ok(()) } } } /// Mapping to the object offset within an extrinsic associated with given key #[derive(Debug)] pub struct CallObject { /// Key to the object located at the offset. pub key: Blake2b256Hash, /// Offset of object in the encoded call. pub offset: u32, } impl<T: Config> Pallet<T> { pub fn successful_puts() -> Vec<T::Hash> { SuccessfulPuts::<T>::get() } } impl<T: Config> Call<T> { /// Extract the call objects if an extrinsic corresponds to `put` call pub fn extract_call_objects(&self) -> Vec<CallObject> { match self { Self::put { feed_id, object } => { let feed_processor_id = match FeedConfigs::<T>::get(feed_id) { Some(config) => config.feed_processor_id, // return if this was a invalid extrinsic None => return vec![], }; let feed_processor = T::feed_processor(feed_processor_id); let objects_mappings = feed_processor.object_mappings(*feed_id, object); // +1 for the Call::put enum variant // Since first arg is feed_id, we bump the offset by its encoded size let base_offset = 1 + mem::size_of::<T::FeedId>() as u32; objects_mappings .into_iter() .filter_map(|object_mapping| { let mut co = object_mapping.try_into_call_object( feed_id, object.as_slice(), |data| crypto::blake2b_256_hash(data), )?; co.offset += base_offset; Some(co) }) .collect() } _ => Default::default(), } } }
use actix_web::{web, HttpRequest, HttpResponse, }; use actix_files::NamedFile; use std::path::PathBuf; use tera::{Context, Tera}; use futures::future::{join_all, ok as fut_ok, Future, Either}; use std::default::Default; use std::net::IpAddr; use std::process; use std::str::from_utf8; use crate::error::Result; //?command=traceroute&target=rappet.de&rawoutput=true #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Params { target: Option<Target>, #[serde(default)] command: Command, #[serde(default)] rawoutput: bool, } impl Params { fn perform(self) -> Result<Option<String>> { //let output = &process::Command::new(cmd.name()).args(&[&ip.to_string()]).output()?.stdout; match (self.target, self.command) { (Some(Target::Ip(ip)), Command::Ping) => { let output = process::Command::new("ping").args(&["-c5", &ip.to_string()]).output()?.stdout; Ok(Some(String::from_utf8(output)?)) }, (Some(Target::Ip(ip)), Command::Traceroute) => { let output = process::Command::new("traceroute").args(&["-A", &ip.to_string()]).output()?.stdout; Ok(Some(String::from_utf8(output)?)) }, (Some(Target::Ip(ip)), Command::Mtr) => { let output = process::Command::new("mtr").args(&["-wenzc3", &ip.to_string()]).output()?.stdout; Ok(Some(String::from_utf8(output)?)) }, _ => Ok(None) } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Command { Ping, Traceroute, Mtr, } impl Command { fn name(self) -> &'static str { match self { Command::Ping => "ping", Command::Traceroute => "traceroute", Command::Mtr => "mtr" } } } #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(untagged)] pub enum Target { Ip(IpAddr), Host(String), } impl Default for Command { fn default() -> Command { Command::Traceroute } } fn perform_lg(templ: &Tera, params: &Params) -> Result<String> { let mut ctx = Context::new(); ctx.insert("params", params); match params.clone() { Params { target: Some(Target::Ip(ip)), command: cmd, .. } => { ctx.insert("output", &if let Some(output) = params.clone().perform()? { output } else { String::from("unimplemented") }); let s = templ.render("output-raw.html", &ctx)?; Ok(s) }, _ => { let s = templ.render("index.html", &ctx)?; Ok(s) } } } pub fn index( templ: web::Data<Tera>, params: web::Query<Params>, ) -> impl Future<Item = HttpResponse, Error = actix_web::Error> { web::block(move || perform_lg(&templ, &params)) .from_err() .and_then(|s| HttpResponse::Ok().content_type("text/html").body(s)) } pub fn raw( templ: web::Data<Tera>, params: web::Query<Params>, ) -> Result<HttpResponse> { let mut ctx = Context::new(); ctx.insert("output", &format!("{:?}", params)); ctx.insert("params", &params.0); let s = templ.render("output-raw.html", &ctx)?; Ok(HttpResponse::Ok().content_type("text/html").body(s)) } pub fn traceroute( templ: web::Data<Tera>, params: web::Query<Params>, ) -> Result<HttpResponse> { let mut ctx = Context::new(); ctx.insert("output", &format!("{:?}", params)); ctx.insert("params", &params.0); let s = templ.render("output-traceroute.html", &ctx)?; Ok(HttpResponse::Ok().content_type("text/html").body(s)) } pub fn css(req: HttpRequest) -> Result<NamedFile> { let mut path = PathBuf::from("./static/css"); path.push(req.match_info().query("filename")); Ok(NamedFile::open(path)?) } pub fn js(req: HttpRequest) -> Result<NamedFile> { let mut path = PathBuf::from("./static/js"); path.push(req.match_info().query("filename")); Ok(NamedFile::open(path)?) } pub fn webfonts(req: HttpRequest) -> Result<NamedFile> { let mut path = PathBuf::from("./static/webfonts"); path.push(req.match_info().query("filename")); Ok(NamedFile::open(path)?) }
extern crate libc; use libc::{c_void, c_int, size_t, c_char};//, c_ulong, c_long, c_uint, c_uchar}; pub type AnimCb = extern fn(data : *mut c_void) -> bool; pub type RustCb = extern fn(data : *mut c_void); pub type PressedCb = extern fn(data : *mut c_void, device : c_int, x : c_int, y : c_int); #[repr(C)] pub struct Keyboard; #[repr(C)] pub struct Evas_Object; #[repr(C)] pub struct Ecore_Animator; extern "C" { pub fn init(); pub fn run(); pub fn kexit(); pub fn reduce(); pub fn window_new() -> *const Evas_Object; pub fn ui_create( win : *const Evas_Object, folder : *const c_void, previous : RustCb, next : RustCb ); pub fn ecore_animator_add(cb : AnimCb, data :*const c_void) -> *const Ecore_Animator; pub fn ecore_animator_del(animator : *const Ecore_Animator); pub fn show_image(path : *const c_char); pub fn _slideshow_create( win : *const Evas_Object, folder : *const c_void, previous : RustCb, next : RustCb ) -> *const Evas_Object; pub fn image_add( slideshow : *const Evas_Object, path : *const c_char); }
//! Rust library for low-level abstraction of MIPS32 processors #![feature(llvm_asm)] #![no_std] #![deny(warnings)] #![cfg_attr(feature = "inline-asm", feature(llvm_asm))] #[macro_use] extern crate bitflags; pub mod addr; pub mod instructions; pub mod interrupts; pub mod paging; pub mod registers; pub mod tlb;
/******************************************************* * Copyright (C) 2019,2020 Jonathan Gerber <jlgerber@gmail.com> * * This file is part of packybara. * * packybara can not be copied and/or distributed without the express * permission of Jonathan Gerber *******************************************************/ use super::args::PbFind; use packybara::db::traits::*; use packybara::packrat::{Client, PackratDb}; use packybara::SearchMode; use prettytable::{cell, format, row, table}; use std::ops::Deref; /// Pretty print the set of package coordinates from the database that match the provided criteria /// /// # Arguments /// * `client` - A Client instance used to connect to the database /// * `cmd` - A PbFind enum instance used to extract the relevant commandline arguments /// /// # Returns /// * a Unit if Ok, or a boxed error if Err pub fn find(client: Client, cmd: PbFind) -> Result<(), Box<dyn std::error::Error>> { if let PbFind::PkgCoords { package, level, role, platform, site, search_mode, order_by, .. } = cmd { let mut pb = PackratDb::new(client); let mut results = pb.find_pkgcoords(); results .package_opt(package.as_ref().map(Deref::deref)) .role_opt(role.as_ref().map(Deref::deref)) .level_opt(level.as_ref().map(Deref::deref)) .platform_opt(platform.as_ref().map(Deref::deref)) .site_opt(site.as_ref().map(Deref::deref)) .order_by_opt(order_by.as_ref().map(Deref::deref)); if let Some(ref mode) = search_mode { results.search_mode(SearchMode::try_from_str(mode)?); } let results = results.query()?; // For now I do this. I need to add packge handling into the query // either by switching functions or handling the sql on this end let mut table = table!([bFg => "ID","PACKAGE", "ROLE", "LEVEL", "PLATFORM", "SITE"]); for result in results { table.add_row(row![ result.id, result.package, result.role, result.level, result.platform, result.site ]); } table.set_format(*format::consts::FORMAT_CLEAN); //FORMAT_NO_LINESEP_WITH_TITLE FORMAT_NO_BORDER_LINE_SEPARATOR table.printstd(); }; Ok(()) }
use super::super::components::Position; use specs::Entity; use std::collections::{HashMap, HashSet}; bitflags! { #[derive(Default)] pub struct TileProperties: u16 { const BLOCKED = 1 << 0; } } #[derive(Clone, Default)] struct TileData { properties: TileProperties, entities: HashSet<Entity>, } pub struct GameMap { data: HashMap<Position, TileData>, } impl GameMap { pub fn new() -> GameMap { GameMap { data: HashMap::with_capacity(5000), } } pub fn add(&mut self, coordinate: &Position, entity: Entity) { let entry = &mut self.data.entry(coordinate.clone()).or_default().entities; entry.insert(entity); } pub fn get_entities(&self, coordinate: &Position) -> Option<&HashSet<Entity>> { match self.data.get(coordinate) { None => None, Some(entry) => Some(&entry.entities), } } pub fn mark_tile(&mut self, coordinate: &Position, flags: TileProperties) { let mut entry = &mut self.data.entry(coordinate.clone()).or_default(); entry.properties = entry.properties | flags; } pub fn clear_tile_properties(&mut self, coordinate: &Position) { match self.data.get_mut(&coordinate) { None => (), Some(entry) => { entry.properties = TileProperties::empty(); } } } pub fn tile_is(&self, coordinate: &Position, flags: TileProperties) -> bool { match self.data.get(&coordinate) { None => false, Some(entry) => entry.properties.contains(flags), } } pub fn clear_all(&mut self) { self.data.clear(); } } impl Default for GameMap { fn default() -> Self { GameMap::new() } } #[cfg(test)] mod tests { use super::*; use specs::{Builder, World, WorldExt}; #[test] fn coordinate_up_returns_1_up() { let initial = Position { x: -4, y: 3 }; // Remember that up is negative in Y coordinates for our world let expected = Position { x: -4, y: 2 }; assert_eq!(initial.up(), expected); } #[test] fn coordinate_down_returns_1_down() { let initial = Position { x: -4, y: 3 }; // Remember that down is positive in Y coordinates for our world let expected = Position { x: -4, y: 4 }; assert_eq!(initial.down(), expected); } #[test] fn coordinate_right_returns_1_right() { let initial = Position { x: 5, y: 3 }; let expected = Position { x: 6, y: 3 }; assert_eq!(initial.right(), expected); } #[test] fn coordinate_left_returns_1_left() { let initial = Position { x: 5, y: 3 }; let expected = Position { x: 4, y: 3 }; assert_eq!(initial.left(), expected); } #[test] fn safely_returns_no_entities_when_not_found() { let map: GameMap = GameMap::new(); let square = Position { x: -4, y: 3 }; let result = map.get_entities(&square); match result { Some(_) => panic!("Expected to be empty"), None => (), }; } #[test] fn adds_entities_and_returns_them() { let mut map: GameMap = GameMap::new(); let mut world = World::new(); let expected_value = world.create_entity().build(); let square = Position { x: -3, y: 4 }; map.add(&square, expected_value); let result = map.get_entities(&square); match result { Some(set) => { assert_eq!(set.len(), 1); assert_eq!(set.contains(&expected_value), true); } None => panic!("Not found"), }; let result = map.get_entities(&square.up()); match result { Some(_) => panic!("Should not have gotten anything back from wrong square"), None => (), }; } #[test] fn clears_stored_values() { let mut map: GameMap = GameMap::new(); let mut world = World::new(); let expected_value = world.create_entity().build(); let square = Position { x: -3, y: 4 }; map.add(&square, expected_value); map.clear_all(); let result = map.get_entities(&square); // Don't actually care about underlying implementation, just shouldn't // actually have the value stored here anymore match result { Some(set) => { assert_eq!(set.len(), 0); } None => (), }; } #[test] fn stores_entities_in_different_locations() { let mut map: GameMap = GameMap::new(); let mut world = World::new(); let first_value = world.create_entity().build(); let second_value = world.create_entity().build(); let first_square = Position { x: -3, y: 4 }; let second_square = first_square.up(); map.add(&first_square, first_value); map.add(&second_square, second_value); let result = map.get_entities(&first_square); match result { Some(set) => { assert_eq!(set.len(), 1); assert_eq!(set.contains(&first_value), true); } None => panic!("Not found"), }; let result = map.get_entities(&second_square); match result { Some(set) => { assert_eq!(set.len(), 1); assert_eq!(set.contains(&second_value), true); } None => panic!("Not found"), }; } #[test] fn stores_multiple_unique_entities_in_same_location() { let mut map: GameMap = GameMap::new(); let mut world = World::new(); let first_value = world.create_entity().build(); let second_value = world.create_entity().build(); let square = Position { x: -3, y: 4 }; map.add(&square, first_value); map.add(&square, second_value); let result = map.get_entities(&square); match result { Some(set) => { assert_eq!(set.len(), 2); assert_eq!(set.contains(&first_value), true); assert_eq!(set.contains(&second_value), true); } None => panic!("Not found"), }; } #[test] fn marks_square_as_blocked() { let mut map: GameMap = GameMap::new(); let square = Position { x: -3, y: 4 }; assert!(!map.tile_is(&square, TileProperties::BLOCKED)); map.mark_tile(&square, TileProperties::BLOCKED); assert!(map.tile_is(&square, TileProperties::BLOCKED)); } #[test] fn clears_tile_properties() { let mut map: GameMap = GameMap::new(); let square = Position { x: -3, y: 4 }; map.mark_tile(&square, TileProperties::BLOCKED); assert!(map.tile_is(&square, TileProperties::BLOCKED)); map.clear_tile_properties(&square); assert!(!map.tile_is(&square, TileProperties::BLOCKED)); } }
use bevy::prelude::*; use bevy::window::WindowMode; use bevy::render::camera::Camera; use bevy_tmx::TmxPlugin; fn main() { App::build() .insert_resource(WindowDescriptor { title: "Parallax".to_string(), width: 1024., height: 720., vsync: true, resizable: true, mode: WindowMode::Windowed, ..Default::default() }) .insert_resource(ClearColor(Color::TEAL)) .add_plugins(DefaultPlugins) .add_plugin(TmxPlugin::default()) .add_startup_system(spawn_scene.system()) .add_system(circle_camera.system()) .run() } fn spawn_scene(mut commands: Commands, asset_server: Res<AssetServer>) { commands.spawn_scene(asset_server.load("sticker/sandbox.tmx")); commands.spawn().insert_bundle(OrthographicCameraBundle { transform: Transform::from_xyz(600.0, -600.0, 50.0), ..OrthographicCameraBundle::new_2d() }); } fn circle_camera(time: Res<Time>, mut camera: Query<(&mut Transform, &Camera)>) { let rads = time.seconds_since_startup(); for (mut transform, _camera) in camera.iter_mut() { transform.translation.x = 1264.0 + rads.cos() as f32 * 600.0; transform.translation.y = -720.0 + rads.sin() as f32 * 200.0; } }
pub mod sixty_four { use crate::XxHash64; use core::hash::BuildHasher; use rand::{self, Rng}; #[derive(Clone)] /// Constructs a randomized seed and reuses it for multiple hasher instances. pub struct RandomXxHashBuilder64(u64); impl RandomXxHashBuilder64 { fn new() -> RandomXxHashBuilder64 { RandomXxHashBuilder64(rand::thread_rng().gen()) } } impl Default for RandomXxHashBuilder64 { fn default() -> RandomXxHashBuilder64 { RandomXxHashBuilder64::new() } } impl BuildHasher for RandomXxHashBuilder64 { type Hasher = XxHash64; fn build_hasher(&self) -> XxHash64 { XxHash64::with_seed(self.0) } } } pub mod thirty_two { use crate::XxHash32; use core::hash::BuildHasher; use rand::{self, Rng}; #[derive(Clone)] /// Constructs a randomized seed and reuses it for multiple hasher instances. See the usage warning on `XxHash32`. pub struct RandomXxHashBuilder32(u32); impl RandomXxHashBuilder32 { fn new() -> RandomXxHashBuilder32 { RandomXxHashBuilder32(rand::thread_rng().gen()) } } impl Default for RandomXxHashBuilder32 { fn default() -> RandomXxHashBuilder32 { RandomXxHashBuilder32::new() } } impl BuildHasher for RandomXxHashBuilder32 { type Hasher = XxHash32; fn build_hasher(&self) -> XxHash32 { XxHash32::with_seed(self.0) } } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 mod chain; mod chain_service; mod consensus; pub use chain::{Chain, ChainReader, ChainWriter, ExcludedTxns}; pub use chain_service::{ChainAsyncService, ChainService}; pub use consensus::{Consensus, ConsensusHeader}; use thiserror::Error; pub type ConnectResult<T> = anyhow::Result<T, ConnectBlockError>; #[derive(Error, Debug, Clone)] pub enum ConnectBlockError { #[error("block already exist.")] DuplicateConn, #[error("parent block not exist.")] FutureBlock, #[error("block verify failed.")] VerifyFailed, #[error("connect failed, cause : {0:?}")] Other(String), } pub fn is_ok<T>(conn_result: &ConnectResult<T>) -> bool { conn_result.is_ok() || if let Err(ConnectBlockError::DuplicateConn) = conn_result { true } else { false } }
use crate::Flags; use regex::{Regex, RegexBuilder}; use std::{fs::Metadata, path::Path}; pub struct Check<'a> { check: PathCheck<'a>, flags: &'a Flags, } impl<'a> Check<'a> { pub fn check(&self, path: &Path, metadata: Option<Metadata>) -> bool { match (&self.flags.size, metadata) { (Some(size), Some(meta)) => self.check.check(path) && size.check(meta.len()), _ => self.check.check(path), } } pub fn new(flags: &'a Flags) -> Result<Self, regex::Error> { PathCheck::new(flags).map(|pc| Check { check: pc, flags }) } } pub enum PathCheck<'a> { Allow, CheckRegex(Regex), CheckStr(&'a str), CheckCaseInsensitiveStr(&'a str), } impl<'a> PathCheck<'a> { pub fn check(&self, path: &Path) -> bool { match self { PathCheck::Allow => true, PathCheck::CheckStr(query) => path.to_string_lossy().contains(query), PathCheck::CheckCaseInsensitiveStr(query) => path .to_string_lossy() .to_lowercase() .contains(&query.to_lowercase()), PathCheck::CheckRegex(regex) => regex.is_match(&path.to_string_lossy()), } } pub fn new(flags: &'a Flags) -> Result<Self, regex::Error> { if let Some(ref query) = flags.query { if flags.regex { RegexBuilder::new(&query) .case_insensitive(flags.case_insensitive) .build() .map(|v| PathCheck::CheckRegex(v)) } else { if query == "." { Ok(PathCheck::Allow) } else { if flags.case_insensitive { Ok(PathCheck::CheckCaseInsensitiveStr(&query)) } else { Ok(PathCheck::CheckStr(&query)) } } } } else { Ok(PathCheck::Allow) } } } #[cfg(test)] mod tests { use super::*; use std::path::Path; #[test] fn test_allow() { assert!(PathCheck::Allow.check(Path::new("./foo"))); assert!(PathCheck::Allow.check(Path::new("/full/path.pdf"))); } #[test] fn test_check_str_matches_any_exact_substring() { assert!(PathCheck::CheckStr("o").check(Path::new("./foo"))); assert!(PathCheck::CheckStr("foo").check(Path::new("./foo"))); assert!(PathCheck::CheckStr("/foo").check(Path::new("./foo"))); assert!(PathCheck::CheckStr("./foo").check(Path::new("./foo"))); } #[test] fn test_check_str_tests_punctuation() { assert!(PathCheck::CheckStr("path.pdf").check(Path::new("/full/path.pdf"))); } #[test] fn test_check_str_doesnt_match_unmatching() { assert!(!PathCheck::CheckStr("bogus").check(Path::new("/full/path.pdf"))); } #[test] fn test_check_str_is_case_sensitive() { assert!(!PathCheck::CheckStr("Path.pdf").check(Path::new("/full/path.pdf"))); assert!(!PathCheck::CheckStr("path.pdf").check(Path::new("/full/Path.pdf"))); } #[test] fn test_check_str_insensitive_matches_any_exact_substring_as_case_insensitive() { assert!(PathCheck::CheckCaseInsensitiveStr("O").check(Path::new("./foo"))); assert!(PathCheck::CheckCaseInsensitiveStr("fOo").check(Path::new("./foo"))); assert!(PathCheck::CheckCaseInsensitiveStr("/foo").check(Path::new("./Foo"))); assert!(PathCheck::CheckCaseInsensitiveStr("./foO").check(Path::new("./Foo"))); } #[test] fn test_check_regex() { assert!(PathCheck::CheckRegex(regex("\\.xls$")).check(Path::new("./path/to/thing.xls"))); assert!(!PathCheck::CheckRegex(regex("\\.xls$")).check(Path::new("./path/to/thing.xlsx"))); } fn regex(input: &str) -> Regex { Regex::new(input).unwrap() } }
use std::net::{ TcpListener }; fn main() { let listener = TcpListener::bind("127.0.0.1:8888") .expect("not bound"); println!("127.0.0.1:8888 running"); for stream in listener.incoming() { match stream { Ok(stream) => { println!("new client: {}", stream.peer_addr().expect("wheee, fail")); } Err(e) => { println!("something is bad: {}", e); } } } } /* TCP server diplays peer_addr() on connection */
use std::{str}; use std::error::Error; use error::SimpleError; macro_rules! ret_err { ($e:expr) => { return Err(Box::new(SimpleError::from($e))); } } extern crate pancurses; use pancurses::{ Input, ERR, Window, }; const BANNER: &'static str = r#"================================================================================ = Android ADB Keyboard = = = = = = To end your session just type \q and hit enter = = = = Hit F1 to enter multiline mode = = = = = ================================================================================ "#; const PROMPT: &'static str = "> "; const TAB_ECHO: &'static str = " ➜ "; const ENTER_ECHO: &'static str = "↵\n"; macro_rules! write_str_ret { ($win:expr, $s:expr) => { if $win.addstr($s) == ERR { ret_err!(format!("\ncurses error writing string: {}", $s)); } } } macro_rules! write_char_ret { ($win:expr, $c:expr) => { if $win.addch($c) == ERR { ret_err!(format!("\ncurses error writing char: {}", $c)); } } } #[derive(Debug)] enum State { Normal, MultiLine, } #[derive(Debug)] pub(crate) struct Editor<'a> { cmd_buf: Vec<u8>, cmd_buf_widths: Vec<u8>, echo_buf: Vec<u8>, echo_buf_widths: Vec<u8>, state: State, prompt: String, len: usize, win: &'a Window, start_y: i32, new_prompt: bool, } impl<'a> Editor<'a> { pub(crate) fn new(win: &'a Window, pre: &Option<String>) -> Self{ win.keypad(true); let mut prompt = String::new(); if let Some(ref s) = *pre { prompt.push_str(&s); } let y = win.get_cur_y(); prompt.push_str(PROMPT); Self{ cmd_buf: Vec::with_capacity(512), echo_buf: Vec::with_capacity(512), cmd_buf_widths: Vec::with_capacity(512), echo_buf_widths: Vec::with_capacity(512), prompt: prompt, win: win, new_prompt: true, start_y: y, state: State::Normal, len: 0, } } pub(crate) fn clear_line(&mut self) { let y = self.win.get_cur_y(); for i in (self.start_y..y+1).rev() { self.win.mv(i, 0); self.win.clrtoeol(); } } pub(crate) fn write_banner(&mut self) { self.win.addstr(BANNER); self.start_y = self.win.get_cur_y(); } pub(crate) fn new_line(&mut self) -> Result<(), Box<Error>> { write_char_ret!(self.win, '\n'); self.start_y = self.win.get_cur_y(); self.write_prompt() } pub(crate) fn write_str_ln(&mut self, s: &str) -> Result<(), Box<Error>> { write_str_ret!(self.win, s); write_char_ret!(self.win, '\n'); self.write_prompt() } pub(crate) fn write_prompt(&mut self) -> Result<(), Box<Error>> { match self.state { State::Normal => write_str_ret!(self.win, &self.prompt), State::MultiLine => write_str_ret!(self.win, ">>> "), }; Ok(()) } fn handle_backspace(&mut self) -> Result<(), Box<Error>> { if self.len == 0 { return Ok(()); } match self.cmd_buf_widths.pop() { Some(n) => { for _ in 0..n { self.cmd_buf.pop(); } }, None => {}, }; match self.echo_buf_widths.pop() { Some(n) => { for _ in 0..n { self.echo_buf.pop(); } }, None => {}, }; self.clear_line(); match self.state { State::Normal => { self.write_prompt()?; write_str_ret!(self.win, str::from_utf8(&self.echo_buf)?); }, State::MultiLine => { write_str_ret!(self.win, &self.prompt); let split: Vec<&str> = str::from_utf8(&self.echo_buf)?.split('\n').collect(); for i in 0..split.len() { write_str_ret!(self.win, split[i]); if i < split.len() - 1 { write_char_ret!(self.win, '\n'); write_str_ret!(self.win, ">>> "); } } }, }; Ok(()) } fn handle_char(&mut self, c: char) -> Result<bool, Box<Error>> { match c { '\n' => { match self.state { State::Normal => { if self.len == 0 { self.new_prompt = false; self.add_to_buf(c, false)?; } Ok(true) }, State::MultiLine => { self.add_to_buf(c, true)?; self.write_prompt()?; Ok(false) } } } '\t' => { match self.state { State::Normal => { if self.len == 0 { self.new_prompt = false; self.add_to_buf(c, false)?; } else { self.add_to_buf(c, true)?; } Ok(true) }, State::MultiLine => { self.add_to_buf(c, true)?; Ok(false) } } }, '\u{007f}' | '\u{0008}' => { if self.echo_buf.len() == 0 { self.new_prompt = false; self.add_to_buf(c, false)?; Ok(true) } else { self.handle_backspace()?; Ok(false) } }, _ => { self.add_to_buf(c, true)?; Ok(false) }, } } fn add_to_buf(&mut self, c: char, echo: bool) -> Result<(), Box<Error>> { match c { '\'' => { self.len += 1; self.echo_buf.push(b'\''); self.echo_buf_widths.push(1); let prev = self.cmd_buf.len() as u8; self.cmd_buf.push(b'\''); self.cmd_buf.push(b'"'); self.cmd_buf.push(b'\''); self.cmd_buf.push(b'"'); self.cmd_buf.push(b'\''); self.cmd_buf_widths.push(self.cmd_buf.len() as u8 - prev); if echo { write_char_ret!(self.win, c); } }, '\n' => { self.len += 1; for b in ENTER_ECHO.as_bytes() { self.echo_buf.push(*b); } self.echo_buf_widths.push(ENTER_ECHO.as_bytes().len() as u8); self.cmd_buf.push(b'\n'); self.cmd_buf_widths.push(1); if echo { write_str_ret!(self.win, ENTER_ECHO); } }, '\t' => { self.len += 1; for b in TAB_ECHO.as_bytes() { self.echo_buf.push(*b); } self.echo_buf_widths.push(TAB_ECHO.as_bytes().len() as u8); self.cmd_buf.push(b'\t'); self.cmd_buf_widths.push(1); if echo { write_str_ret!(self.win, TAB_ECHO); } }, _ => { let mut into = [0; 4]; let s = (c as char).encode_utf8(&mut into); if echo { write_str_ret!(self.win, s); } self.cmd_buf_widths.push(s.len() as u8); self.echo_buf_widths.push(s.len() as u8); for b in s.as_bytes() { self.len += 1; self.echo_buf.push(*b); self.cmd_buf.push(*b); } }, }; Ok(()) } pub(crate) fn get_line(&mut self) -> Result<&Vec<u8>, Box<Error>> { self.echo_buf.truncate(0); self.cmd_buf.truncate(0); self.len = 0; if self.new_prompt { self.new_line()?; } else { self.new_prompt = true; } loop { match self.win.getch() { Some(Input::KeyBackspace) => self.handle_backspace()?, Some(Input::KeyF1) => { match self.state { State::Normal => self.state = State::MultiLine, State::MultiLine => self.state = State::Normal, }; }, Some(Input::Character(c)) => { if self.handle_char(c)? { return Ok(&self.cmd_buf); } }, Some(Input::Unknown(c)) => { let msg = &format!("Unknown character `{}`", c); self.write_str_ln(msg)?; }, Some(_) => { // Don't do anything with unrecognized input }, None => (), }; } } }
/* Copyright 2019-2023 Didier Plaindoux Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use crate::stream::end_line::EndLine; use crate::stream::position::Position; use crate::stream::stream::Len; use crate::stream::stream::Stream; #[derive(Copy, Clone)] pub struct ArrayStream<'a, A, P>(&'a [A], P) where A: EndLine, P: Position; impl<'a, A> ArrayStream<'a, A, (usize, usize, usize)> where A: EndLine, { pub fn new(v: &'a [A]) -> Self { Self::new_with_position(v, <(usize, usize, usize)>::new()) } } impl<'a, A, P> ArrayStream<'a, A, P> where A: EndLine, P: Position, { pub fn new_with_position(v: &'a [A], p: P) -> Self { Self(v, p) } } impl<'a, A, P> Stream for ArrayStream<'a, A, P> where A: EndLine + Clone, P: Position + Clone, { type Item = A; type Pos = P; fn position(&self) -> Self::Pos { self.1.clone() } fn next(&self) -> (Option<Self::Item>, Self) { let option = self.0.get(self.1.offset()); if option.is_some() { ( option.cloned(), ArrayStream(self.0, self.1.step(option.unwrap().is_end_line())), ) } else { (option.cloned(), ArrayStream(self.0, self.1.clone())) } } } impl<'a, A, P> Len for ArrayStream<'a, A, P> where A: EndLine, P: Position, { fn len(&self) -> usize { self.0.len() } }
//! Tests auto-converted from "sass-spec/spec/libsass-closed-issues/issue_1803" #[allow(unused)] use super::rsass; // From "sass-spec/spec/libsass-closed-issues/issue_1803/nested.hrx" // Ignoring "nested", error tests are not supported yet. // From "sass-spec/spec/libsass-closed-issues/issue_1803/shallow.hrx" #[test] fn shallow() { assert_eq!( rsass( "a {\ \n display: block\ \n\ \n b {\ \n foo: bar;\ \n }\ \n}\ \n" ) .unwrap(), "a {\ \n display: block b;\ \n display-foo: bar;\ \n}\ \n" ); }
#[doc = "Register `DMAMFBOCR` reader"] pub type R = crate::R<DMAMFBOCR_SPEC>; #[doc = "Field `MFC` reader - Missed frames by the controller"] pub type MFC_R = crate::FieldReader<u16>; #[doc = "Field `OMFC` reader - Overflow bit for missed frame counter"] pub type OMFC_R = crate::BitReader; #[doc = "Field `MFA` reader - Missed frames by the application"] pub type MFA_R = crate::FieldReader<u16>; #[doc = "Field `OFOC` reader - Overflow bit for FIFO overflow counter"] pub type OFOC_R = crate::BitReader; impl R { #[doc = "Bits 0:15 - Missed frames by the controller"] #[inline(always)] pub fn mfc(&self) -> MFC_R { MFC_R::new((self.bits & 0xffff) as u16) } #[doc = "Bit 16 - Overflow bit for missed frame counter"] #[inline(always)] pub fn omfc(&self) -> OMFC_R { OMFC_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bits 17:27 - Missed frames by the application"] #[inline(always)] pub fn mfa(&self) -> MFA_R { MFA_R::new(((self.bits >> 17) & 0x07ff) as u16) } #[doc = "Bit 28 - Overflow bit for FIFO overflow counter"] #[inline(always)] pub fn ofoc(&self) -> OFOC_R { OFOC_R::new(((self.bits >> 28) & 1) != 0) } } #[doc = "Ethernet DMA missed frame and buffer overflow counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmamfbocr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DMAMFBOCR_SPEC; impl crate::RegisterSpec for DMAMFBOCR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dmamfbocr::R`](R) reader structure"] impl crate::Readable for DMAMFBOCR_SPEC {} #[doc = "`reset()` method sets DMAMFBOCR to value 0"] impl crate::Resettable for DMAMFBOCR_SPEC { const RESET_VALUE: Self::Ux = 0; }
pub mod category; pub mod comment; pub mod drive; pub mod embed; pub mod handler; pub mod page; pub mod post; pub mod schema; pub mod topic; pub mod user;
#[doc = "Reader of register DDRCTRL_ADDRMAP6"] pub type R = crate::R<u32, super::DDRCTRL_ADDRMAP6>; #[doc = "Writer for register DDRCTRL_ADDRMAP6"] pub type W = crate::W<u32, super::DDRCTRL_ADDRMAP6>; #[doc = "Register DDRCTRL_ADDRMAP6 `reset()`'s with value 0"] impl crate::ResetValue for super::DDRCTRL_ADDRMAP6 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ADDRMAP_ROW_B12`"] pub type ADDRMAP_ROW_B12_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDRMAP_ROW_B12`"] pub struct ADDRMAP_ROW_B12_W<'a> { w: &'a mut W, } impl<'a> ADDRMAP_ROW_B12_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `ADDRMAP_ROW_B13`"] pub type ADDRMAP_ROW_B13_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDRMAP_ROW_B13`"] pub struct ADDRMAP_ROW_B13_W<'a> { w: &'a mut W, } impl<'a> ADDRMAP_ROW_B13_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `ADDRMAP_ROW_B14`"] pub type ADDRMAP_ROW_B14_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDRMAP_ROW_B14`"] pub struct ADDRMAP_ROW_B14_W<'a> { w: &'a mut W, } impl<'a> ADDRMAP_ROW_B14_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `ADDRMAP_ROW_B15`"] pub type ADDRMAP_ROW_B15_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDRMAP_ROW_B15`"] pub struct ADDRMAP_ROW_B15_W<'a> { w: &'a mut W, } impl<'a> ADDRMAP_ROW_B15_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } #[doc = "Reader of field `LPDDR3_6GB_12GB`"] pub type LPDDR3_6GB_12GB_R = crate::R<bool, bool>; #[doc = "Write proxy for field `LPDDR3_6GB_12GB`"] pub struct LPDDR3_6GB_12GB_W<'a> { w: &'a mut W, } impl<'a> LPDDR3_6GB_12GB_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } impl R { #[doc = "Bits 0:3 - ADDRMAP_ROW_B12"] #[inline(always)] pub fn addrmap_row_b12(&self) -> ADDRMAP_ROW_B12_R { ADDRMAP_ROW_B12_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 8:11 - ADDRMAP_ROW_B13"] #[inline(always)] pub fn addrmap_row_b13(&self) -> ADDRMAP_ROW_B13_R { ADDRMAP_ROW_B13_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:19 - ADDRMAP_ROW_B14"] #[inline(always)] pub fn addrmap_row_b14(&self) -> ADDRMAP_ROW_B14_R { ADDRMAP_ROW_B14_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 24:27 - ADDRMAP_ROW_B15"] #[inline(always)] pub fn addrmap_row_b15(&self) -> ADDRMAP_ROW_B15_R { ADDRMAP_ROW_B15_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bit 31 - LPDDR3_6GB_12GB"] #[inline(always)] pub fn lpddr3_6gb_12gb(&self) -> LPDDR3_6GB_12GB_R { LPDDR3_6GB_12GB_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:3 - ADDRMAP_ROW_B12"] #[inline(always)] pub fn addrmap_row_b12(&mut self) -> ADDRMAP_ROW_B12_W { ADDRMAP_ROW_B12_W { w: self } } #[doc = "Bits 8:11 - ADDRMAP_ROW_B13"] #[inline(always)] pub fn addrmap_row_b13(&mut self) -> ADDRMAP_ROW_B13_W { ADDRMAP_ROW_B13_W { w: self } } #[doc = "Bits 16:19 - ADDRMAP_ROW_B14"] #[inline(always)] pub fn addrmap_row_b14(&mut self) -> ADDRMAP_ROW_B14_W { ADDRMAP_ROW_B14_W { w: self } } #[doc = "Bits 24:27 - ADDRMAP_ROW_B15"] #[inline(always)] pub fn addrmap_row_b15(&mut self) -> ADDRMAP_ROW_B15_W { ADDRMAP_ROW_B15_W { w: self } } #[doc = "Bit 31 - LPDDR3_6GB_12GB"] #[inline(always)] pub fn lpddr3_6gb_12gb(&mut self) -> LPDDR3_6GB_12GB_W { LPDDR3_6GB_12GB_W { w: self } } }
use crate::path; use autorust_openapi::{ AdditionalProperties, MsExamples, OpenAPI, Operation, Parameter, PathItem, Reference, ReferenceOr, Response, Schema, StatusCode, }; use heck::SnakeCase; use indexmap::{IndexMap, IndexSet}; use std::{ ffi::OsStr, fs, path::{Path, PathBuf}, }; /// An API specification #[derive(Clone, Debug)] pub struct Spec { /// A store of all the documents for an API specification keyed on their file paths where the first one is the root document docs: IndexMap<PathBuf, OpenAPI>, schemas: IndexMap<RefKey, Schema>, parameters: IndexMap<RefKey, Parameter>, input_files_paths: IndexSet<PathBuf>, } impl Spec { /// Read a list of input files as OpenApi docs with the first being the root doc /// /// This eagerly collects all the schemas and parametes for the docs pub fn read_files<P: AsRef<Path>>(input_files_paths: &[P]) -> Result<Self> { let mut docs: IndexMap<PathBuf, OpenAPI> = IndexMap::new(); for file_path in input_files_paths { Spec::read_file(&mut docs, file_path)?; } let mut schemas: IndexMap<RefKey, Schema> = IndexMap::new(); let mut parameters: IndexMap<RefKey, Parameter> = IndexMap::new(); for (path, doc) in &docs { for (name, schema) in &doc.definitions { if let ReferenceOr::Item(schema) = schema { let ref_key = RefKey { file_path: path.clone(), name: name.clone(), }; schemas.insert(ref_key, schema.clone()); } } for (name, param) in &doc.parameters { parameters.insert( RefKey { file_path: path.clone(), name: name.clone(), }, param.clone(), ); } } Ok(Self { docs, schemas, parameters, input_files_paths: input_files_paths.iter().map(|f| f.as_ref().to_owned()).collect(), }) } /// Read a file and references too, recursively into the map fn read_file<P: AsRef<Path>>(docs: &mut IndexMap<PathBuf, OpenAPI>, file_path: P) -> Result<()> { let file_path = file_path.as_ref(); if !docs.contains_key(file_path) { let doc = openapi::parse(&file_path)?; let ref_files = openapi::get_reference_file_paths(&file_path.to_path_buf(), &doc); docs.insert(PathBuf::from(file_path), doc); for ref_file in ref_files { let child_path = path::join(&file_path, &ref_file).map_err(|source| Error::PathJoin { source })?; Spec::read_file(docs, &child_path)?; } } Ok(()) } pub fn docs(&self) -> &IndexMap<PathBuf, OpenAPI> { &self.docs } pub fn title(&self) -> Option<&str> { let mut titles: Vec<_> = self .docs .values() .map(|doc| &doc.info.title) .filter(|t| t.is_some()) .flatten() .collect(); titles.sort_unstable(); titles.get(0).map(|t| t.as_str()) } pub fn consumes(&self) -> Vec<&String> { let mut versions: Vec<_> = self .docs() .values() .filter(|doc| !doc.paths().is_empty()) .map(|api| &api.consumes) .flatten() .collect(); versions.sort_unstable(); versions } /// Look for specs with operations and return the last one sorted alphabetically pub fn api_version(&self) -> Option<String> { let mut versions: Vec<&str> = self .docs() .values() .filter(|doc| !doc.paths().is_empty()) .filter_map(|api| api.info.version.as_deref()) .collect(); versions.sort_unstable(); versions.last().map(|version| version.to_string()) } pub fn input_docs(&self) -> impl Iterator<Item = (&PathBuf, &OpenAPI)> { self.docs.iter().filter(move |(p, _)| self.is_input_file(p)) } pub fn is_input_file<P: AsRef<Path>>(&self, path: P) -> bool { self.input_files_paths.contains(path.as_ref()) } /// Find the schema for a given doc path and reference pub fn resolve_schema_ref<P: AsRef<Path>>(&self, doc_file: P, reference: Reference) -> Result<ResolvedSchema> { let doc_file = doc_file.as_ref(); let full_path = match reference.file { None => doc_file.to_owned(), Some(file) => path::join(doc_file, &file).map_err(|source| Error::PathJoin { source })?, }; let name = reference.name.ok_or(Error::NoNameInReference)?; let ref_key = RefKey { file_path: full_path, name, }; let schema = self .schemas .get(&ref_key) .ok_or_else(|| Error::SchemaNotFound { ref_key: ref_key.clone() })? .clone(); Ok(ResolvedSchema { ref_key: Some(ref_key), schema, }) } /// Find the parameter for a given doc path and reference pub fn resolve_parameter_ref<P: AsRef<Path>>(&self, doc_file: P, reference: Reference) -> Result<Parameter> { let doc_file = doc_file.as_ref(); let full_path = match reference.file { None => doc_file.to_owned(), Some(file) => path::join(doc_file, &file).map_err(|source| Error::PathJoin { source })?, }; let name = reference.name.ok_or(Error::NoNameInReference)?; let ref_key = RefKey { file_path: full_path, name, }; Ok(self.parameters.get(&ref_key).ok_or(Error::ParameterNotFound { ref_key })?.clone()) } /// Resolve a reference or schema to a resolved schema pub fn resolve_schema<P: AsRef<Path>>(&self, doc_file: P, ref_or_schema: &ReferenceOr<Schema>) -> Result<ResolvedSchema> { match ref_or_schema { ReferenceOr::Item(schema) => Ok(ResolvedSchema { ref_key: None, schema: schema.clone(), }), ReferenceOr::Reference { reference, .. } => self.resolve_schema_ref(doc_file.as_ref(), reference.clone()), } } /// Resolve a collection of references or schemas to a collection of resolved schemas pub fn resolve_schemas<P: AsRef<Path>>(&self, doc_file: P, ref_or_schemas: &[ReferenceOr<Schema>]) -> Result<Vec<ResolvedSchema>> { let mut resolved = Vec::new(); for schema in ref_or_schemas { resolved.push(self.resolve_schema(&doc_file, schema)?); } Ok(resolved) } /// Resolve a collection of references or schemas to a collection of resolved schemas pub fn resolve_schema_map<P: AsRef<Path>>( &self, doc_file: P, ref_or_schemas: &IndexMap<String, ReferenceOr<Schema>>, ) -> Result<IndexMap<String, ResolvedSchema>> { let mut resolved = IndexMap::new(); for (name, schema) in ref_or_schemas { resolved.insert(name.clone(), self.resolve_schema(&doc_file, schema)?); } Ok(resolved) } pub fn resolve_path<P: AsRef<Path>>(&self, _doc_file: P, path: &ReferenceOr<PathItem>) -> Result<PathItem> { match path { ReferenceOr::Item(path) => Ok(path.clone()), ReferenceOr::Reference { .. } => { // self.resolve_path_ref(doc_file, reference), // TODO Err(Error::NotImplemented) } } } pub fn resolve_path_map(&self, doc_file: &Path, paths: &IndexMap<String, ReferenceOr<PathItem>>) -> Result<IndexMap<String, PathItem>> { let mut resolved = IndexMap::new(); for (name, path) in paths { resolved.insert(name.clone(), self.resolve_path(doc_file, path)?); } Ok(resolved) } pub fn resolve_parameter(&self, doc_file: &Path, parameter: &ReferenceOr<Parameter>) -> Result<Parameter> { match parameter { ReferenceOr::Item(param) => Ok(param.clone()), ReferenceOr::Reference { reference, .. } => self.resolve_parameter_ref(doc_file, reference.clone()), } } pub fn resolve_parameters(&self, doc_file: &Path, parameters: &[ReferenceOr<Parameter>]) -> Result<Vec<Parameter>> { let mut resolved = Vec::new(); for param in parameters { resolved.push(self.resolve_parameter(doc_file, param)?); } Ok(resolved) } // only operations from listed input files pub fn operations(&self) -> Result<Vec<WebOperation>> { let mut operations: Vec<WebOperation> = Vec::new(); for (doc_file, doc) in self.docs() { if self.is_input_file(&doc_file) { let paths = self.resolve_path_map(doc_file, doc.paths())?; for (path, item) in &paths { operations.extend(path_operations(doc_file, path, item)) } } } Ok(operations) } } type Result<T, E = Error> = std::result::Result<T, E>; #[derive(Debug, thiserror::Error)] pub enum Error { #[error("PathJoin")] PathJoin { source: path::Error }, #[error("SchemaNotFound {} {}", ref_key.file_path.display(), ref_key.name)] SchemaNotFound { ref_key: RefKey }, #[error("NoNameInReference")] NoNameInReference, #[error("ParameterNotFound")] ParameterNotFound { ref_key: RefKey }, #[error("NotImplemented")] NotImplemented, #[error("ReadFile")] ReadFile { source: std::io::Error, path: PathBuf }, #[error("DeserializeYaml")] DeserializeYaml { source: serde_yaml::Error, path: PathBuf }, #[error("DeserializeJson")] DeserializeJson { source: serde_json::Error, path: PathBuf }, } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct RefKey { pub file_path: PathBuf, pub name: String, } pub struct ResolvedSchema { pub ref_key: Option<RefKey>, pub schema: Schema, } /// Functionality related to Open API definitions pub mod openapi { use super::*; /// Parse an OpenAPI object from a file located at `path` pub fn parse<P: AsRef<Path>>(path: P) -> Result<OpenAPI> { let path = path.as_ref(); let bytes = fs::read(path).map_err(|source| Error::ReadFile { source, path: PathBuf::from(path), })?; let api = if path.extension() == Some(OsStr::new("yaml")) || path.extension() == Some(OsStr::new("yml")) { serde_yaml::from_slice(&bytes).map_err(|source| Error::DeserializeYaml { source, path: PathBuf::from(path), })? } else { serde_json::from_slice(&bytes).map_err(|source| Error::DeserializeJson { source, path: PathBuf::from(path), })? }; Ok(api) } /// Returns a set of referenced relative file paths from an OpenAPI specficiation pub fn get_reference_file_paths<P: AsRef<Path>>(doc_file: P, api: &OpenAPI) -> IndexSet<String> { get_references(doc_file, api) .into_iter() .filter_map(|reference| match reference { TypedReference::Example(_) => None, reference => { let reference: Reference = reference.into(); reference.file } }) .collect() } /// Returns the list of all references contained in an OpenAPI schema pub fn get_references<P: AsRef<Path>>(doc_file: P, api: &OpenAPI) -> Vec<TypedReference> { let mut list = Vec::new(); // paths and operations for (path, item) in api.paths() { match item { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::PathItem(reference.clone())), ReferenceOr::Item(item) => { for operation in path_operations(&doc_file, path, item) { // parameters for param in &operation.parameters { match param { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Parameter(reference.clone())), ReferenceOr::Item(parameter) => match &parameter.schema { Some(ReferenceOr::Reference { reference, .. }) => list.push(TypedReference::Schema(reference.clone())), Some(ReferenceOr::Item(schema)) => add_references_for_schema(&mut list, schema), None => {} }, } } // responses for (_code, rsp) in &operation.responses { match &rsp.schema { Some(ReferenceOr::Reference { reference, .. }) => list.push(TypedReference::Schema(reference.clone())), Some(ReferenceOr::Item(schema)) => add_references_for_schema(&mut list, schema), None => {} } } // examples for (_name, example) in &operation.examples { if let ReferenceOr::Reference { reference, .. } = example { list.push(TypedReference::Example(reference.clone())); } } } } } } // definitions for (_name, schema) in &api.definitions { match schema { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Schema(reference.clone())), ReferenceOr::Item(schema) => add_references_for_schema(&mut list, schema), } } list } /// Get all references related to schemas for an Open API specification pub fn get_api_schema_references(doc_file: &Path, api: &OpenAPI) -> Vec<Reference> { get_references(doc_file, api) .into_iter() .filter_map(|rf| match rf { TypedReference::Schema(rs) => Some(rs), _ => None, }) .collect() } } pub struct WebOperation { pub doc_file: PathBuf, pub id: Option<String>, pub path: String, pub verb: WebVerb, pub parameters: Vec<ReferenceOr<Parameter>>, pub responses: IndexMap<StatusCode, Response>, pub examples: MsExamples, } impl WebOperation { pub fn rust_module_name(&self) -> Option<String> { match &self.id { Some(id) => { let parts: Vec<&str> = id.splitn(2, '_').collect(); if parts.len() == 2 { Some(parts[0].to_snake_case()) } else { None } } None => None, } } pub fn rust_function_name(&self) -> String { match &self.id { Some(id) => { let parts: Vec<&str> = id.splitn(2, '_').collect(); if parts.len() == 2 { parts[1].to_snake_case() } else { parts[0].to_snake_case() } } None => create_function_name(&self.verb, &self.path), } } } pub enum WebVerb { Get, Post, Put, Patch, Delete, Options, Head, } impl<'a> WebVerb { pub fn as_str(&self) -> &'static str { match self { WebVerb::Get => "get", WebVerb::Post => "post", WebVerb::Put => "put", WebVerb::Patch => "patch", WebVerb::Delete => "delete", WebVerb::Options => "options", WebVerb::Head => "head", } } } /// Creating a function name from the path and verb when an operationId is not specified. /// All azure-rest-api-specs operations should have an operationId. fn create_function_name(verb: &WebVerb, path: &str) -> String { let mut path = path.split('/').filter(|&x| !x.is_empty()).collect::<Vec<_>>(); path.insert(0, verb.as_str()); path.join("_") } struct OperationVerb<'a> { pub operation: Option<&'a Operation>, pub verb: WebVerb, } pub fn path_operations<P: AsRef<Path>>(doc_file: P, path: &str, item: &PathItem) -> Vec<WebOperation> { vec![ OperationVerb { operation: item.get.as_ref(), verb: WebVerb::Get, }, OperationVerb { operation: item.post.as_ref(), verb: WebVerb::Post, }, OperationVerb { operation: item.put.as_ref(), verb: WebVerb::Put, }, OperationVerb { operation: item.patch.as_ref(), verb: WebVerb::Patch, }, OperationVerb { operation: item.delete.as_ref(), verb: WebVerb::Delete, }, OperationVerb { operation: item.options.as_ref(), verb: WebVerb::Options, }, OperationVerb { operation: item.head.as_ref(), verb: WebVerb::Head, }, ] .into_iter() .filter_map(|op_verb| match op_verb.operation { Some(op) => { let mut parameters = item.parameters.clone(); parameters.append(&mut op.parameters.clone()); Some(WebOperation { doc_file: doc_file.as_ref().to_path_buf(), id: op.operation_id.clone(), path: path.to_string(), verb: op_verb.verb, parameters, responses: op.responses.clone(), examples: op.x_ms_examples.clone(), }) } None => None, }) .collect() } /// A $ref reference type that knows what type of reference it is #[derive(Clone, Debug, PartialEq)] pub enum TypedReference { PathItem(Reference), Parameter(Reference), Schema(Reference), Example(Reference), } impl From<TypedReference> for Reference { fn from(s: TypedReference) -> Reference { match s { TypedReference::PathItem(r) => r, TypedReference::Parameter(r) => r, TypedReference::Schema(r) => r, TypedReference::Example(r) => r, } } } /// Get all schema references for a given schema pub fn get_schema_schema_references(schema: &Schema) -> Vec<Reference> { let mut refs = Vec::new(); add_references_for_schema(&mut refs, schema); refs.into_iter() .filter_map(|rf| match rf { TypedReference::Schema(rs) => Some(rs), _ => None, }) .collect() } fn add_references_for_schema(list: &mut Vec<TypedReference>, schema: &Schema) { for (_, schema) in &schema.properties { match schema { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Schema(reference.clone())), ReferenceOr::Item(schema) => add_references_for_schema(list, schema), } } if let Some(ap) = schema.additional_properties.as_ref() { match ap { AdditionalProperties::Boolean(_) => {} AdditionalProperties::Schema(schema) => match schema { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Schema(reference.clone())), ReferenceOr::Item(schema) => add_references_for_schema(list, schema), }, } } if let Some(schema) = schema.common.items.as_ref() { match schema { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Schema(reference.clone())), ReferenceOr::Item(schema) => add_references_for_schema(list, schema), } } for schema in &schema.all_of { match schema { ReferenceOr::Reference { reference, .. } => list.push(TypedReference::Schema(reference.clone())), ReferenceOr::Item(schema) => add_references_for_schema(list, schema), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_create_function_name() { assert_eq!(create_function_name(&WebVerb::Get, "/pets"), "get_pets"); } #[test] fn test_function_name_from_operation_id() { let operation = WebOperation { doc_file: PathBuf::from(""), id: Some("PrivateClouds_CreateOrUpdate".to_owned()), path: "/horse".to_owned(), verb: WebVerb::Get, parameters: Vec::new(), responses: IndexMap::new(), examples: IndexMap::new(), }; assert_eq!(Some("private_clouds".to_owned()), operation.rust_module_name()); assert_eq!("create_or_update", operation.rust_function_name()); } #[test] fn test_function_name_from_verb_and_path() { let operation = WebOperation { doc_file: PathBuf::from(""), id: None, path: "/horse".to_owned(), verb: WebVerb::Get, parameters: Vec::new(), responses: IndexMap::new(), examples: IndexMap::new(), }; assert_eq!(None, operation.rust_module_name()); assert_eq!("get_horse", operation.rust_function_name()); } #[test] fn test_function_name_with_no_module_name() { let operation = WebOperation { doc_file: PathBuf::from(""), id: Some("PerformConnectivityCheck".to_owned()), path: "/horse".to_owned(), verb: WebVerb::Put, parameters: Vec::new(), responses: IndexMap::new(), examples: IndexMap::new(), }; assert_eq!(None, operation.rust_module_name()); assert_eq!("perform_connectivity_check", operation.rust_function_name()); } }
mod font; pub mod ui; pub use ui::*; mod hotkey; pub use hotkey::register_hotkey;
use super::Solution; impl Solution { #[allow(dead_code)] pub fn roman_to_int(s: String) -> i32 { let numbers: Vec<i32> = s.chars().map(|ch| { match ch { 'I' => 1, 'V' => 5, 'X' => 10, 'L' => 50, 'C' => 100, 'D' => 500, 'M' => 1000, _ => panic!("invalid") } }).collect(); let mut result = 0; for i in 0..numbers.len() - 1 { let num = numbers[i]; result += if num < numbers[i + 1] { -num } else { num } } result + numbers.last().unwrap() } } #[cfg(test)] mod tests { use super::Solution; #[test] #[ignore] fn s13_test() { assert_eq!(Solution::roman_to_int(String::from("III")), 3); assert_eq!(Solution::roman_to_int(String::from("MCMXCIV")), 1994); } }