text
stringlengths
8
4.13M
use rocket::form::Form; use rocket::fs::TempFile; use rocket::response::{Debug, Flash, Redirect}; use rocket::Route; use crate::db::schema::files; use crate::db::user::UserId; use crate::db::Connection; use diesel; use diesel::prelude::*; use std::error::Error; use std::fs; use std::path::Path; #[derive(Insertable)] #[table_name = "files"] struct NewFile<'a> { name: &'a str, user_id: i32, } #[post("/", data = "<upload>")] async fn upload( connection: Connection, user_id: UserId, mut upload: Form<TempFile<'_>>, ) -> Result<Flash<Redirect>, Debug<Box<dyn Error>>> { let name: String = if let Some(name) = upload.name() { name.into() } else { return Ok(Flash::error( Redirect::to("/"), "Plik nie ma właściwej nazwy.", )); }; let upload_path = Path::new("uploads").join(user_id.0.to_string()); fs::create_dir_all(&upload_path).map_err(|e| Debug(e.into()))?; upload .persist_to(upload_path.join(&name)) .await .map_err(|e| Debug(e.into()))?; diesel::insert_into(files::table) .values(&NewFile { name: &name, user_id: user_id.0, }) .execute(&*connection) .map_err(|e| Debug(e.into()))?; Ok(Flash::success(Redirect::to("/"), "Plik został wrzucony.")) } pub fn routes() -> Vec<Route> { routes![upload] }
use colored::*; use crate::input; pub struct Board { pub field: Vec<Vec<&'static str>>, pub display: Vec<Vec<&'static str>>, width: usize, height: usize, mine_count: usize } impl Board { pub fn create(width: usize, height: usize, mine_count: usize) -> Board { let mut field: Vec<Vec<&'static str>> = vec![vec!["0"; width]; height]; use rand; for _i in 0..mine_count { let x = (rand::random::<f32>() * width as f32) as usize; let y = (rand::random::<f32>() * height as f32) as usize; field[y][x] = "B"; } for y in 0..height { for x in 0 ..width { if field[y][x] != "B" { let mut count = 0; if y > 0 && field[y -1][x] == "B" { count += 1; } if y < height -1 && field[y +1][x] == "B" { count += 1; } if x > 0 && field[y][x -1] == "B" { count += 1; } if x < width -1 && field[y][x +1] == "B" { count += 1; } if y > 0 && x > 0 && field[y -1][x -1] == "B" { count += 1; } if y > 0 && x < width -1 && field[y -1][x +1] == "B" { count += 1; } if y < height -1 && x < width -1 && field[y +1][x +1] == "B" { count += 1; } if y < height -1 && x > 0 && field[y +1][x -1] == "B" { count += 1; } match count { 1 => field[y][x] = "1", 2 => field[y][x] = "2", 3 => field[y][x] = "3", 4 => field[y][x] = "4", 5 => field[y][x] = "5", 6 => field[y][x] = "6", 7 => field[y][x] = "7", 8 => field[y][x] = "8", _ => field[y][x] = "0" } } } } return Board { field, display: vec![vec![" "; width]; height], width, height, mine_count }; } pub fn reveal(&mut self, x: usize, y: usize) { if self.display[y][x] == " " { match self.field[y][x] { "0" => self.reveal_blank(x, y), "B" => { self.print_all(); println!("{}", "Game Over!".red()); use std::process; process::exit(256); }, _ => { self.display[y][x] = self.field[y][x]; } } self.win_check(); } else { self.print(); println!("{}", "Selected position is already revealed or marked".yellow()); } } fn reveal_blank(&mut self, x: usize, y: usize) { if self.display[y][x] == " " { match self.field[y][x] { "0" => { self.display[y][x] = "0"; if y > 0 { self.reveal_blank(x, y -1); } if y < self.height -1 { self.reveal_blank(x, y +1); } if x > 0 { self.reveal_blank(x -1, y); } if x < self.width -1 { self.reveal_blank(x +1, y); } if y > 0 && x > 0 { self.reveal_blank(x -1, y -1); } if y > 0 && x < self.width -1 { self.reveal_blank(x +1, y -1); } if y < self.height -1 && x < self.width -1 { self.reveal_blank(x +1, y +1); } if y < self.height -1 && x > 0 { self.reveal_blank(x -1, y +1); } }, _ => { self.display[y][x] = self.field[y][x]; } } } } pub fn mark(&mut self, x: usize, y: usize) { if self.display[y][x] == " " { self.display[y][x] = "M"; self.print(); } else { self.print(); println!("{}", "Selected position cannot be marked".yellow()); } input::get_command(self); } pub fn un_mark(&mut self, x: usize, y: usize) { if self.display[y][x] == "M" { self.display[y][x] = " "; self.print(); } else { self.print(); println!("{}", "Please select an already marked position".yellow()); } input::get_command(self); } pub fn is_in_bounds(&self, x: usize, y: usize) -> bool { if y >= self.display.len() { return false; } if x >= self.display[y].len() { return false; } return true; } fn win_check(&self) { let mut empty_count = 0; for y in 0..self.height { for x in 0..self.width { if self.display[y][x] == " " || (self.display[y][x] == "M" && self.field[y][x] == "B") { empty_count += 1; } } } if empty_count == self.mine_count { print!("{}[2J", 27 as char); self.print_all(); println!("{}", "Congradulations! You win!".cyan()); use std::process; process::exit(256); } } pub fn print(&self) { print!(" |"); for i in 0..self.width { if i < 10 { print!(" {} |", i.to_string().green()); } else if i < 100 { print!(" {}|", i.to_string().green()); } else { print!("{}|", i.to_string().green()); } } println!(); for _i in 0..self.width { print!("----"); } print!("----"); println!(); for y in 0..self.height { if y < 10 { print!("{} | ", y.to_string().green()); } else if y < 100 { print!("{} | ", y.to_string().green()); } else { print!("{}| ", y.to_string().green()); } for x in 0..self.width { if self.display[y][x] != "B" { print!("{} | ", self.display[y][x].cyan().bold()); } else { print!("{} | ", self.display[y][x].red().bold()); } } println!(); for _i in 0..self.width { print!("----"); } print!("----"); println!(); } } fn print_all(&self) { print!(" |"); for i in 0..self.width { if i < 10 { print!(" {} |", i.to_string().green()); } else if i < 100 { print!(" {}|", i.to_string().green()); } else { print!("{}|", i.to_string().green()); } } println!(); for _i in 0..self.width { print!("----"); } print!("----"); println!(); for y in 0..self.height { if y < 10 { print!("{} | ", y.to_string().green()); } else if y < 100 { print!("{} | ", y.to_string().green()); } else { print!("{}| ", y.to_string().green()); } for x in 0..self.width { if self.field[y][x] != "B" { print!("{} | ", self.field[y][x].cyan().bold()); } else { print!("{} | ", self.field[y][x].red().bold()); } } println!(); for _i in 0..self.width { print!("----"); } print!("----"); println!(); } } }
use crate::{algorithms::Translate, CanvasSpace, DrawingSpace, Point, Vector}; use euclid::Scale; use specs::prelude::*; use specs_derive::Component; #[derive(Debug, Clone, PartialEq, Component)] #[storage(HashMapStorage)] pub struct Viewport { /// The location (in drawing units) this viewport is centred on. pub centre: Point, /// The number of pixels each drawing unit should take up on the screen. pub pixels_per_drawing_unit: Scale<f64, DrawingSpace, CanvasSpace>, } impl crate::algorithms::Scale for Viewport { /// Zoom the viewport, where a positive `scale_factor` will zoom in. fn scale(&mut self, scale_factor: f64) { assert!(scale_factor.is_finite() && scale_factor != 0.0); self.pixels_per_drawing_unit = euclid::Scale::new( self.pixels_per_drawing_unit.get() / scale_factor, ); } } impl Translate<DrawingSpace> for Viewport { fn translate(&mut self, displacement: Vector) { self.centre.translate(displacement); } }
extern crate hacl_star; use hacl_star::hmac; const KEY: &[u8] = b"key"; const INPUT: &[u8] = b"The quick brown fox jumps over the lazy dog"; const OUTPUT: [u8; 32] = [0xf7, 0xbc, 0x83, 0xf4, 0x30, 0x53, 0x84, 0x24, 0xb1, 0x32, 0x98, 0xe6, 0xaa, 0x6f, 0xb1, 0x43, 0xef, 0x4d, 0x59, 0xa1, 0x49, 0x46, 0x17, 0x59, 0x97, 0x47, 0x9d, 0xbc, 0x2d, 0x1a, 0x3c, 0xd8]; #[test] fn test_hmac_sha256() { let mut output = [0; 32]; hmac::hmac_sha256(&mut output, KEY, INPUT); assert_eq!(output, OUTPUT); }
//! Companies Service, presents CRUD operations use diesel::connection::AnsiTransactionManager; use diesel::pg::Pg; use diesel::Connection; use r2d2::ManageConnection; use failure::Error as FailureError; use stq_types::{Alpha3, CompanyId}; use models::companies::{Company, NewCompany, UpdateCompany}; use repos::ReposFactory; use services::types::{Service, ServiceFuture}; pub trait CompaniesService { /// Create a new company fn create_company(&self, payload: NewCompany) -> ServiceFuture<Company>; /// Returns list of companies fn list_companies(&self) -> ServiceFuture<Vec<Company>>; /// Find specific company by ID fn find_company(&self, id: CompanyId) -> ServiceFuture<Option<Company>>; /// Returns list of companies supported by the country fn find_deliveries_from(&self, country: Alpha3) -> ServiceFuture<Vec<Company>>; /// Update a company fn update_company(&self, id: CompanyId, payload: UpdateCompany) -> ServiceFuture<Company>; /// Delete a company fn delete_company(&self, id: CompanyId) -> ServiceFuture<Company>; } impl< T: Connection<Backend = Pg, TransactionManager = AnsiTransactionManager> + 'static, M: ManageConnection<Connection = T>, F: ReposFactory<T>, > CompaniesService for Service<T, M, F> { /// Create a new company fn create_company(&self, payload: NewCompany) -> ServiceFuture<Company> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); conn.transaction::<Company, FailureError, _>(move || { company_repo .create(payload) .map_err(|e| e.context("Service Companies, create endpoint error occured.").into()) }) }) } /// Returns list of companies fn list_companies(&self) -> ServiceFuture<Vec<Company>> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); company_repo .list() .map_err(|e| e.context("Service Companies, list endpoint error occured.").into()) }) } /// Find specific company by ID fn find_company(&self, company_id: CompanyId) -> ServiceFuture<Option<Company>> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); company_repo .find(company_id) .map_err(|e| e.context("Service Companies, find endpoint error occured.").into()) }) } /// Returns list of companies supported by the country fn find_deliveries_from(&self, country: Alpha3) -> ServiceFuture<Vec<Company>> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); company_repo .find_deliveries_from(country) .map_err(|e| e.context("Service Companies, find_deliveries_from endpoint error occured.").into()) }) } /// Update a company fn update_company(&self, id: CompanyId, payload: UpdateCompany) -> ServiceFuture<Company> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); company_repo .update(id, payload) .map_err(|e| e.context("Service Companies, update endpoint error occured.").into()) }) } /// Delete a company fn delete_company(&self, company_id: CompanyId) -> ServiceFuture<Company> { let repo_factory = self.static_context.repo_factory.clone(); let user_id = self.dynamic_context.user_id; self.spawn_on_pool(move |conn| { let company_repo = repo_factory.create_companies_repo(&*conn, user_id); company_repo .delete(company_id) .map_err(|e| e.context("Service Companies, delete endpoint error occured.").into()) }) } }
use std::{fmt, thread, time::Duration}; use crate::System; /// A helper wrapper to run test actors for a certain period. /// /// # Example /// /// ```ignore /// use actor::testing::SystemThread; /// /// SystemThread::run_for(Duration::from_millis(100), |system| { /// system.spawn(SomeActor::new())?; /// }); /// ``` pub struct SystemThread { inner: Option<thread::JoinHandle<()>>, } impl SystemThread { pub fn run_for<F, E: fmt::Debug>(duration: Duration, func: F) -> Self where F: FnOnce(&mut System) -> Result<(), E> + Send + 'static, { Self { inner: Some(thread::spawn(move || { let mut system = System::new("test"); func(&mut system).unwrap(); thread::sleep(duration); system.shutdown().unwrap(); })), } } } impl Drop for SystemThread { fn drop(&mut self) { self.inner.take().unwrap().join().unwrap(); } }
#![cfg(feature = "stream")] #[macro_use] extern crate nom; use nom::{Producer,Consumer,ConsumerState,Input,Move,MemProducer,IResult,HexDisplay}; #[derive(PartialEq,Eq,Debug)] enum State { Beginning, Middle, End, Done, Error } struct TestConsumer { state: State, c_state: ConsumerState<usize,(),Move>, counter: usize, } named!(om_parser, tag!("om")); named!(nomnom_parser<&[u8],Vec<&[u8]> >, many1!(tag!("nom"))); named!(end_parser, tag!("kthxbye")); impl<'a> Consumer<&'a[u8], usize, (), Move> for TestConsumer { fn state(&self) -> &ConsumerState<usize,(),Move> { &self.c_state } fn handle(&mut self, input: Input<&'a [u8]>) -> &ConsumerState<usize,(),Move> { match self.state { State::Beginning => { match input { Input::Empty | Input::Eof(None) => { self.state = State::Error; self.c_state = ConsumerState::Error(()); }, Input::Element(sl) | Input::Eof(Some(sl)) => { match om_parser(sl) { IResult::Error(_) => { self.state = State::Error; self.c_state = ConsumerState::Error(()); }, IResult::Incomplete(n) => { self.c_state = ConsumerState::Continue(Move::Await(n)); }, IResult::Done(i,_) => { self.state = State::Middle; self.c_state = ConsumerState::Continue(Move::Consume(sl.offset(i))); } } } } }, State::Middle => { match input { Input::Empty | Input::Eof(None) => { self.state = State::Error; self.c_state = ConsumerState::Error(()); }, Input::Element(sl) | Input::Eof(Some(sl)) => { match nomnom_parser(sl) { IResult::Error(_) => { self.state = State::End; self.c_state = ConsumerState::Continue(Move::Consume(0)); }, IResult::Incomplete(n) => { self.c_state = ConsumerState::Continue(Move::Await(n)); }, IResult::Done(i,noms_vec) => { self.counter = self.counter + noms_vec.len(); self.state = State::Middle; self.c_state = ConsumerState::Continue(Move::Consume(sl.offset(i))); } } } } }, State::End => { match input { Input::Empty | Input::Eof(None) => { self.state = State::Error; self.c_state = ConsumerState::Error(()); }, Input::Element(sl) | Input::Eof(Some(sl)) => { match end_parser(sl) { IResult::Error(_) => { self.state = State::Error; self.c_state = ConsumerState::Error(()); }, IResult::Incomplete(n) => { self.c_state = ConsumerState::Continue(Move::Await(n)); }, IResult::Done(i,_) => { self.state = State::Done; self.c_state = ConsumerState::Done(Move::Consume(sl.offset(i)), self.counter); } } } } }, State::Done | State::Error => { // this should not be called self.state = State::Error; self.c_state = ConsumerState::Error(()) } }; &self.c_state } } #[test] fn nom1() { let mut p = MemProducer::new(&b"omnomkthxbye"[..], 8); let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; while let &ConsumerState::Continue(Move::Consume(_)) = p.apply(&mut c) { } assert_eq!(c.counter, 1); assert_eq!(c.state, State::Done); } #[test] fn nomnomnom() { let mut p = MemProducer::new(&b"omnomnomnomkthxbye"[..], 8); let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; while let &ConsumerState::Continue(_) = p.apply(&mut c) { } assert_eq!(c.counter, 3); assert_eq!(c.state, State::Done); } #[test] fn no_nomnom() { let mut p = MemProducer::new(&b"omkthxbye"[..], 8); let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; while let &ConsumerState::Continue(_) = p.apply(&mut c) { } assert_eq!(c.counter, 0); assert_eq!(c.state, State::Done); } #[test] fn impolite() { let mut p = MemProducer::new(&b"omnomnomnom"[..], 4); let mut c = TestConsumer{state: State::Beginning, counter: 0, c_state: ConsumerState::Continue(Move::Consume(0))}; while let &ConsumerState::Continue(Move::Consume(ref c)) = p.apply(&mut c) { println!("consume {:?}", c); } assert_eq!(c.counter, 3); assert_eq!(c.state, State::End); }
use actionable::Permissions; use custodian_password::{ LoginFinalization, LoginRequest, LoginResponse, RegistrationFinalization, RegistrationRequest, RegistrationResponse, }; use schema::SchemaName; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use crate::{ connection::{AccessPolicy, Database, QueryKey}, document::Document, kv::{KeyOperation, Output}, schema::{ self, view::{self, map}, CollectionName, Key, MappedValue, NamedReference, ViewName, }, transaction::{Executed, OperationResult, Transaction}, }; /// A payload with an associated id. #[derive(Clone, Deserialize, Serialize, Debug)] pub struct Payload<T> { /// The unique id for this payload. pub id: Option<u32>, /// The wrapped payload. pub wrapped: T, } /// A request made to a server. #[derive(Clone, Deserialize, Serialize, Debug)] #[cfg_attr(feature = "actionable-traits", derive(actionable::Actionable))] pub enum Request<T> { /// A server-related request. #[cfg_attr(feature = "actionable-traits", actionable(protection = "none"))] Server(ServerRequest), /// A database-related request. #[cfg_attr(feature = "actionable-traits", actionable(protection = "none"))] Database { /// The name of the database. database: String, /// The request made to the database. request: DatabaseRequest, }, /// A database-related request. #[cfg_attr( feature = "actionable-traits", actionable(protection = "none", subaction) )] Api(T), } /// A server-related request. #[derive(Clone, Deserialize, Serialize, Debug)] #[cfg_attr(feature = "actionable-traits", derive(actionable::Actionable))] pub enum ServerRequest { /// Authenticates the current session as `username` using a password. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] LoginWithPassword { /// The username of the user to authenticate as. username: String, /// The password login request. login_request: LoginRequest, }, /// Completes logging in via `LoginWithPassword`. #[cfg_attr(feature = "actionable-traits", actionable(protection = "none"))] FinishPasswordLogin { /// The payload required to complete logging in. login_finalization: LoginFinalization, }, /// Creates a database. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] CreateDatabase(Database), /// Deletes the database named `name` #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] DeleteDatabase { /// The name of the database to delete. name: String, }, /// Lists all databases. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] ListDatabases, /// Lists available schemas. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] ListAvailableSchemas, /// Creates a user. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] CreateUser { /// The unique username of the user to create. username: String, }, /// Sets a user's password. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] SetPassword { /// The username or id of the user to set the password for. user: NamedReference<'static>, /// A registration request for a password. password_request: RegistrationRequest, }, /// Finishes setting the password for a user. #[cfg_attr(feature = "actionable-traits", actionable(protection = "none"))] FinishSetPassword { /// The username or id of the user to set the password for. user: NamedReference<'static>, /// The finalization payload for the password change. password_finalization: RegistrationFinalization, }, /// Alter's a user's membership in a permission group. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] AlterUserPermissionGroupMembership { /// The username or id of the user. user: NamedReference<'static>, /// The name or id of the group. group: NamedReference<'static>, /// Whether the user should be in the group. should_be_member: bool, }, /// Alter's a user's role #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] AlterUserRoleMembership { /// The username or id of the user. user: NamedReference<'static>, /// The name or id of the role. role: NamedReference<'static>, /// Whether the user should have the role. should_be_member: bool, }, } /// A database-related request. #[derive(Clone, Deserialize, Serialize, Debug)] #[cfg_attr(feature = "actionable-traits", derive(actionable::Actionable))] pub enum DatabaseRequest { /// Retrieve a single document. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] Get { /// The collection of the document. collection: CollectionName, /// The id of the document. id: u64, }, /// Retrieve multiple documents. #[cfg_attr(feature = "actionable-traits", actionable(protection = "custom"))] GetMultiple { /// The collection of the documents. collection: CollectionName, /// The ids of the documents. ids: Vec<u64>, }, /// Queries a view. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] Query { /// The name of the view. view: ViewName, /// The filter for the view. key: Option<QueryKey<Vec<u8>>>, /// The access policy for the query. access_policy: AccessPolicy, /// If true, [`DatabaseResponse::ViewMappingsWithDocs`] will be /// returned. If false, [`DatabaseResponse::ViewMappings`] will be /// returned. with_docs: bool, }, /// Reduces a view. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] Reduce { /// The name of the view. view: ViewName, /// The filter for the view. key: Option<QueryKey<Vec<u8>>>, /// The access policy for the query. access_policy: AccessPolicy, /// Whether to return a single value or values grouped by unique key. If /// true, [`DatabaseResponse::ViewGroupedReduction`] will be returned. /// If false, [`DatabaseResponse::ViewReduction`] is returned. grouped: bool, }, /// Applies a transaction. #[cfg_attr(feature = "actionable-traits", actionable(protection = "custom"))] ApplyTransaction { /// The trasnaction to apply. transaction: Transaction<'static>, }, /// Lists executed transactions. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] ListExecutedTransactions { /// The starting transaction id. starting_id: Option<u64>, /// The maximum number of results. result_limit: Option<usize>, }, /// Queries the last transaction id. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] LastTransactionId, /// Creates a `PubSub` [`Subscriber`](crate::pubsub::Subscriber) #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] CreateSubscriber, /// Publishes `payload` to all subscribers of `topic`. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] Publish { /// The topics to publish to. topic: String, /// The payload to publish. payload: Vec<u8>, }, /// Publishes `payload` to all subscribers of all `topics`. #[cfg_attr(feature = "actionable-traits", actionable(protection = "custom"))] PublishToAll { /// The topics to publish to. topics: Vec<String>, /// The payload to publish. payload: Vec<u8>, }, /// Subscribes `subscriber_id` to messages for `topic`. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] SubscribeTo { /// The id of the [`Subscriber`](crate::pubsub::Subscriber). subscriber_id: u64, /// The topic to subscribe to. topic: String, }, /// Unsubscribes `subscriber_id` from messages for `topic`. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] UnsubscribeFrom { /// The id of the [`Subscriber`](crate::pubsub::Subscriber). subscriber_id: u64, /// The topic to unsubscribe from. topic: String, }, /// Unregisters the subscriber. #[cfg_attr(feature = "actionable-traits", actionable(protection = "none"))] UnregisterSubscriber { /// The id of the [`Subscriber`](crate::pubsub::Subscriber). subscriber_id: u64, }, /// Excutes a key-value store operation. #[cfg_attr(feature = "actionable-traits", actionable(protection = "simple"))] ExecuteKeyOperation(KeyOperation), } /// A response from a server. #[derive(Clone, Serialize, Deserialize, Debug)] pub enum Response<T> { /// A request succeded but provided no output. Ok, /// A response to a [`ServerRequest`]. Server(ServerResponse), /// A response to a [`DatabaseRequest`]. Database(DatabaseResponse), /// A response to an Api request. Api(T), /// An error occurred processing a request. Error(crate::Error), } /// A response to a [`ServerRequest`]. #[derive(Clone, Serialize, Deserialize, Debug)] pub enum ServerResponse { /// A database with `name` was successfully created. DatabaseCreated { /// The name of the database to create. name: String, }, /// A database with `name` was successfully removed. DatabaseDeleted { /// The name of the database to remove. name: String, }, /// A list of available databases. Databases(Vec<Database>), /// A list of availble schemas. AvailableSchemas(Vec<SchemaName>), /// A user was created. UserCreated { /// The id of the user created. id: u64, }, /// Asks the client to complete the password change. This process ensures /// the server receives no information that can be used to derive /// information about the password. FinishSetPassword { /// The password registration response. Must be finalized using /// `custodian-password`. password_reponse: Box<RegistrationResponse>, }, /// A response to a password login attempt. PasswordLoginResponse { /// The server's response to the provided [`LoginRequest`]. response: Box<LoginResponse>, }, /// Successfully authenticated. LoggedIn { /// The effective permissions for the authenticated user. permissions: Permissions, }, } /// A response to a [`DatabaseRequest`]. #[derive(Clone, Serialize, Deserialize, Debug)] pub enum DatabaseResponse { /// One or more documents. Documents(Vec<Document<'static>>), /// Results of [`DatabaseRequest::ApplyTransaction`]. TransactionResults(Vec<OperationResult>), /// Results of [`DatabaseRequest::Query`] when `with_docs` is false. ViewMappings(Vec<map::Serialized>), /// Results of [`DatabaseRequest::Query`] when `with_docs` is true. ViewMappingsWithDocs(Vec<MappedDocument>), /// Result of [`DatabaseRequest::Reduce`] when `grouped` is false. ViewReduction(Vec<u8>), /// Result of [`DatabaseRequest::Reduce`] when `grouped` is true. ViewGroupedReduction(Vec<MappedValue<Vec<u8>, Vec<u8>>>), /// Results of [`DatabaseRequest::ListExecutedTransactions`]. ExecutedTransactions(Vec<Executed<'static>>), /// Result of [`DatabaseRequest::LastTransactionId`]. LastTransactionId(Option<u64>), /// A new `PubSub` subscriber was created. SubscriberCreated { /// The unique ID of the subscriber. subscriber_id: u64, }, /// A PubSub message was received. MessageReceived { /// The ID of the subscriber receiving the message. subscriber_id: u64, /// The topic the payload was received on. topic: String, /// The message payload. payload: Vec<u8>, }, /// Output from a [`KeyOperation`] being executed. KvOutput(Output), } /// A serialized [`MappedDocument`](map::MappedDocument). #[derive(Clone, Serialize, Deserialize, Debug)] pub struct MappedDocument { /// The serialized key. pub key: Vec<u8>, /// The serialized value. pub value: Vec<u8>, /// The source document. pub source: Document<'static>, } impl MappedDocument { /// Deserialize into a [`MappedDocument`](map::MappedDocument). pub fn deserialized<K: Key, V: Serialize + DeserializeOwned>( self, ) -> Result<map::MappedDocument<K, V>, crate::Error> { let key = Key::from_big_endian_bytes(&self.key).map_err(|err| { crate::Error::Database(view::Error::KeySerialization(err).to_string()) })?; let value = serde_cbor::from_slice(&self.value) .map_err(|err| crate::Error::Database(view::Error::from(err).to_string()))?; Ok(map::MappedDocument { document: self.source, key, value, }) } } /// A networking error. #[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)] pub enum Error { /// The server responded with a message that wasn't expected for the request /// sent. #[error("unexpected response: {0}")] UnexpectedResponse(String), /// The connection was interrupted. #[error("unexpected disconnection")] Disconnected, }
// 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 criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; use rand::Rng; use std::time::Duration; use winter_math::{fft, fields::f128::BaseElement, polynom, FieldElement}; const SIZES: [usize; 3] = [262_144, 524_288, 1_048_576]; fn syn_div(c: &mut Criterion) { let mut group = c.benchmark_group("syn_div"); group.sample_size(10); group.measurement_time(Duration::from_secs(10)); for &size in SIZES.iter() { let stride = 8; let mut values = BaseElement::prng_vector(get_seed(), size); for v in values.iter_mut().skip(stride) { *v = BaseElement::ZERO; } let inv_twiddles = fft::get_inv_twiddles::<BaseElement>(size); fft::interpolate_poly(&mut values, &inv_twiddles); let p = values; let z_power = size / stride; group.bench_function(BenchmarkId::new("high_degree", size), |bench| { bench.iter_batched_ref( || p.clone(), |mut p| polynom::syn_div(&mut p, z_power, BaseElement::ONE), BatchSize::LargeInput, ); }); } group.finish(); } criterion_group!(polynom_group, syn_div); criterion_main!(polynom_group); fn get_seed() -> [u8; 32] { rand::thread_rng().gen::<[u8; 32]>() }
use std::net::{TcpStream}; use std::io::{Read, Write}; use std::str::from_utf8; fn main() { match TcpStream::connect("localhost:5044") { Ok(mut stream) => { println!("Successfully connected"); let msg = b"Hello"; stream.write(msg).unwrap(); let mut data = [0 as u8; 2]; match stream.read(&mut data) { Ok(_) => { println!("reply info:{:?}", from_utf8(&data).unwrap()) }, Err(e) => { println!("Failed to receive data: {}", e); } } }, Err(e) => { println!("Failed to connect: {}", e); } } println!("Terminated."); }
// SPDX-FileCopyrightText: 2020-2021 HH Partners // // SPDX-License-Identifier: MIT use serde::{Deserialize, Serialize}; use crate::SPDXExpression; /// https://spdx.github.io/spdx-spec/5-snippet-information/ #[derive(Serialize, Deserialize, Debug, PartialEq)] pub struct Snippet { /// https://spdx.github.io/spdx-spec/5-snippet-information/#51-snippet-spdx-identifier #[serde(rename = "SPDXID")] pub snippet_spdx_identifier: String, /// https://spdx.github.io/spdx-spec/5-snippet-information/#52-snippet-from-file-spdx-identifier #[serde(rename = "snippetFromFile")] pub snippet_from_file_spdx_identifier: String, /// https://spdx.github.io/spdx-spec/5-snippet-information/#53-snippet-byte-range pub ranges: Vec<Range>, /// https://spdx.github.io/spdx-spec/5-snippet-information/#55-snippet-concluded-license #[serde(rename = "licenseConcluded")] pub snippet_concluded_license: SPDXExpression, /// https://spdx.github.io/spdx-spec/5-snippet-information/#56-license-information-in-snippet #[serde( rename = "licenseInfoInSnippets", skip_serializing_if = "Vec::is_empty", default )] pub license_information_in_snippet: Vec<String>, /// https://spdx.github.io/spdx-spec/5-snippet-information/#57-snippet-comments-on-license #[serde( rename = "licenseComments", skip_serializing_if = "Option::is_none", default )] pub snippet_comments_on_license: Option<String>, /// https://spdx.github.io/spdx-spec/5-snippet-information/#58-snippet-copyright-text #[serde(rename = "copyrightText")] pub snippet_copyright_text: String, /// https://spdx.github.io/spdx-spec/5-snippet-information/#59-snippet-comment #[serde(rename = "comment", skip_serializing_if = "Option::is_none", default)] pub snippet_comment: Option<String>, /// https://spdx.github.io/spdx-spec/5-snippet-information/#510-snippet-name #[serde(rename = "name", skip_serializing_if = "Option::is_none", default)] pub snippet_name: Option<String>, /// https://spdx.github.io/spdx-spec/5-snippet-information/#511-snippet-attribution-text #[serde( rename = "attributionText", skip_serializing_if = "Option::is_none", default )] pub snippet_attribution_text: Option<String>, } /// https://spdx.github.io/spdx-spec/5-snippet-information/#53-snippet-byte-range #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct Range { pub start_pointer: StartPointer, pub end_pointer: EndPointer, } /// https://spdx.github.io/spdx-spec/5-snippet-information/#53-snippet-byte-range #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct StartPointer { pub reference: Option<String>, pub offset: Option<i32>, pub line_number: Option<i32>, } /// https://spdx.github.io/spdx-spec/5-snippet-information/#53-snippet-byte-range #[derive(Serialize, Deserialize, Debug, PartialEq)] #[serde(rename_all = "camelCase")] pub struct EndPointer { pub reference: Option<String>, pub offset: Option<i32>, pub line_number: Option<i32>, }
pub struct Task { pub name: &'static str, } pub struct TaskStatus; #[cfg(test)] mod test { }
use crate::asset::*; use crate::reader::*; use crate::util::*; use anyhow::*; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; use std::io::Cursor; #[derive(Debug)] pub struct Name { pub index: u32, pub name: String, // Size as a uint32, then null terminated string pub non_case_preserving_hash: u16, // idk how this is calculated, idk if it matters pub case_preserving_hash: u16, // ditto } impl Name { fn read(rdr: &mut ByteReader) -> Result<Self> { let name = read_string(rdr)?; let non_case_preserving_hash = rdr.read_u16::<LittleEndian>()?; let case_preserving_hash = rdr.read_u16::<LittleEndian>()?; Ok(Name { index: 0, name, non_case_preserving_hash, case_preserving_hash, }) } fn write(&self, curs: &mut Cursor<Vec<u8>>) -> Result<()> { write_string(curs, &self.name)?; curs.write_u16::<LittleEndian>(self.non_case_preserving_hash)?; curs.write_u16::<LittleEndian>(self.case_preserving_hash)?; Ok(()) } } #[derive(Debug, Clone, PartialEq)] pub struct NameVariant { pub name_idx: usize, // Reference into Names pub variant: u32, } impl NameVariant { pub fn new(name: &str, variant: u32, names: &Names) -> Self { let pos = names.expect(name); Self { name_idx: pos, variant, } } /// Parses a string to a NameVariant /// /// Strings like SomeName_6 are turned into a NameVariant with variant = 6. pub fn parse(txt: &str, names: &Names) -> Self { let pieces: Vec<&str> = txt.split('_').collect(); let len = pieces.len(); if len > 1 { if let Ok(variant) = pieces[len - 1].parse::<u32>() { let name: String = pieces[0..len - 1].join("_"); return Self::new(&name, variant, names); } } Self::new(txt, 0, names) } /// Parses a string to a NameVariant, adding the name to the name list /// if necessary. pub fn parse_and_add(txt: &str, names: &mut Names) -> Self { let pieces: Vec<&str> = txt.split('_').collect(); let len = pieces.len(); // TODO refactor this to remove default value duplication let (name, variant) = if len > 1 { if let Ok(variant) = pieces[len - 1].parse::<u32>() { let name: String = pieces[0..len - 1].join("_"); (name, variant) } else { (txt.to_string(), 0) } } else { (txt.to_string(), 0) }; names.add(&name); Self::new(txt, variant, names) } pub fn read(rdr: &mut ByteReader, names: &Names) -> Result<Self> { let start_pos = rdr.position(); let index = rdr.read_u32::<LittleEndian>()?; let name = names .lookup(index) .map(|x| x.name.clone()) .with_context(|| format!("Failed parsing NameVariant starting at {:#X}", start_pos))?; let variant = read_u32(rdr)?; Ok(Self::new(&name, variant, names)) } pub fn write(&self, curs: &mut Cursor<Vec<u8>>, _names: &Names) -> Result<()> { write_u32(curs, self.name_idx as u32)?; write_u32(curs, self.variant)?; Ok(()) } pub fn to_string(&self, names: &Names) -> String { let name = &names.names[self.name_idx]; if self.variant == 0 { name.name.clone() } else { format!("{}_{}", name.name, self.variant) } } } #[derive(Debug)] pub struct Names { pub names: Vec<Name>, } impl Names { pub fn read(rdr: &mut ByteReader, summary: &FileSummary) -> Result<Self> { if rdr.position() != summary.name_offset as u64 { bail!( "Wrong name map starting position: Expected to be at position {:#X}, but I'm at position {:#X}", summary.name_offset, rdr.position() ); } let mut names = vec![]; for i in 0..summary.name_count { let start_pos = rdr.position(); let mut name = Name::read(rdr) .with_context(|| format!("Failed to parse name starting at {:#X}", start_pos))?; name.index = i; names.push(name); } Ok(Names { names }) } pub fn write(&self, curs: &mut Cursor<Vec<u8>>) -> Result<()> { for name in self.names.iter() { name.write(curs)?; } Ok(()) } pub fn byte_size(&self) -> usize { // Size of each is 8 + (len(name) + 1) let mut size = 0; for name in self.names.iter() { size += 8 + name.name.len() + 1; } size } pub fn get_name_obj(&self, name: &str) -> Option<&Name> { for own_name in self.names.iter() { if own_name.name == name { return Some(own_name); } } None } pub fn lookup(&self, index: u32) -> Result<&Name> { if index > self.names.len() as u32 { bail!( "Name index {} is not in names (length {})", index, self.names.len() ); } Ok(&self.names[index as usize]) } pub fn add(&mut self, name: &str) -> bool { // No-op if name already exists if self.get_name_obj(name).is_some() { return false; } let index = self.names.len() as u32; let name_obj = Name { index, name: name.to_string(), non_case_preserving_hash: 0, case_preserving_hash: 0, }; self.names.push(name_obj); true } /// Checks that name is in the names map and returns its position. Otherwise /// panics. /// /// # Panics /// /// If name is not in this Names. pub fn expect(&self, name: &str) -> usize { let name = name.to_string(); if let Some(pos) = self.names.iter().position(|other| other.name == name) { pos } else { panic!("Missing name '{}' in Names", name) } } }
const DNS_CLASS_IN: u16 = 1; const DNS_HEADER_SIZE: usize = 12; const DNS_MAX_HOSTNAME_LEN: usize = 256; const DNS_MAX_PACKET_SIZE: usize = 65_535; const DNS_OFFSET_QUESTION: usize = DNS_HEADER_SIZE; const DNS_TYPE_OPT: u16 = 41; #[inline] fn qdcount(packet: &[u8]) -> u16 { (u16::from(packet[4]) << 8) | u16::from(packet[5]) } #[inline] fn ancount(packet: &[u8]) -> u16 { (u16::from(packet[6]) << 8) | u16::from(packet[7]) } #[inline] fn nscount(packet: &[u8]) -> u16 { (u16::from(packet[8]) << 8) | u16::from(packet[9]) } #[inline] fn arcount(packet: &[u8]) -> u16 { (u16::from(packet[10]) << 8) | u16::from(packet[11]) } fn skip_name(packet: &[u8], offset: usize) -> Result<(usize, u16), &'static str> { let packet_len = packet.len(); if offset >= packet_len - 1 { return Err("Short packet"); } let mut name_len: usize = 0; let mut offset = offset; let mut labels_count = 0u16; loop { let label_len = match packet[offset] { len if len & 0xc0 == 0xc0 => { if 2 > packet_len - offset { return Err("Incomplete offset"); } offset += 2; break; } len if len > 0x3f => return Err("Label too long"), len => len, } as usize; if label_len >= packet_len - offset - 1 { return Err("Malformed packet with an out-of-bounds name"); } name_len += label_len + 1; if name_len > DNS_MAX_HOSTNAME_LEN { return Err("Name too long"); } offset += label_len + 1; if label_len == 0 { break; } labels_count += 1; } Ok((offset, labels_count)) } pub fn min_ttl( packet: &[u8], min_ttl: u32, max_ttl: u32, failure_ttl: u32, ) -> Result<u32, &'static str> { if qdcount(packet) != 1 { return Err("Unsupported number of questions"); } let packet_len = packet.len(); if packet_len <= DNS_OFFSET_QUESTION { return Err("Short packet"); } if packet_len >= DNS_MAX_PACKET_SIZE { return Err("Large packet"); } let mut offset = match skip_name(packet, DNS_OFFSET_QUESTION) { Ok(offset) => offset.0, Err(e) => return Err(e), }; assert!(offset > DNS_OFFSET_QUESTION); if 4 > packet_len - offset { return Err("Short packet"); } offset += 4; let ancount = ancount(packet); let nscount = nscount(packet); let arcount = arcount(packet); let rrcount = ancount + nscount + arcount; let mut found_min_ttl = if rrcount > 0 { max_ttl } else { failure_ttl }; for _ in 0..rrcount { offset = match skip_name(packet, offset) { Ok(offset) => offset.0, Err(e) => return Err(e), }; if 10 > packet_len - offset { return Err("Short packet"); } let qtype = u16::from(packet[offset]) << 8 | u16::from(packet[offset + 1]); let qclass = u16::from(packet[offset + 2]) << 8 | u16::from(packet[offset + 3]); let ttl = u32::from(packet[offset + 4]) << 24 | u32::from(packet[offset + 5]) << 16 | u32::from(packet[offset + 6]) << 8 | u32::from(packet[offset + 7]); let rdlen = (u16::from(packet[offset + 8]) << 8 | u16::from(packet[offset + 9])) as usize; offset += 10; if !(qtype == DNS_TYPE_OPT && qclass == DNS_CLASS_IN) { if ttl < found_min_ttl { found_min_ttl = ttl; } } if rdlen > packet_len - offset { return Err("Record length would exceed packet length"); } offset += rdlen; } if found_min_ttl < min_ttl { found_min_ttl = min_ttl; } if offset != packet_len { return Err("Garbage after packet"); } Ok(found_min_ttl) }
extern crate chrono; use std::process::Command; use worker::{Request, Response, Period}; use self::chrono::UTC; pub struct Processor; impl Processor { pub fn run (request: Request) -> Response { // starting process let started_at = UTC::now(); let mut command = Command::new("sh"); command.arg("-c"); command.arg(request.command.clone()); command.current_dir(request.cwd.clone()); match command.output() { Err(_) => { let finished_at = UTC::now(); // create response Response { stderr: "could not execute".to_string(), stdout: "".to_string(), status: 1i32, period: Period { started_at: started_at, finished_at: finished_at } } }, Ok(output) => { let stdout = output.stdout; let stderr = output.stderr; let finished_at = UTC::now(); // create response Response { stderr: String::from_utf8(stderr.clone()).ok().expect("cannot convert stderr to string"), stdout: String::from_utf8(stdout.clone()).ok().expect("cannot convert stdout to string"), status: output.status.code().unwrap(), period: Period { started_at: started_at, finished_at: finished_at } } } } } }
#[macro_use] extern crate lazy_static; extern crate html5ever; extern crate regex; extern crate reqwest; extern crate url; pub mod html; pub mod http; pub mod utils;
use num_traits::Float; use crate::solver::{SliceLike, SliceRef, Operator}; use crate::{LinAlgEx, splitm}; // /// Matrix type and size #[derive(Debug, Clone, Copy, PartialEq)] pub enum MatType { /// General matrix with a number of rows and a number of columns. General(usize, usize), /// Symmetric matrix, supplied in packed form, with a number of rows and columns. SymPack(usize), } impl MatType { /// Length of array to store a [`MatType`] matrix. /// /// Returns the length. pub fn len(&self) -> usize { match self { MatType::General(n_row, n_col) => n_row * n_col, MatType::SymPack(n) => n * (n + 1) / 2, } } /// Size of a [`MatType`] matrix. /// /// Returns a tuple of a number of rows and a number of columns. pub fn size(&self) -> (usize, usize) { match self { MatType::General(n_row, n_col) => (*n_row, *n_col), MatType::SymPack(n) => (*n, *n), } } } // /// Matrix operator /// /// <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> /// <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js"></script> /// /// Matrix struct which borrows a slice of data array and implements [`Operator`]. #[derive(Debug)] pub struct MatOp<'a, L: LinAlgEx> { typ: MatType, array: SliceRef<'a, L::Sl> } impl<'a, L: LinAlgEx> MatOp<'a, L> { /// Creates an instance /// /// Returns [`MatOp`] instance. /// * `typ`: Matrix type and size. /// * `array`: data array slice. /// Column-major matrix data shall be stored if [`MatType::General`]. /// Symmetric packed form (the upper-triangular part in column-wise) of matrix data shall be stored if [`MatType::SymPack`]. pub fn new(typ: MatType, array: &'a[L::F]) -> Self { assert_eq!(typ.len(), array.len()); MatOp { typ, array: L::Sl::new_ref(array) } } fn op_impl(&self, transpose: bool, alpha: L::F, x: &L::Sl, beta: L::F, y: &mut L::Sl) { match self.typ { MatType::General(nr, nc) => { if nr > 0 && nc > 0 { L::transform_ge(transpose, nr, nc, alpha, &self.array, x, beta, y) } else { L::scale(beta, y); } }, MatType::SymPack(n) => { if n > 0 { L::transform_sp(n, alpha, &self.array, x, beta, y) } else { L::scale(beta, y); } }, } } fn absadd_impl(&self, colwise: bool, y: &mut L::Sl) { match self.typ { MatType::General(nr, nc) => { if colwise { assert_eq!(nc, y.len()); for (i, e) in y.get_mut().iter_mut().enumerate() { splitm!(self.array, (_t; i * nr), (col; nr)); *e = L::abssum(&col, 1) + *e; } } else { assert_eq!(nr, y.len()); for (i, e) in y.get_mut().iter_mut().enumerate() { splitm!(self.array, (_t; i), (row; nr * nc - i)); *e = L::abssum(&row, nr) + *e; } } }, MatType::SymPack(n) => { assert_eq!(n, y.len()); let y_mut = y.get_mut(); let mut sum = 0; for n in 0.. { splitm!(self.array, (_t; sum), (col; n + 1)); sum += n + 1; y_mut[n] = L::abssum(&col, 1) + y_mut[n]; let col_ref = col.get_ref(); for i in 0.. n { y_mut[i] = y_mut[i] + col_ref[i].abs(); } if sum == self.array.len() { break; } } }, } } } impl<'a, L: LinAlgEx> Operator<L> for MatOp<'a, L> { fn size(&self) -> (usize, usize) { self.typ.size() } fn op(&self, alpha: L::F, x: &L::Sl, beta: L::F, y: &mut L::Sl) { self.op_impl(false, alpha, x, beta, y); } fn trans_op(&self, alpha: L::F, x: &L::Sl, beta: L::F, y: &mut L::Sl) { self.op_impl(true, alpha, x, beta, y); } fn absadd_cols(&self, tau: &mut L::Sl) { self.absadd_impl(true, tau); } fn absadd_rows(&self, sigma: &mut L::Sl) { self.absadd_impl(false, sigma); } } impl<'a, L: LinAlgEx> AsRef<[L::F]> for MatOp<'a, L> { fn as_ref(&self) -> &[L::F] { self.array.get_ref() } } // #[test] fn test_matop1() { use float_eq::assert_float_eq; use crate::FloatGeneric; type L = FloatGeneric<f64>; let array = &[ // column-major, upper-triangle (seen as if transposed) 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 13., 14., 15., ]; let ref_array = &[ 1., 2., 4., 7., 11., 2., 3., 5., 8., 12., 4., 5., 6., 9., 13., 7., 8., 9., 10., 14., 11., 12., 13., 14., 15., ]; let x = &mut[0.; 5]; let y = &mut[0.; 5]; let m = MatOp::<L>::new(MatType::SymPack(5), array); for i in 0.. x.len() { x[i] = 1.; m.op(1., x, 0., y); assert_float_eq!(y.as_ref(), ref_array[i * 5 .. i * 5 + 5].as_ref(), abs_all <= 1e-3); x[i] = 0.; } }
pub mod simple; pub mod spsc;
struct Complex { real: i32, imaginary: i32 } //fn add_complex(c1: Complex, c2: Complex) -> Complex { fn add_complex(c1: &Complex, c2: &Complex) -> Complex { let r = c1.real + c2.real; let i = c1.imaginary + c2.imaginary; return Complex { real: r, imaginary: i }; } fn square_complex_inplace(c: &mut Complex) { let r = c.real * c.real - c.imaginary * c.imaginary; let i = c.real * c.imaginary + c.imaginary * c.real; c.real = r; c.imaginary = i; } fn main() { let cmplx1 = Complex { real: 7, imaginary: 2 }; let cmplx2 = Complex { real: 3, imaginary: 1 }; //let ans = add_complex(cmplx1, cmplx2); // No issues, unless we use cmplx1 or cmplx2 later let mut ans = add_complex(&cmplx1, &cmplx2); println!("The answer is {}+{}i", ans.real, ans.imaginary); println!("{}+{}i + {}+{}i = {}+{}i", cmplx1.real, cmplx1.imaginary, cmplx2.real, cmplx2.imaginary, ans.real, ans.imaginary); square_complex_inplace(&mut ans); println!("The answer squared is {}+{}i", ans.real, ans.imaginary); }
//! Functions and types related to windows. use controls::Control; use ffi_utils::{self, Text}; use libc::{c_int, c_void}; use std::cell::RefCell; use std::ffi::CString; use std::mem; use ui_sys::{self, uiControl, uiWindow}; thread_local! { static WINDOWS: RefCell<Vec<Window>> = RefCell::new(Vec::new()) } define_control_alt!(Window, uiWindow, ui_window); impl Window { #[inline] pub fn as_ui_window(&self) -> *mut uiWindow { self.ui_window } #[inline] pub fn title(&self) -> Text { ffi_utils::ensure_initialized(); unsafe { Text::new(ui_sys::uiWindowTitle(self.ui_window)) } } #[inline] pub fn set_title(&self, title: &str) { ffi_utils::ensure_initialized(); unsafe { let c_string = CString::new(title.as_bytes().to_vec()).unwrap(); ui_sys::uiWindowSetTitle(self.ui_window, c_string.as_ptr()) } } #[inline] pub fn on_closing(&self, callback: Box<FnMut(&Window) -> bool>) { ffi_utils::ensure_initialized(); unsafe { let mut data: Box<Box<FnMut(&Window) -> bool>> = Box::new(callback); ui_sys::uiWindowOnClosing(self.ui_window, c_callback, &mut *data as *mut Box<FnMut(&Window) -> bool> as *mut c_void); mem::forget(data); } extern "C" fn c_callback(window: *mut uiWindow, data: *mut c_void) -> i32 { unsafe { let window = Window { ui_window: window, }; mem::transmute::<*mut c_void, Box<Box<FnMut(&Window) -> bool>>>(data)(&window) as i32 } } } #[inline] pub fn set_child(&self, child: Control) { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowSetChild(self.ui_window, child.as_ui_control()) } } #[inline] pub fn margined(&self) -> bool { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowMargined(self.ui_window) != 0 } } #[inline] pub fn set_margined(&self, margined: bool) { ffi_utils::ensure_initialized(); unsafe { ui_sys::uiWindowSetMargined(self.ui_window, margined as c_int) } } pub fn set_autosave(&self, name: &str) { ffi_utils::ensure_initialized(); unsafe { let c_string = CString::new(name.as_bytes().to_vec()).unwrap(); ui_sys::uiWindowSetAutosave(self.ui_window, c_string.as_ptr()) } } #[inline] pub fn new(title: &str, width: c_int, height: c_int, has_menubar: bool) -> Window { ffi_utils::ensure_initialized(); unsafe { let c_string = CString::new(title.as_bytes().to_vec()).unwrap(); let window = Window::from_ui_window(ui_sys::uiNewWindow(c_string.as_ptr(), width, height, has_menubar as c_int)); WINDOWS.with(|windows| windows.borrow_mut().push(window.clone())); window } } #[inline] pub unsafe fn from_ui_window(window: *mut uiWindow) -> Window { Window { ui_window: window, } } pub unsafe fn destroy_all_windows() { WINDOWS.with(|windows| { let mut windows = windows.borrow_mut(); for window in windows.drain(..) { window.destroy() } }) } } // Defines a new control, creating a Rust wrapper, a `Deref` implementation, and a destructor. // An example of use: // // define_control!(Slider, uiSlider, ui_slider) #[macro_export] macro_rules! define_control_alt { ($rust_type:ident, $ui_type:ident, $ui_field:ident) => { pub struct $rust_type { $ui_field: *mut $ui_type, } impl ::std::ops::Deref for $rust_type { type Target = ::controls::Control; #[inline] fn deref(&self) -> &::controls::Control { // FIXME(pcwalton): $10 says this is undefined behavior. How do I make it not so? unsafe { mem::transmute::<&$rust_type, &::controls::Control>(self) } } } impl Drop for $rust_type { #[inline] fn drop(&mut self) { // For now this does nothing, but in the future, when `libui` supports proper // memory management, this will likely need to twiddle reference counts. } } impl Clone for $rust_type { #[inline] fn clone(&self) -> $rust_type { $rust_type { $ui_field: self.$ui_field, } } } impl Into<Control> for $rust_type { #[inline] fn into(self) -> Control { unsafe { let control = Control::from_ui_control(self.$ui_field as *mut uiControl); mem::forget(self); control } } } impl $rust_type { #[inline] pub unsafe fn from_ui_control($ui_field: *mut $ui_type) -> $rust_type { $rust_type { $ui_field: $ui_field } } } } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. ///! This module defines the `Uuid` type which represents a 128-bit Bluetooth UUID. It provides ///! convenience functions to support 16-bit, 32-bit, and 128-bit canonical formats as well as ///! string representation. It can be converted to/from a fuchsia.bluetooth.Uuid FIDL type. use { byteorder::{ByteOrder, LittleEndian}, fidl_fuchsia_bluetooth as fidl, std::fmt, }; const NUM_UUID_BYTES: usize = 16; #[derive(Clone, Debug, PartialEq)] pub struct Uuid([u8; NUM_UUID_BYTES]); fn base_uuid() -> Uuid { Uuid([ 0xFB, 0x34, 0x9B, 0x5F, 0x80, 0x00, 0x00, 0x80, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]) } impl Uuid { pub fn new16(value: u16) -> Uuid { Uuid::new32(value as u32) } pub fn new32(value: u32) -> Uuid { let mut uuid = base_uuid(); LittleEndian::write_u32(&mut uuid.0[(NUM_UUID_BYTES - 4)..NUM_UUID_BYTES], value); uuid } pub fn to_string(&self) -> String { format!("{:02x}{:02x}{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}", self.0[15], self.0[14], self.0[13], self.0[12], self.0[11], self.0[10], self.0[9], self.0[8], self.0[7], self.0[6], self.0[5], self.0[4], self.0[3], self.0[2], self.0[1], self.0[0]) } } impl From<&fidl::Uuid> for Uuid { fn from(src: &fidl::Uuid) -> Uuid { Uuid(src.value) } } impl From<fidl::Uuid> for Uuid { fn from(src: fidl::Uuid) -> Uuid { Uuid::from(&src) } } #[cfg(test)] mod tests { use super::*; #[test] fn uuid16_to_string() { let uuid = Uuid::new16(0x180d); assert_eq!("0000180d-0000-1000-8000-00805f9b34fb", uuid.to_string()); } #[test] fn uuid32_to_string() { let uuid = Uuid::new32(0xAABBCCDD); assert_eq!("aabbccdd-0000-1000-8000-00805f9b34fb", uuid.to_string()); } #[test] fn uuid128_to_string() { let uuid = Uuid([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); assert_eq!("0f0e0d0c-0b0a-0908-0706-050403020100", uuid.to_string()); } #[test] fn uuid_from_fidl() { let uuid = fidl::Uuid { value: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] }; let uuid: Uuid = uuid.into(); assert_eq!("0f0e0d0c-0b0a-0908-0706-050403020100", uuid.to_string()); } }
use serde::{Deserialize, Serialize}; #[derive(Copy, Clone, Serialize, Deserialize, Eq, PartialEq, Hash, Debug)] pub struct StoreConfig { pub header_cache_size: usize, pub cell_data_cache_size: usize, pub block_proposals_cache_size: usize, pub block_tx_hashes_cache_size: usize, pub block_uncles_cache_size: usize, pub cellbase_cache_size: usize, } impl Default for StoreConfig { fn default() -> Self { StoreConfig { header_cache_size: 4096, cell_data_cache_size: 128, block_proposals_cache_size: 30, block_tx_hashes_cache_size: 30, block_uncles_cache_size: 30, cellbase_cache_size: 30, } } }
#![no_std] use serde_big_array::BigArray; use serde_derive::{Deserialize, Serialize}; #[derive(Serialize)] struct S { #[serde(with = "BigArray")] arr: [SerOnly; 64], } #[derive(Debug, Clone, Copy, Serialize)] struct SerOnly(u8); #[derive(Deserialize)] struct D { #[serde(with = "BigArray")] arr: [DeOnly; 64], } #[derive(Debug, Clone, Copy, Deserialize)] struct DeOnly(u8); impl PartialEq<DeOnly> for SerOnly { fn eq(&self, other: &DeOnly) -> bool { self.0 == other.0 } } #[test] fn test() { let s = S { arr: [SerOnly(1); 64], }; let j = serde_json::to_string(&s).unwrap(); let s_back = serde_json::from_str::<D>(&j).unwrap(); assert_eq!(&s.arr[..], &s_back.arr[..]); }
use itertools::Itertools; use scan_fmt::scan_fmt; #[aoc::main(11)] pub fn main(input: &str) -> (u64, u64) { solve(input) } #[aoc::test(11)] pub fn test(input: &str) -> (String, String) { let res = solve(input); (res.0.to_string(), res.1.to_string()) } #[derive(Clone, Debug)] struct Operation { op: char, n: String, } fn solve(input: &str) -> (u64, u64) { let monkies = get_monkies(input); let p1 = part1(monkies.clone()); let p2 = part2(monkies); (p1, p2) } fn get_monkies(input: &str) -> Vec<(Vec<u64>, Operation, u64, usize, usize)> { input .trim() .split("\r\n\r\n") .map(|monkey_def| { let monkey = monkey_def.trim().lines().skip(1).collect_vec(); let mut items_str = monkey[0].split(", ").collect_vec(); items_str[0] = items_str[0].split_once(": ").unwrap().1; let items = items_str .iter() .map(|&item| item.trim().parse::<u64>().unwrap()) .collect_vec(); let op_str = monkey[1].split_once(" old ").unwrap().1; let (op, num_str) = op_str.split_once(' ').unwrap(); let operation = Operation { op: *op.trim().chars().collect_vec().first().unwrap(), n: num_str.to_string(), }; let test = scan_fmt!(monkey[2].trim(), "Test: divisible by {d}", u64).unwrap(); let success = scan_fmt!(monkey[3].trim(), "If true: throw to monkey {d}", usize).unwrap(); let failure = scan_fmt!(monkey[4].trim(), "If false: throw to monkey {d}", usize).unwrap(); (items, operation, test, success, failure) }) .collect_vec() } fn get_inspection_counts( mut monkies: Vec<(Vec<u64>, Operation, u64, usize, usize)>, rounds: u64, modification: impl Fn(u64) -> u64, ) -> Vec<u64> { let mut monkey_inspections: Vec<u64> = vec![0; monkies.len()]; for _ in 0..rounds { for i in 0..monkies.len() { let (items, operation, test, success, fail) = monkies[i].clone(); items.iter().for_each(|&(mut worry_level)| { monkey_inspections[i] += 1; match operation.op { '+' => worry_level += operation.n.parse::<u64>().unwrap(), '*' => match operation.n.as_str() { "old" => worry_level *= worry_level, _ => worry_level *= operation.n.parse::<u64>().unwrap(), }, _ => panic!("Shouldn't happen"), } worry_level = modification(worry_level); if worry_level.rem_euclid(test) == 0 { monkies[success].0.push(worry_level); } else { monkies[fail].0.push(worry_level); } }); monkies[i].0.clear(); } } monkey_inspections } fn part1(monkies: Vec<(Vec<u64>, Operation, u64, usize, usize)>) -> u64 { let mut inspections = get_inspection_counts(monkies, 20, |x| x / 3); inspections.sort(); inspections.reverse(); inspections[0] * inspections[1] } fn part2(monkies: Vec<(Vec<u64>, Operation, u64, usize, usize)>) -> u64 { let modulus = monkies.iter().map(|m| m.2).product::<u64>(); let mut inspections = get_inspection_counts(monkies, 10000, |x| x % modulus); inspections.sort(); inspections.reverse(); inspections[0] * inspections[1] }
//! A simple Driver for the Waveshare 4.2" E-Ink Display via SPI //! //! //! Build with the help of documentation/code from [Waveshare](https://www.waveshare.com/wiki/4.2inch_e-Paper_Module), //! [Ben Krasnows partial Refresh tips](https://benkrasnow.blogspot.de/2017/10/fast-partial-refresh-on-42-e-paper.html) and //! the driver documents in the `pdfs`-folder as orientation. //! //! # Examples //! //!```rust, no_run //!# use embedded_hal_mock::*; //!# fn main() -> Result<(), MockError> { //!use embedded_graphics::{ //! pixelcolor::BinaryColor::On as Black, prelude::*, primitives::{Line, PrimitiveStyle}, //!}; //!use epd_waveshare::{epd4in2::*, prelude::*}; //!# //!# let expectations = []; //!# let mut spi = spi::Mock::new(&expectations); //!# let expectations = []; //!# let cs_pin = pin::Mock::new(&expectations); //!# let busy_in = pin::Mock::new(&expectations); //!# let dc = pin::Mock::new(&expectations); //!# let rst = pin::Mock::new(&expectations); //!# let mut delay = delay::MockNoop::new(); //! //!// Setup EPD //!let mut epd = Epd4in2::new(&mut spi, cs_pin, busy_in, dc, rst, &mut delay, None)?; //! //!// Use display graphics from embedded-graphics //!let mut display = Display4in2::default(); //! //!// Use embedded graphics for drawing a line //!let _ = Line::new(Point::new(0, 120), Point::new(0, 295)) //! .into_styled(PrimitiveStyle::with_stroke(Color::Black, 1)) //! .draw(&mut display); //! //! // Display updated frame //!epd.update_frame(&mut spi, &display.buffer(), &mut delay)?; //!epd.display_frame(&mut spi, &mut delay)?; //! //!// Set the EPD to sleep //!epd.sleep(&mut spi, &mut delay)?; //!# Ok(()) //!# } //!``` //! //! //! //! BE CAREFUL! The screen can get ghosting/burn-ins through the Partial Fast Update Drawing. use embedded_hal::{ blocking::{delay::*, spi::Write}, digital::v2::*, }; use crate::interface::DisplayInterface; use crate::traits::{InternalWiAdditions, QuickRefresh, RefreshLut, WaveshareDisplay}; //The Lookup Tables for the Display mod constants; use crate::epd4in2::constants::*; /// Width of the display pub const WIDTH: u32 = 400; /// Height of the display pub const HEIGHT: u32 = 300; /// Default Background Color pub const DEFAULT_BACKGROUND_COLOR: Color = Color::White; const IS_BUSY_LOW: bool = true; use crate::color::Color; pub(crate) mod command; use self::command::Command; use crate::buffer_len; /// Full size buffer for use with the 4in2 EPD #[cfg(feature = "graphics")] pub type Display4in2 = crate::graphics::Display< WIDTH, HEIGHT, false, { buffer_len(WIDTH as usize, HEIGHT as usize) }, Color, >; /// Epd4in2 driver /// pub struct Epd4in2<SPI, CS, BUSY, DC, RST, DELAY> { /// Connection Interface interface: DisplayInterface<SPI, CS, BUSY, DC, RST, DELAY>, /// Background Color color: Color, /// Refresh LUT refresh: RefreshLut, } impl<SPI, CS, BUSY, DC, RST, DELAY> InternalWiAdditions<SPI, CS, BUSY, DC, RST, DELAY> for Epd4in2<SPI, CS, BUSY, DC, RST, DELAY> where SPI: Write<u8>, CS: OutputPin, BUSY: InputPin, DC: OutputPin, RST: OutputPin, DELAY: DelayUs<u32>, { fn init(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { // reset the device self.interface.reset(delay, 10_000, 10_000); // set the power settings self.interface.cmd_with_data( spi, Command::PowerSetting, &[0x03, 0x00, 0x2b, 0x2b, 0xff], )?; // start the booster self.interface .cmd_with_data(spi, Command::BoosterSoftStart, &[0x17, 0x17, 0x17])?; // power on self.command(spi, Command::PowerOn)?; delay.delay_us(5000); self.wait_until_idle(spi, delay)?; // set the panel settings self.cmd_with_data(spi, Command::PanelSetting, &[0x3F])?; // Set Frequency, 200 Hz didn't work on my board // 150Hz and 171Hz wasn't tested yet // TODO: Test these other frequencies // 3A 100HZ 29 150Hz 39 200HZ 31 171HZ DEFAULT: 3c 50Hz self.cmd_with_data(spi, Command::PllControl, &[0x3A])?; self.send_resolution(spi)?; self.interface .cmd_with_data(spi, Command::VcmDcSetting, &[0x12])?; //VBDF 17|D7 VBDW 97 VBDB 57 VBDF F7 VBDW 77 VBDB 37 VBDR B7 self.interface .cmd_with_data(spi, Command::VcomAndDataIntervalSetting, &[0x97])?; self.set_lut(spi, delay, None)?; self.wait_until_idle(spi, delay)?; Ok(()) } } impl<SPI, CS, BUSY, DC, RST, DELAY> WaveshareDisplay<SPI, CS, BUSY, DC, RST, DELAY> for Epd4in2<SPI, CS, BUSY, DC, RST, DELAY> where SPI: Write<u8>, CS: OutputPin, BUSY: InputPin, DC: OutputPin, RST: OutputPin, DELAY: DelayUs<u32>, { type DisplayColor = Color; fn new( spi: &mut SPI, cs: CS, busy: BUSY, dc: DC, rst: RST, delay: &mut DELAY, delay_us: Option<u32>, ) -> Result<Self, SPI::Error> { let interface = DisplayInterface::new(cs, busy, dc, rst, delay_us); let color = DEFAULT_BACKGROUND_COLOR; let mut epd = Epd4in2 { interface, color, refresh: RefreshLut::Full, }; epd.init(spi, delay)?; Ok(epd) } fn sleep(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; self.interface .cmd_with_data(spi, Command::VcomAndDataIntervalSetting, &[0x17])?; //border floating self.command(spi, Command::VcmDcSetting)?; // VCOM to 0V self.command(spi, Command::PanelSetting)?; self.command(spi, Command::PowerSetting)?; //VG&VS to 0V fast for _ in 0..4 { self.send_data(spi, &[0x00])?; } self.command(spi, Command::PowerOff)?; self.wait_until_idle(spi, delay)?; self.interface .cmd_with_data(spi, Command::DeepSleep, &[0xA5])?; Ok(()) } fn wake_up(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.init(spi, delay) } fn set_background_color(&mut self, color: Color) { self.color = color; } fn background_color(&self) -> &Color { &self.color } fn width(&self) -> u32 { WIDTH } fn height(&self) -> u32 { HEIGHT } fn update_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; let color_value = self.color.get_byte_value(); self.interface.cmd(spi, Command::DataStartTransmission1)?; self.interface .data_x_times(spi, color_value, WIDTH / 8 * HEIGHT)?; self.interface .cmd_with_data(spi, Command::DataStartTransmission2, buffer)?; Ok(()) } fn update_partial_frame( &mut self, spi: &mut SPI, delay: &mut DELAY, buffer: &[u8], x: u32, y: u32, width: u32, height: u32, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; if buffer.len() as u32 != width / 8 * height { //TODO: panic!! or sth like that //return Err("Wrong buffersize"); } self.command(spi, Command::PartialIn)?; self.command(spi, Command::PartialWindow)?; self.send_data(spi, &[(x >> 8) as u8])?; let tmp = x & 0xf8; self.send_data(spi, &[tmp as u8])?; // x should be the multiple of 8, the last 3 bit will always be ignored let tmp = tmp + width - 1; self.send_data(spi, &[(tmp >> 8) as u8])?; self.send_data(spi, &[(tmp | 0x07) as u8])?; self.send_data(spi, &[(y >> 8) as u8])?; self.send_data(spi, &[y as u8])?; self.send_data(spi, &[((y + height - 1) >> 8) as u8])?; self.send_data(spi, &[(y + height - 1) as u8])?; self.send_data(spi, &[0x01])?; // Gates scan both inside and outside of the partial window. (default) //TODO: handle dtm somehow let is_dtm1 = false; if is_dtm1 { self.command(spi, Command::DataStartTransmission1)? //TODO: check if data_start transmission 1 also needs "old"/background data here } else { self.command(spi, Command::DataStartTransmission2)? } self.send_data(spi, buffer)?; self.command(spi, Command::PartialOut)?; Ok(()) } fn display_frame(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; self.command(spi, Command::DisplayRefresh)?; Ok(()) } fn update_and_display_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error> { self.update_frame(spi, buffer, delay)?; self.command(spi, Command::DisplayRefresh)?; Ok(()) } fn clear_frame(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; self.send_resolution(spi)?; let color_value = self.color.get_byte_value(); self.interface.cmd(spi, Command::DataStartTransmission1)?; self.interface .data_x_times(spi, color_value, WIDTH / 8 * HEIGHT)?; self.interface.cmd(spi, Command::DataStartTransmission2)?; self.interface .data_x_times(spi, color_value, WIDTH / 8 * HEIGHT)?; Ok(()) } fn set_lut( &mut self, spi: &mut SPI, delay: &mut DELAY, refresh_rate: Option<RefreshLut>, ) -> Result<(), SPI::Error> { if let Some(refresh_lut) = refresh_rate { self.refresh = refresh_lut; } match self.refresh { RefreshLut::Full => { self.set_lut_helper(spi, delay, &LUT_VCOM0, &LUT_WW, &LUT_BW, &LUT_WB, &LUT_BB) } RefreshLut::Quick => self.set_lut_helper( spi, delay, &LUT_VCOM0_QUICK, &LUT_WW_QUICK, &LUT_BW_QUICK, &LUT_WB_QUICK, &LUT_BB_QUICK, ), } } fn wait_until_idle(&mut self, _spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.interface.wait_until_idle(delay, IS_BUSY_LOW); Ok(()) } } impl<SPI, CS, BUSY, DC, RST, DELAY> Epd4in2<SPI, CS, BUSY, DC, RST, DELAY> where SPI: Write<u8>, CS: OutputPin, BUSY: InputPin, DC: OutputPin, RST: OutputPin, DELAY: DelayUs<u32>, { fn command(&mut self, spi: &mut SPI, command: Command) -> Result<(), SPI::Error> { self.interface.cmd(spi, command) } fn send_data(&mut self, spi: &mut SPI, data: &[u8]) -> Result<(), SPI::Error> { self.interface.data(spi, data) } fn cmd_with_data( &mut self, spi: &mut SPI, command: Command, data: &[u8], ) -> Result<(), SPI::Error> { self.interface.cmd_with_data(spi, command, data) } fn send_resolution(&mut self, spi: &mut SPI) -> Result<(), SPI::Error> { let w = self.width(); let h = self.height(); self.command(spi, Command::ResolutionSetting)?; self.send_data(spi, &[(w >> 8) as u8])?; self.send_data(spi, &[w as u8])?; self.send_data(spi, &[(h >> 8) as u8])?; self.send_data(spi, &[h as u8]) } #[allow(clippy::too_many_arguments)] fn set_lut_helper( &mut self, spi: &mut SPI, delay: &mut DELAY, lut_vcom: &[u8], lut_ww: &[u8], lut_bw: &[u8], lut_wb: &[u8], lut_bb: &[u8], ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; // LUT VCOM self.cmd_with_data(spi, Command::LutForVcom, lut_vcom)?; // LUT WHITE to WHITE self.cmd_with_data(spi, Command::LutWhiteToWhite, lut_ww)?; // LUT BLACK to WHITE self.cmd_with_data(spi, Command::LutBlackToWhite, lut_bw)?; // LUT WHITE to BLACK self.cmd_with_data(spi, Command::LutWhiteToBlack, lut_wb)?; // LUT BLACK to BLACK self.cmd_with_data(spi, Command::LutBlackToBlack, lut_bb)?; Ok(()) } /// Helper function. Sets up the display to send pixel data to a custom /// starting point. pub fn shift_display( &mut self, spi: &mut SPI, x: u32, y: u32, width: u32, height: u32, ) -> Result<(), SPI::Error> { self.send_data(spi, &[(x >> 8) as u8])?; let tmp = x & 0xf8; self.send_data(spi, &[tmp as u8])?; // x should be the multiple of 8, the last 3 bit will always be ignored let tmp = tmp + width - 1; self.send_data(spi, &[(tmp >> 8) as u8])?; self.send_data(spi, &[(tmp | 0x07) as u8])?; self.send_data(spi, &[(y >> 8) as u8])?; self.send_data(spi, &[y as u8])?; self.send_data(spi, &[((y + height - 1) >> 8) as u8])?; self.send_data(spi, &[(y + height - 1) as u8])?; self.send_data(spi, &[0x01])?; // Gates scan both inside and outside of the partial window. (default) Ok(()) } } impl<SPI, CS, BUSY, DC, RST, DELAY> QuickRefresh<SPI, CS, BUSY, DC, RST, DELAY> for Epd4in2<SPI, CS, BUSY, DC, RST, DELAY> where SPI: Write<u8>, CS: OutputPin, BUSY: InputPin, DC: OutputPin, RST: OutputPin, DELAY: DelayUs<u32>, { /// To be followed immediately after by `update_old_frame`. fn update_old_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; self.interface.cmd(spi, Command::DataStartTransmission1)?; self.interface.data(spi, buffer)?; Ok(()) } /// To be used immediately after `update_old_frame`. fn update_new_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; // self.send_resolution(spi)?; self.interface.cmd(spi, Command::DataStartTransmission2)?; self.interface.data(spi, buffer)?; Ok(()) } /// This is a wrapper around `display_frame` for using this device as a true /// `QuickRefresh` device. fn display_new_frame(&mut self, spi: &mut SPI, delay: &mut DELAY) -> Result<(), SPI::Error> { self.display_frame(spi, delay) } /// This is wrapper around `update_new_frame` and `display_frame` for using /// this device as a true `QuickRefresh` device. /// /// To be used immediately after `update_old_frame`. fn update_and_display_new_frame( &mut self, spi: &mut SPI, buffer: &[u8], delay: &mut DELAY, ) -> Result<(), SPI::Error> { self.update_new_frame(spi, buffer, delay)?; self.display_frame(spi, delay) } fn update_partial_old_frame( &mut self, spi: &mut SPI, delay: &mut DELAY, buffer: &[u8], x: u32, y: u32, width: u32, height: u32, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; if buffer.len() as u32 != width / 8 * height { //TODO: panic!! or sth like that //return Err("Wrong buffersize"); } self.interface.cmd(spi, Command::PartialIn)?; self.interface.cmd(spi, Command::PartialWindow)?; self.shift_display(spi, x, y, width, height)?; self.interface.cmd(spi, Command::DataStartTransmission1)?; self.interface.data(spi, buffer)?; Ok(()) } /// Always call `update_partial_old_frame` before this, with buffer-updating code /// between the calls. fn update_partial_new_frame( &mut self, spi: &mut SPI, delay: &mut DELAY, buffer: &[u8], x: u32, y: u32, width: u32, height: u32, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; if buffer.len() as u32 != width / 8 * height { //TODO: panic!! or sth like that //return Err("Wrong buffersize"); } self.shift_display(spi, x, y, width, height)?; self.interface.cmd(spi, Command::DataStartTransmission2)?; self.interface.data(spi, buffer)?; self.interface.cmd(spi, Command::PartialOut)?; Ok(()) } fn clear_partial_frame( &mut self, spi: &mut SPI, delay: &mut DELAY, x: u32, y: u32, width: u32, height: u32, ) -> Result<(), SPI::Error> { self.wait_until_idle(spi, delay)?; self.send_resolution(spi)?; let color_value = self.color.get_byte_value(); self.interface.cmd(spi, Command::PartialIn)?; self.interface.cmd(spi, Command::PartialWindow)?; self.shift_display(spi, x, y, width, height)?; self.interface.cmd(spi, Command::DataStartTransmission1)?; self.interface .data_x_times(spi, color_value, width / 8 * height)?; self.interface.cmd(spi, Command::DataStartTransmission2)?; self.interface .data_x_times(spi, color_value, width / 8 * height)?; self.interface.cmd(spi, Command::PartialOut)?; Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn epd_size() { assert_eq!(WIDTH, 400); assert_eq!(HEIGHT, 300); assert_eq!(DEFAULT_BACKGROUND_COLOR, Color::White); } }
mod token; mod tokenize; pub use self::token::Token; pub use self::token::Dictionary; pub use self::token::Operator; pub use self::token::Bracket; pub use self::token::BracketSide; pub use self::token::ReservedWord; pub use self::tokenize::tokenize;
use std::path::PathBuf; use actix_cors::Cors; use actix_web::{App, HttpServer, Responder, web, http::header}; use serde_derive::*; use structopt::StructOpt; use crate::dictionary::Dictionary; use crate::errors::AppError; use crate::screen::{Screen, Opt as ScreenOpt}; #[derive(StructOpt, Debug)] #[structopt(name = "server")] pub struct Opt { /// "host:port" to listen pub bind_to: Option<String>, /// Ignore not found #[structopt(short = "i", long = "ignore")] pub ignore_not_found: bool, /// Output to #[structopt(subcommand)] pub screen: ScreenOpt, } #[derive(Clone)] struct State { pub dictionary_path: PathBuf, pub ignore_not_found: bool, pub screen: Screen, } #[derive(Deserialize)] pub struct GetWord { word: String, } pub fn start_server(opt: Opt, dictionary_path: PathBuf) -> Result<(), AppError> { let bind_to = opt.bind_to.unwrap_or_else(|| "127.0.0.1:8116".to_owned()); let state = State { dictionary_path: dictionary_path.clone(), ignore_not_found: opt.ignore_not_found, screen: Screen::new(opt.screen, dictionary_path, bind_to.clone()) }; let server = HttpServer::new(move || { let state= state.clone(); App::new() .wrap( Cors::new() .allowed_origin("http://localhost:8080") .allowed_methods(vec!["GET", "POST"]) .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT]) .allowed_header(header::CONTENT_TYPE) .max_age(3600), ) .route("/ack", web::get().to(on_ack)) .route("/word/{word}", web::get().to(on_get_word)) .data(state) }); server .bind(bind_to)? .run()?; Ok(()) } fn on_ack() -> impl Responder { "␆" } fn on_get_word(state: web::Data<State>, param: web::Path<GetWord>) -> impl Responder { match Dictionary::get_word(&state.dictionary_path, &param.word) { Ok(entries) => { if !state.ignore_not_found || entries.is_some() { state.screen.print_opt(entries.clone()); } if let Some(entries) = entries { let mut content = vec![]; for entry in &entries { content.push(format!("#{}", entry.key)); // content.push(entry.content); } Some(content.join("\n")) } else { None } }, Err(err) => panic!("Not implemented: {}", err) } }
use std::collections::HashMap; fn main(){ // //Vec let mut vec = vec![1,2,3,4,5]; // show the contents of vec for x in vec.iter() { println!("{}",x); } println!("--------------------------------------"); // iter_mut :an iterator of mutable reference for x in vec.iter_mut() { *x = *x + 1; println!("{}",x); } println!("-------------------------------------"); //into_iter let vec_ = vec![7,8,9]; vec.extend(vec_); for i in vec.iter() { println!("{}",i); } // HashMap let mut prefecture_and_capital = HashMap::new(); // insert the key and value prefecture_and_capital.insert("Fukushima", "Fukushima"); prefecture_and_capital.insert("Miyagi", "Sendai"); prefecture_and_capital.insert("Yamagata", "Yamagata"); prefecture_and_capital.insert("Hokkaido", "Sapporo"); //if Iwate is not containd in prefecture_and_capital HashMap, print the message if !prefecture_and_capital.contains_key("Iwate") { println!("prefecture_and_capital has {} prefecture but Iwate ain't one.",prefecture_and_capital.len()); } //remove the key and value prefecture_and_capital.remove("Miyagi"); let to_find = ["Fukushima","Miyagi"]; for prefecture in &to_find { match prefecture_and_capital.get(prefecture) { Some(capital) => println!("{}:{}",prefecture,capital), None => println!("{} doesn't exist",prefecture), } } //capacity println!("capacity:{}",prefecture_and_capital.capacity()); prefecture_and_capital.insert("Hyogo","Kobe"); }
// Robert "Skipper" Gonzaelz <sgonzalez@hmc.edu> // Starter code for HMC's MemorySafe, week 1 // // The implementation of SinglyLinkedList use Stack; use std::mem; pub struct SinglyLinkedList<T> { head: Option<Box<Node<T>>>, length: usize } struct Node<T> { data: T, next: Option<Box<Node<T>>>, } impl<T: Eq> Stack<T> for SinglyLinkedList<T> { fn new() -> Self { SinglyLinkedList{ head: None, length: 0} } fn push_front(&mut self, item: T) { let new_node = Node{data: item, next: self.head.take()}; self.head = Some(Box::new(new_node)); self.length += 1; } fn pop_front(&mut self) -> Option<T> { if self.length > 0 { let old_head = self.head.take(); let mut unwrapped_old_head = old_head.unwrap(); self.head = mem::replace(&mut unwrapped_old_head.next, None); let popped = unwrapped_old_head.data; self.length -= 1; Some(popped) } else { None } } fn peek_front(&self) -> Option<&T> { if self.length > 0 { let head_ref = self.head.as_ref(); Some(&head_ref.unwrap().data) } else { None } } fn len(&self) -> usize { self.length } }
use std::process::Command; /// Spawn "youtube-dl" from PATH #[cfg(target_os = "linux")] pub fn spawn_command() -> Command { return Command::new("youtube-dl"); } /// Spawn "youtube-dl" for non-linux systems #[cfg(not(target_os = "linux"))] pub fn spawn_command() -> Command { use std::env::current_exe; use std::fs::metadata; let path: Path = current_exe() .expect("Current Exectuable path not found, how does this even run?") .parent() .expect("invalid executable folder"); if cfg!(target_os = windows) { path.join("youtube-dl.exe"); } else { path.join("youtube-dl"); } if let Ok(_) = metadata(path) { return Command::new(path); } return Command::new("youtube-dl"); }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `EN` reader - AES enable"] pub type EN_R = crate::BitReader; #[doc = "Field `EN` writer - AES enable"] pub type EN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DATATYPE` reader - Data type selection (for data in and data out to/from the cryptographic block)"] pub type DATATYPE_R = crate::FieldReader; #[doc = "Field `DATATYPE` writer - Data type selection (for data in and data out to/from the cryptographic block)"] pub type DATATYPE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `MODE` reader - AES operating mode"] pub type MODE_R = crate::FieldReader; #[doc = "Field `MODE` writer - AES operating mode"] pub type MODE_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CHMOD` reader - AES chaining mode selection Bit1 Bit0"] pub type CHMOD_R = crate::FieldReader; #[doc = "Field `CHMOD` writer - AES chaining mode selection Bit1 Bit0"] pub type CHMOD_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CCFC` reader - Computation Complete Flag Clear"] pub type CCFC_R = crate::BitReader; #[doc = "Field `CCFC` writer - Computation Complete Flag Clear"] pub type CCFC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ERRC` reader - Error clear"] pub type ERRC_R = crate::BitReader; #[doc = "Field `ERRC` writer - Error clear"] pub type ERRC_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CCFIE` reader - CCF flag interrupt enable"] pub type CCFIE_R = crate::BitReader; #[doc = "Field `CCFIE` writer - CCF flag interrupt enable"] pub type CCFIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ERRIE` reader - Error interrupt enable"] pub type ERRIE_R = crate::BitReader; #[doc = "Field `ERRIE` writer - Error interrupt enable"] pub type ERRIE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMAINEN` reader - Enable DMA management of data input phase"] pub type DMAINEN_R = crate::BitReader; #[doc = "Field `DMAINEN` writer - Enable DMA management of data input phase"] pub type DMAINEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DMAOUTEN` reader - Enable DMA management of data output phase"] pub type DMAOUTEN_R = crate::BitReader; #[doc = "Field `DMAOUTEN` writer - Enable DMA management of data output phase"] pub type DMAOUTEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `GCMPH` reader - Used only for GCM, CCM and GMAC algorithms and has no effect when other algorithms are selected"] pub type GCMPH_R = crate::FieldReader; #[doc = "Field `GCMPH` writer - Used only for GCM, CCM and GMAC algorithms and has no effect when other algorithms are selected"] pub type GCMPH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `CHMOD2` reader - AES chaining mode Bit2"] pub type CHMOD2_R = crate::BitReader; #[doc = "Field `CHMOD2` writer - AES chaining mode Bit2"] pub type CHMOD2_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `KEYSIZE` reader - Key size selection"] pub type KEYSIZE_R = crate::BitReader; #[doc = "Field `KEYSIZE` writer - Key size selection"] pub type KEYSIZE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `NPBLB` reader - Number of padding bytes in last block of payload"] pub type NPBLB_R = crate::FieldReader; #[doc = "Field `NPBLB` writer - Number of padding bytes in last block of payload"] pub type NPBLB_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bit 0 - AES enable"] #[inline(always)] pub fn en(&self) -> EN_R { EN_R::new((self.bits & 1) != 0) } #[doc = "Bits 1:2 - Data type selection (for data in and data out to/from the cryptographic block)"] #[inline(always)] pub fn datatype(&self) -> DATATYPE_R { DATATYPE_R::new(((self.bits >> 1) & 3) as u8) } #[doc = "Bits 3:4 - AES operating mode"] #[inline(always)] pub fn mode(&self) -> MODE_R { MODE_R::new(((self.bits >> 3) & 3) as u8) } #[doc = "Bits 5:6 - AES chaining mode selection Bit1 Bit0"] #[inline(always)] pub fn chmod(&self) -> CHMOD_R { CHMOD_R::new(((self.bits >> 5) & 3) as u8) } #[doc = "Bit 7 - Computation Complete Flag Clear"] #[inline(always)] pub fn ccfc(&self) -> CCFC_R { CCFC_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Error clear"] #[inline(always)] pub fn errc(&self) -> ERRC_R { ERRC_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - CCF flag interrupt enable"] #[inline(always)] pub fn ccfie(&self) -> CCFIE_R { CCFIE_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Error interrupt enable"] #[inline(always)] pub fn errie(&self) -> ERRIE_R { ERRIE_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Enable DMA management of data input phase"] #[inline(always)] pub fn dmainen(&self) -> DMAINEN_R { DMAINEN_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Enable DMA management of data output phase"] #[inline(always)] pub fn dmaouten(&self) -> DMAOUTEN_R { DMAOUTEN_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bits 13:14 - Used only for GCM, CCM and GMAC algorithms and has no effect when other algorithms are selected"] #[inline(always)] pub fn gcmph(&self) -> GCMPH_R { GCMPH_R::new(((self.bits >> 13) & 3) as u8) } #[doc = "Bit 16 - AES chaining mode Bit2"] #[inline(always)] pub fn chmod2(&self) -> CHMOD2_R { CHMOD2_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 18 - Key size selection"] #[inline(always)] pub fn keysize(&self) -> KEYSIZE_R { KEYSIZE_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bits 20:23 - Number of padding bytes in last block of payload"] #[inline(always)] pub fn npblb(&self) -> NPBLB_R { NPBLB_R::new(((self.bits >> 20) & 0x0f) as u8) } } impl W { #[doc = "Bit 0 - AES enable"] #[inline(always)] #[must_use] pub fn en(&mut self) -> EN_W<CR_SPEC, 0> { EN_W::new(self) } #[doc = "Bits 1:2 - Data type selection (for data in and data out to/from the cryptographic block)"] #[inline(always)] #[must_use] pub fn datatype(&mut self) -> DATATYPE_W<CR_SPEC, 1> { DATATYPE_W::new(self) } #[doc = "Bits 3:4 - AES operating mode"] #[inline(always)] #[must_use] pub fn mode(&mut self) -> MODE_W<CR_SPEC, 3> { MODE_W::new(self) } #[doc = "Bits 5:6 - AES chaining mode selection Bit1 Bit0"] #[inline(always)] #[must_use] pub fn chmod(&mut self) -> CHMOD_W<CR_SPEC, 5> { CHMOD_W::new(self) } #[doc = "Bit 7 - Computation Complete Flag Clear"] #[inline(always)] #[must_use] pub fn ccfc(&mut self) -> CCFC_W<CR_SPEC, 7> { CCFC_W::new(self) } #[doc = "Bit 8 - Error clear"] #[inline(always)] #[must_use] pub fn errc(&mut self) -> ERRC_W<CR_SPEC, 8> { ERRC_W::new(self) } #[doc = "Bit 9 - CCF flag interrupt enable"] #[inline(always)] #[must_use] pub fn ccfie(&mut self) -> CCFIE_W<CR_SPEC, 9> { CCFIE_W::new(self) } #[doc = "Bit 10 - Error interrupt enable"] #[inline(always)] #[must_use] pub fn errie(&mut self) -> ERRIE_W<CR_SPEC, 10> { ERRIE_W::new(self) } #[doc = "Bit 11 - Enable DMA management of data input phase"] #[inline(always)] #[must_use] pub fn dmainen(&mut self) -> DMAINEN_W<CR_SPEC, 11> { DMAINEN_W::new(self) } #[doc = "Bit 12 - Enable DMA management of data output phase"] #[inline(always)] #[must_use] pub fn dmaouten(&mut self) -> DMAOUTEN_W<CR_SPEC, 12> { DMAOUTEN_W::new(self) } #[doc = "Bits 13:14 - Used only for GCM, CCM and GMAC algorithms and has no effect when other algorithms are selected"] #[inline(always)] #[must_use] pub fn gcmph(&mut self) -> GCMPH_W<CR_SPEC, 13> { GCMPH_W::new(self) } #[doc = "Bit 16 - AES chaining mode Bit2"] #[inline(always)] #[must_use] pub fn chmod2(&mut self) -> CHMOD2_W<CR_SPEC, 16> { CHMOD2_W::new(self) } #[doc = "Bit 18 - Key size selection"] #[inline(always)] #[must_use] pub fn keysize(&mut self) -> KEYSIZE_W<CR_SPEC, 18> { KEYSIZE_W::new(self) } #[doc = "Bits 20:23 - Number of padding bytes in last block of payload"] #[inline(always)] #[must_use] pub fn npblb(&mut self) -> NPBLB_W<CR_SPEC, 20> { NPBLB_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 = "control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0; }
/// Permute an integer pseudorandomly. /// /// This is a bijective function emitting chaotic behavior. Such functions are used as building /// blocks for hash functions. pub fn sigma(mut x: u8) -> u8 { x = x.wrapping_mul(211); x ^= x >> 4; x = x.wrapping_mul(211); } const INITIAL_STATE: u64 = 0x8a; struct Sponge { state: u8, bytes: Vec<u8>, } impl Sponge { fn finalize(&mut self) { self.write_usize(self.bytes.len()); self.state = INITIAL_STATE; } fn squeeze(&mut self) -> u8 { self.state ^= self.bytes.pop().unwrap_or(0); self.state } } impl Hasher for Sponge { fn finish(&self) -> u64 { unreachable!(); } fn write_u8(&mut self, mut i: u8) { self.state ^= i; self.state = sigma(self.state); self.bytes.push(self.state) } }
use std::fmt::Display; /// A specific [KDL Value](https://github.com/kdl-org/kdl/blob/main/SPEC.md#value). #[derive(Debug, Clone, PartialEq)] pub enum KdlValue { /// A [KDL Raw String](https://github.com/kdl-org/kdl/blob/main/SPEC.md#raw-string). RawString(String), /// A [KDL String](https://github.com/kdl-org/kdl/blob/main/SPEC.md#string). String(String), /// A [KDL /// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in /// binary form (e.g. `0b010101`). Base2(i64), /// A [KDL /// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in /// octal form (e.g. `0o12345670`). Base8(i64), /// A [KDL /// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in /// decimal form (e.g. `1234567890`). Base10(i64), /// A [KDL /// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in /// decimal form (e.g. `1234567890.123`), interpreted as a Rust f64. Base10Float(f64), /// A [KDL /// Number](https://github.com/kdl-org/kdl/blob/main/SPEC.md#number) in /// hexadecimal form (e.g. `1234567890abcdef`). Base16(i64), /// A [KDL Boolean](https://github.com/kdl-org/kdl/blob/main/SPEC.md#boolean). Bool(bool), /// The [KDL Null Value](https://github.com/kdl-org/kdl/blob/main/SPEC.md#null). Null, } impl KdlValue { /// Returns `true` if the value is a [`KdlValue::RawString`]. pub fn is_raw_string(&self) -> bool { matches!(self, Self::RawString(..)) } /// Returns `true` if the value is a [`KdlValue::String`]. pub fn is_string(&self) -> bool { matches!(self, Self::String(..)) } /// Returns `true` if the value is a [`KdlValue::String`] or [`KdlValue::RawString`]. pub fn is_string_value(&self) -> bool { matches!(self, Self::String(..) | Self::RawString(..)) } /// Returns `true` if the value is a [`KdlValue::Base2`]. pub fn is_base2(&self) -> bool { matches!(self, Self::Base2(..)) } /// Returns `true` if the value is a [`KdlValue::Base8`]. pub fn is_base8(&self) -> bool { matches!(self, Self::Base8(..)) } /// Returns `true` if the value is a [`KdlValue::Base10`]. pub fn is_base10(&self) -> bool { matches!(self, Self::Base10(..)) } /// Returns `true` if the value is a [`KdlValue::Base16`]. pub fn is_base16(&self) -> bool { matches!(self, Self::Base16(..)) } /// Returns `true` if the value is a [`KdlValue::Base2`], /// [`KdlValue::Base8`], [`KdlValue::Base10`], or [`KdlValue::Base16`]. pub fn is_i64_value(&self) -> bool { matches!( self, Self::Base2(..) | Self::Base8(..) | Self::Base10(..) | Self::Base16(..) ) } /// Returns `true` if the value is a [`KdlValue::Base10Float`]. pub fn is_base10_float(&self) -> bool { matches!(self, Self::Base10Float(..)) } /// Returns `true` if the value is a [`KdlValue::Base10Float`]. pub fn is_float_value(&self) -> bool { matches!(self, Self::Base10Float(..)) } /// Returns `true` if the value is a [`KdlValue::Bool`]. pub fn is_bool(&self) -> bool { matches!(self, Self::Bool(..)) } /// Returns `true` if the value is a [`KdlValue::Null`]. pub fn is_null(&self) -> bool { matches!(self, Self::Null) } /// Returns `Some(&str)` if the `KdlValue` is a [`KdlValue::RawString`] or a /// [`KdlValue::String`], otherwise returns `None`. pub fn as_string(&self) -> Option<&str> { use KdlValue::*; match self { String(s) | RawString(s) => Some(s), _ => None, } } /// Returns `Some(i64)` if the `KdlValue` is a [`KdlValue::Base2`], /// [`KdlValue::Base8`], [`KdlValue::Base10`], or [`KdlValue::Base16`], /// otherwise returns `None`. pub fn as_i64(&self) -> Option<i64> { use KdlValue::*; match self { Base2(i) | Base8(i) | Base10(i) | Base16(i) => Some(*i), _ => None, } } /// Returns `Some(f64)` if the `KdlValue` is a [`KdlValue::Base10Float`], /// otherwise returns `None`. pub fn as_f64(&self) -> Option<f64> { if let Self::Base10Float(v) = self { Some(*v) } else { None } } /// Returns `Some(bool)` if the `KdlValue` is a [`KdlValue::Bool`], otherwise returns `None`. pub fn as_bool(&self) -> Option<bool> { if let Self::Bool(v) = self { Some(*v) } else { None } } } impl Display for KdlValue { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::RawString(_) => self.write_raw_string(f), Self::String(_) => self.write_string(f), Self::Base2(value) => write!(f, "0b{:b}", value), Self::Base8(value) => write!(f, "0o{:o}", value), Self::Base10(value) => write!(f, "{:?}", value), Self::Base10Float(value) => write!( f, "{:?}", if value == &f64::INFINITY { f64::MAX } else if value == &f64::NEG_INFINITY { -f64::MAX } else if value.is_nan() { 0.0 } else { *value } ), Self::Base16(value) => write!(f, "0x{:x}", value), Self::Bool(value) => write!(f, "{}", value), Self::Null => write!(f, "null"), } } } impl KdlValue { fn write_string(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let string = self.as_string().unwrap(); write!(f, "\"")?; for char in string.chars() { match char { '\\' | '"' => write!(f, "\\{}", char)?, '\n' => write!(f, "\\n")?, '\r' => write!(f, "\\r")?, '\t' => write!(f, "\\t")?, '\u{08}' => write!(f, "\\b")?, '\u{0C}' => write!(f, "\\f")?, _ => write!(f, "{}", char)?, } } write!(f, "\"")?; Ok(()) } fn write_raw_string(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let raw = self.as_string().unwrap(); let mut consecutive = 0usize; let mut maxhash = 0usize; for char in raw.chars() { if char == '#' { consecutive += 1; } else if char == '"' { maxhash = maxhash.max(consecutive + 1); } else { consecutive = 0; } } write!(f, "r")?; write!(f, "{}", "#".repeat(maxhash))?; write!(f, "\"{}\"", raw)?; write!(f, "{}", "#".repeat(maxhash))?; Ok(()) } } impl From<i64> for KdlValue { fn from(value: i64) -> Self { KdlValue::Base10(value) } } impl From<f64> for KdlValue { fn from(value: f64) -> Self { KdlValue::Base10Float(value) } } impl From<&str> for KdlValue { fn from(value: &str) -> Self { KdlValue::String(value.to_string()) } } impl From<String> for KdlValue { fn from(value: String) -> Self { KdlValue::String(value) } } impl From<bool> for KdlValue { fn from(value: bool) -> Self { KdlValue::Bool(value) } } impl<T> From<Option<T>> for KdlValue where T: Into<KdlValue>, { fn from(value: Option<T>) -> Self { match value { Some(value) => value.into(), None => KdlValue::Null, } } } #[cfg(test)] mod test { use super::*; #[test] fn formatting() { let raw = KdlValue::RawString(r###"r##"foor#"bar"#baz"##"###.into()); assert_eq!( format!("{}", raw), r####"r###"r##"foor#"bar"#baz"##"###"#### ); let string = KdlValue::String("foo\n".into()); assert_eq!(format!("{}", string), r#""foo\n""#); let base2 = KdlValue::Base2(0b1010_1010); assert_eq!(format!("{}", base2), "0b10101010"); let base8 = KdlValue::Base8(0o12345670); assert_eq!(format!("{}", base8), "0o12345670"); let base10 = KdlValue::Base10(1234567890); assert_eq!(format!("{}", base10), "1234567890"); let base10float = KdlValue::Base10Float(1234567890.12345); assert_eq!(format!("{}", base10float), "1234567890.12345"); let base16 = KdlValue::Base16(0x1234567890ABCDEF); assert_eq!(format!("{}", base16), "0x1234567890abcdef"); let boolean = KdlValue::Bool(true); assert_eq!(format!("{}", boolean), "true"); let null = KdlValue::Null; assert_eq!(format!("{}", null), "null"); } }
//! Functions related to parsing of input #![deny(unused_must_use)] use value::{Value, StringValue}; use error::{ParseError, ParseResult}; use std::io::{Read, BufRead, BufReader}; use std::str::FromStr; use std::cmp::max; use std::collections::VecDeque; use unescape::unescape; macro_rules! parse_err { ( $name:ident, $me:ident ) => { Err(ParseError::$name($me.line, $me.get_col())) } } macro_rules! cons_side { ( $me:ident, $default:block, $($catch:pat => $catch_result:block),*) => {{ try!($me.consume_comments()); if let Some(&c) = try!($me.peek()) { match c { $($catch => $catch_result),* _ => $default, } } else { end_of_file!($me) } }} } macro_rules! cons_err { ( $me:ident, $($err:pat => $err_name:ident),*) => {{ try!($me.consume_comments()); if let Some(&c) = try!($me.peek()) { match c { $($err => parse_err!($err_name, $me),),* _ => $me.parse_expression(), } } else { end_of_file!($me) } }} } macro_rules! end_of_file { ( $me:ident ) => {parse_err!(EndOfFile, $me)} } /** * A parser for a particular `str` * * Parsing expressions requires a parser to be attached to the given string. * * ```rust * use atoms::{Parser, StringValue}; * let text = "(this is a series of symbols)"; * let parser = Parser::new(&text); * let parsed = parser.parse_basic().unwrap(); * assert_eq!( * StringValue::into_list( * vec!["this", "is", "a", "series", "of", "symbols"], * |s| StringValue::symbol(s).unwrap() * ), * parsed * ); * ``` * * The type parameter given to `Parser::parse` is to inform the parser of * how to evaluate symbols. Any type that implements `ToString` and `FromStr` * reflexively can be used here. `String` is just one such, however it would * be trivial to create an `enum` that restricted parsing to pre-defined * symbols. * * A parser has to be attached to a particular `str` to parse it. Really, this * is to allow us to make sane error messages. */ pub struct Parser<R> { reader: BufReader<R>, buffer: VecDeque<char>, line: usize, col: isize, } impl<'a> Parser<&'a [u8]> { /** * Create a new parser for a single expression */ pub fn new<'b>(source: &'b AsRef<[u8]>) -> Parser<&'b [u8]> { Parser::reader(source.as_ref()) } } impl<R: Read> Parser<R> { /** * Create a new parser for a reader. * * The reader can can be a source of series of discrete expressions, * each to be read one at a time. */ pub fn reader(source: R) -> Parser<R> { Parser { reader: BufReader::new(source), buffer: VecDeque::new(), line: 1usize, col: -1isize, } } /** * Read the next expression. * * ```rust * use atoms::{Parser, Value}; * let text = r#" * (this is a series of symbols) * (this is another sexpression) * mono ;Single expression on its own line * (this expression * spans lines) * (these expressions) (share lines) * "#; * let mut parser = Parser::new(&text); * assert_eq!( * parser.read::<String>().unwrap(), * Value::into_list( * vec!["this", "is", "a", "series", "of", "symbols"], * |s| Value::symbol(s).unwrap() * ) * ); * assert_eq!( * parser.read::<String>().unwrap(), * Value::into_list( * vec!["this", "is", "another", "sexpression"], * |s| Value::symbol(s).unwrap() * ) * ); * assert_eq!( * parser.read::<String>().unwrap(), * Value::symbol("mono").unwrap() * ); * assert_eq!( * parser.read::<String>().unwrap(), * Value::into_list( * vec!["this", "expression", "spans", "lines"], * |s| Value::symbol(s).unwrap() * ) * ); * assert_eq!( * parser.read::<String>().unwrap(), * Value::into_list( * vec!["these", "expressions"], * |s| Value::symbol(s).unwrap() * ) * ); * assert_eq!( * parser.read::<String>().unwrap(), * Value::into_list( * vec!["share", "lines"], * |s| Value::symbol(s).unwrap() * ) * ); * ``` * * This parser must be informed of how to represent symbols when they are * parsed. The `Sym` type parameter must implement `FromStr` and `ToString` * reflexively (i.e. the output of `ToString::to_string` for a given value * **must** produce the same value when used with `FromStr::from_str` and * visa versa such that the value can be encoded and decoded the same way). * If no special treatment of symbols is required, `parse_basic` should be * used. * * This will produce parsing errors when `FromStr::from_str` fails when * being used to create symbols. */ pub fn read<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { // Consume the comments try!(self.consume_comments()); self.parse_expression() } /** * Parse the given expression. Consumes the parser. * * If you want to pass a series of expressions, use `read` instead. * * ```rust * use atoms::{Parser, Value}; * let text = "(this is a series of symbols)"; * let parser = Parser::new(&text); * let parsed = parser.parse::<String>().unwrap(); * assert_eq!( * Value::into_list( * vec!["this", "is", "a", "series", "of", "symbols"], * |s| Value::symbol(s).unwrap() * ), * parsed * ); * ``` * * Similar to `read`, the parser must be informed of the type to be used * for expressing symbols. */ pub fn parse<Sym: FromStr>(mut self) -> ParseResult<Value<Sym>> { // Remove leading whitespace try!(self.consume_comments()); let result = try!(self.parse_expression()); // Remove trailing whitespace try!(self.consume_comments()); if let Some(_) = try!(self.next()) { parse_err!(TrailingGarbage, self) } else { Ok(result) } } /** * Parse the given `str` storing symbols as `String`s. Consumes the parser. * * ```rust * use atoms::{Parser, StringValue}; * let text = "(this is a series of symbols)"; * let parser = Parser::new(&text); * let parsed = parser.parse::<String>().unwrap(); * assert_eq!( * StringValue::into_list( * vec!["this", "is", "a", "series", "of", "symbols"], * |s| StringValue::symbol(s).unwrap() * ), * parsed * ); * ``` * * In cases where no special behaviour for symbols is needed, `parse_basic` * will resolve all symbols as `String`s. */ pub fn parse_basic(self) -> ParseResult<StringValue> { self.parse() } /** * Get the column */ fn get_col(&self) -> usize { max(self.col, 0) as usize } /** * Peek at the next value in the buffer */ fn peek(&mut self) -> ParseResult<Option<&char>> { if self.buffer.len() <= 0 { try!(self.extend_buffer()); } Ok(self.buffer.get(0)) } /** * Get the next value */ fn next(&mut self) -> ParseResult<Option<char>> { if self.buffer.len() <= 0 { try!(self.extend_buffer()); } let next_c = self.buffer.pop_front(); // Advance position if possible if let Some(c) = next_c { if c == '\n' { self.line += 1; self.col = -1; } else { self.col += 1; } Ok(Some(c)) } else { Ok(None) } } /** * Get the next line and add to queue */ fn extend_buffer(&mut self) -> ParseResult<()> { let mut line = String::new(); match self.reader.read_line(&mut line) { Ok(_) => { for t in line.chars() { self.buffer.push_back(t); } Ok(()) }, Err(e) => Err(ParseError::BufferError(self.line, self.get_col(), e)) } } /** * Parse a single sexpression */ fn parse_expression<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { // Consume leading comments try!(self.consume_comments()); self.parse_immediate() } /** * Parse the next immediate expression */ fn parse_immediate<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { if let Some(&c) = try!(self.peek()) { match c { // String literal '"' => self.parse_quoted(), // Start of cons '(' => { try!(self.next()); self.parse_cons() }, // End of Cons ')' => { try!(self.next()); parse_err!(ClosingParen, self) }, // Extension '#' => { try!(self.next()); parse_err!(NoExtensions, self) }, // Quoting '\'' => { try!(self.next()); Ok(Value::data(try!(self.parse_immediate()))) }, '`' => { try!(self.next()); Ok(Value::data(try!(self.parse_immediate()))) }, ',' => { try!(self.next()); Ok(Value::code(try!(self.parse_immediate()))) }, // Automatic value _ => self.parse_value(), } } else { end_of_file!(self) } } /** * Parse a Cons */ fn parse_cons<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { let left = try!(cons_side!(self, {self.parse_immediate()}, ')' => { try!(self.next()); return Ok(Value::Nil) } )); // Get right half of cons let right = try!(cons_side!(self, {self.parse_cons()}, // Nil if immediate close ')' => { try!(self.next()); Ok(Value::Nil) }, // Might be cons pair if starting with . '.' => { self.parse_cons_rest() } )); Ok(Value::cons(left, right)) } fn parse_cons_rest<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { let next_val = try!(self.unescape_value()); if next_val == "." { // Cons join try!(self.consume_comments()); let value = cons_err!(self, ')' => ConsWithoutRight ); try!(self.consume_comments()); if let Some(c) = try!(self.next()) { if c != ')' { parse_err!(ConsWithoutClose, self) } else { value } } else { end_of_file!(self) } } else { // List Ok(Value::cons( try!(self.value_from_string(&next_val)), try!(self.parse_cons()) )) } } /** * Extract a value up until the given delimiter. Does not consume delimiter. */ fn extract_delimited(&mut self, delimiter: &Fn(char) -> bool, allow_eof: bool) -> ParseResult<String> { let mut value = String::new(); // Push each following character into the parsed string while let Some(&preview) = try!(self.peek()) { if preview == '\\' { let c = try!(self.next()).unwrap(); value.push(c); if let Some(follower) = try!(self.next()) { value.push(follower); } else { return end_of_file!(self); } } else if delimiter(preview) { return Ok(value); } else { let c = try!(self.next()).unwrap(); value.push(c); } } // Throw an error if we aren't expecting an end of file if allow_eof { Ok(value) } else { end_of_file!(self) } } /** * Parse a quoted value */ fn parse_quoted<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { // remove leading quote try!(self.next()).unwrap(); // parsed string value let unquoted = try!(self.extract_delimited(&(|c| c == '"'), false)); // remove trailing quote try!(self.next()).unwrap(); Ok(Value::string(try!(self.parse_text(&unquoted)))) } /** * Extract a single string escaped value */ fn unescape_value(&mut self) -> ParseResult<String> { let text = try!(self.extract_delimited(&default_delimit, true)).escape_special(); self.parse_text(&text) } /** * Parse a an escaped text (symbol or string) */ fn parse_text(&mut self, s: &AsRef<str>) -> ParseResult<String> { if let Some(parsed) = unescape(s.as_ref()) { Ok(parsed) } else { parse_err!(StringLiteral, self) } } /** * Parse the next value into a type */ fn parse_value<Sym: FromStr>(&mut self) -> ParseResult<Value<Sym>> { let text = try!(self.unescape_value()); self.value_from_string(&text) } /** * Parse a string into a value */ fn value_from_string<Sym: FromStr>(&mut self, text: &str) -> ParseResult<Value<Sym>> { // Try make an integer match i64::from_str(&text) { Ok(i) => return Ok(Value::int(i)), _ => {}, } // Try make a float match f64::from_str(&text) { Ok(f) => return Ok(Value::float(f)), _ => {}, } // Try make a symbol if text.len() == 0usize { parse_err!(EmptySymbol, self) } else if let Some(sym) = Value::symbol(&text) { Ok(sym) } else { parse_err!(SymbolEncode, self) } } /** * Consume whitespace */ fn consume_whitespace(&mut self) -> ParseResult<()> { while let Some(&c) = try!(self.peek()) { if c.is_whitespace() { try!(self.next()); } else { return Ok(()); } } Ok(()) } /** * Consume the remaining line of text */ fn consume_line(&mut self) -> ParseResult<()> { while let Some(c) = try!(self.next()) { if c == '\n' { return Ok(()); } } Ok(()) } /** * Consume blocks of comments */ fn consume_comments(&mut self) -> ParseResult<()> { try!(self.consume_whitespace()); while let Some(&c) = try!(self.peek()) { if c == ';' { try!(self.consume_line()); } else if c.is_whitespace() { try!(self.consume_whitespace()); } else { return Ok(()); } } Ok(()) } } /** * Additional characters to escape in strings */ trait EscapeSpecial { fn escape_special(self) -> Self; } impl EscapeSpecial for String { fn escape_special(self) -> String { self.replace("\\ ", " ") .replace("\\;", ";") .replace("\\(", "(") .replace("\\)", ")") .replace("\\\"", "\"") .replace("\\\'", "\'") .replace("\\`", "`") .replace("\\,", ",") .replace("\\\\", "\\") } } /** * Default predicate for delimitation is whitespace */ fn default_delimit(c: char) -> bool { c.is_whitespace() || c == ';' || c == '(' || c == ')' || c == '"' } #[test] fn single_element() { let text = "(one)"; let output = Value::list(vec![Value::symbol("one").unwrap()]); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn unary_test() { fn unary(text: &'static str, output: Value<String>) { let parser = Parser::new(&text); assert_eq!(parser.parse().unwrap(), output); } unary("()", Value::Nil); unary("one", Value::symbol("one").unwrap()); unary("2", Value::int(2)); unary("3.0", Value::float(3.0)); unary("\"four\"", Value::string("four")); } #[test] fn integer_test() { let text = "(1 2 3 4 5)"; let nums = vec![1, 2, 3, 4, 5].iter().map(|i| Value::int(*i)).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn float_test() { let text = "(1.0 2.0 3.0 4.0 5.0)"; let nums = vec![1.0, 2.0, 3.0, 4.0, 5.0].iter().map(|f| Value::float(*f)).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn string_test() { let text = "(\"one\" \"two\" \"three\" \"four\" \"five\")"; let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::string(*s)).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn symbol_test() { let text = "(one two three four five)"; let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn nesting_test() { let text = "(one (two three) (four five))"; let inner_one = Value::list(vec!["two", "three"].iter().map(|s| Value::symbol(*s).unwrap()).collect()); let inner_two = Value::list(vec!["four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect()); let output = Value::list(vec![Value::symbol("one").unwrap(), inner_one, inner_two]); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn space_escape_test() { let text = "(one\\ two\\ three\\ four\\ five)"; let output = Value::list(vec![Value::symbol("one two three four five").unwrap()]); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn comment_test() { let text = " ;comment\n (one;comment\n two ;;;comment with space\n three four five) ;trailing comment\n ;end"; let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn skip_whitespace_test() { let text = " \n \t ( \n\t one two \n\t three \n\t four five \t \n ) \n \t"; let nums = vec!["one", "two", "three", "four", "five"].iter().map(|s| Value::symbol(*s).unwrap()).collect(); let output = Value::list(nums); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn trailing_garbage_test() { let text = "(one two three four five) ;not garbage\n garbage"; let parser = Parser::new(&text); assert!(parser.parse::<String>().is_err()); } #[test] fn escape_parsing_test() { let text = "(one\\ two 3 4 \"five\\\\is\\ta\\rless\\nmagic\\\'number\\\"\")"; let output = Value::list(vec![ Value::symbol("one two").unwrap(), Value::int(3), Value::int(4), Value::string("five\\is\ta\rless\nmagic\'number\"") ]); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn cons_parsing() { let text = "(one . (two . (three . four)))"; let output = Value::cons( Value::symbol("one").unwrap(), Value::cons( Value::symbol("two").unwrap(), Value::cons( Value::symbol("three").unwrap(), Value::symbol("four").unwrap(), ), ), ); let parser = Parser::new(&text); assert_eq!(parser.parse::<String>().unwrap(), output); } #[test] fn trailing_cons() { let text = "(one two three . four)"; let output = Value::cons( Value::symbol("one").unwrap(), Value::cons( Value::symbol("two").unwrap(), Value::cons( Value::symbol("three").unwrap(), Value::symbol("four").unwrap(), ), ), ); let two = StringValue::symbol("one").unwrap(); let output_short = s_tree!(StringValue: (two . ([two] . ([three] . [four])))); let parsed = Parser::new(&text).parse::<String>().unwrap(); assert_eq!(parsed, output); assert_eq!(parsed, output_short); } #[test] fn split_cons() { let text = "(one . two . three . four)"; let parser = Parser::new(&text); assert!(parser.parse::<String>().is_err()); } #[test] fn github_issues() { fn parse_text(text: &'static str) -> ParseResult<StringValue> { let parser = Parser::new(&text); parser.parse::<String>() } assert!(parse_text("(a #;(c d) e)").is_err()); assert_eq!( parse_text("(a . () \n \t)").unwrap(), s_tree!(StringValue: ([a])) ); assert_eq!( parse_text("(((())))").unwrap(), s_tree!(StringValue: (((())))) ); } #[test] fn quasiquoting() { fn parse_text(text: &'static str) -> StringValue { let parser = Parser::new(&text); parser.parse::<String>().unwrap() } assert_eq!( parse_text("(this is 'data)"), s_tree!(StringValue: ([this] [is] [d:[data]])) ); assert_eq!( parse_text("'(this is 'data)"), s_tree!(StringValue: [d:([this] [is] [d:[data]])]) ); assert_eq!( parse_text("'(this is ,quasiquoted ,(data that is '2 layers 'deep))"), s_tree!(StringValue: [d:([this] [is] [c:[quasiquoted]] [c:( [data] [that] [is] [d:2] [layers] [d:[deep]] )])] ) ); assert_eq!( parse_text("('this \n;comment here for effect\nshould probably work...)"), s_tree!(StringValue: ([d:[this]] [should] [probably][s:"work..."])) ); assert_eq!( parse_text("('\\;comment \nshould probably work...)"), s_tree!(StringValue: ([d:[s:";comment"]] [should] [probably] [s:"work..."])) ); assert_eq!( parse_text("`,`,`,`,`,data"), s_tree!(StringValue: [d:[c:[d:[c:[d:[c:[d:[c:[d:[c:[data]]]]]]]]]]]) ); assert_eq!( parse_text("`,`,`,`,`,data").unwrap_full(), s_tree!(StringValue: [data]) ); assert_eq!( parse_text("`(,(left `right . `last) ,middle end)").unwrap_full(), s_tree!(StringValue: (([left] . ([right] . [last])) [middle] [end])) ); } #[test] fn symmetric_encoding() { fn check(text: &'static str) { assert_eq!( Parser::new(&text).parse::<String>().unwrap().to_string(), text ); } check("one"); check("12"); check("3.152"); check("3.0"); check("-1.0"); check("(a b c d)"); check("(a b c . d)"); check("this\\;uses\\\"odd\\(chars\\)\\ space"); }
use super::colors::*; use std::collections::BTreeMap; // TODO: use new types so they can be converted into intermediate outputs automatically pub trait Outputter { fn output(&self, output: Output, eol: bool); fn clear(&self); } impl<'a> From<&'a str> for Output { fn from(s: &'a str) -> Self { Output::new().add(s).build() } } #[derive(Debug, PartialEq, Clone)] pub struct Output { pub data: String, pub colors: Vec<(::std::ops::Range<usize>, ColorPair)>, } impl Output { pub fn stamp() -> OutputBuilder { use chrono::prelude::*; let mut builder = OutputBuilder::new(); let now: DateTime<Local> = Local::now(); let ts = format!("{:02}{:02}{:02} ", now.hour(), now.minute(), now.second()); builder.add(&ts); builder } pub fn new() -> OutputBuilder { OutputBuilder::new() } } #[derive(Default)] pub struct OutputBuilder { parts: Vec<String>, colors: BTreeMap<usize, ColorPair>, index: usize, } impl OutputBuilder { pub fn new() -> Self { Self { parts: vec![], colors: BTreeMap::new(), index: 0, } } pub fn bold(&mut self) -> &mut Self { let entry = self.colors.entry(self.index); entry .or_insert_with(|| ColorPair::new(true, Color::White, None)) .bold = true; self } pub fn underline(&mut self) -> &mut Self { let entry = self.colors.entry(self.index); entry .or_insert_with(|| ColorPair::new(false, Color::White, None)) .underline = true; self } pub fn fg(&mut self, c: impl Into<Color>) -> &mut Self { let c = c.into(); let entry = self.colors.entry(self.index); entry.or_insert_with(|| ColorPair::new(false, c, None)).fg = c; self } pub fn bg(&mut self, c: impl Into<Color>) -> &mut Self { let c = c.into(); let entry = self.colors.entry(self.index); entry .or_insert_with(|| ColorPair::new(false, Color::White, Some(c))) .bg = c; self } pub fn add<T>(&mut self, s: T) -> &mut Self where T: AsRef<str>, { self.colors .entry(self.index) .or_insert_with(|| ColorPair::new(false, Color::White, None)); let s = s.as_ref().to_owned(); self.index += s.len(); self.parts.push(s); self } pub fn build(&self) -> Output { Output { colors: self.colors.iter().zip(self.parts.iter()).fold( Vec::new(), |mut a, ((k, v), s)| { a.push(((*k..*k + s.len()), *v)); a }, ), data: self.parts.iter().fold(String::new(), |mut a, c| { a.push_str(c); a }), } } }
use super::super::pystring::{PyString, StringInfo}; use super::{check_dtype, HasPandasColumn, PandasColumn, PandasColumnObject, GIL_MUTEX}; use crate::constants::PYSTRING_BUFFER_SIZE; use crate::errors::ConnectorXPythonError; use anyhow::anyhow; use fehler::throws; use itertools::Itertools; use ndarray::{ArrayViewMut2, Axis, Ix2}; use numpy::PyArray; use pyo3::{FromPyObject, PyAny, PyResult, Python}; use std::any::TypeId; pub struct StringBlock<'a> { data: ArrayViewMut2<'a, PyString>, buf_size_mb: usize, } impl<'a> FromPyObject<'a> for StringBlock<'a> { fn extract(ob: &'a PyAny) -> PyResult<Self> { check_dtype(ob, "object")?; let array = ob.downcast::<PyArray<PyString, Ix2>>()?; let data = unsafe { array.as_array_mut() }; Ok(StringBlock { data, buf_size_mb: PYSTRING_BUFFER_SIZE, // in MB }) } } impl<'a> StringBlock<'a> { #[throws(ConnectorXPythonError)] pub fn split(self) -> Vec<StringColumn> { let mut ret = vec![]; let mut view = self.data; let nrows = view.ncols(); while view.nrows() > 0 { let (col, rest) = view.split_at(Axis(0), 1); view = rest; ret.push(StringColumn { data: col .into_shape(nrows)? .into_slice() .ok_or_else(|| anyhow!("get None for splitted String data"))? .as_mut_ptr(), string_lengths: vec![], row_idx: vec![], string_buf: Vec::with_capacity(self.buf_size_mb * (1 << 20) * 11 / 10), // allocate a little bit more memory to avoid Vec growth buf_size: self.buf_size_mb * (1 << 20), }) } ret } } pub struct StringColumn { data: *mut PyString, string_buf: Vec<u8>, string_lengths: Vec<usize>, // usize::MAX for empty string row_idx: Vec<usize>, buf_size: usize, } unsafe impl Send for StringColumn {} unsafe impl Sync for StringColumn {} impl PandasColumnObject for StringColumn { fn typecheck(&self, id: TypeId) -> bool { id == TypeId::of::<&'static [u8]>() || id == TypeId::of::<Option<&'static [u8]>>() } fn typename(&self) -> &'static str { std::any::type_name::<&'static [u8]>() } #[throws(ConnectorXPythonError)] fn finalize(&mut self) { self.flush(true)?; } } impl<'r> PandasColumn<&'r str> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: &'r str, row: usize) { let bytes = val.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } } impl PandasColumn<Box<str>> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Box<str>, row: usize) { let bytes = val.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } } impl PandasColumn<String> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: String, row: usize) { let bytes = val.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } } impl PandasColumn<char> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: char, row: usize) { let mut buffer = [0; 4]; // a char is max to 4 bytes let bytes = val.encode_utf8(&mut buffer).as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } } impl<'r> PandasColumn<Option<&'r str>> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Option<&'r str>, row: usize) { match val { Some(b) => { let bytes = b.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } None => { self.string_lengths.push(usize::MAX); self.row_idx.push(row); } } } } impl PandasColumn<Option<Box<str>>> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Option<Box<str>>, row: usize) { match val { Some(b) => { let bytes = b.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } None => { self.string_lengths.push(usize::MAX); self.row_idx.push(row); } } } } impl PandasColumn<Option<String>> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Option<String>, row: usize) { match val { Some(b) => { let bytes = b.as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } None => { self.string_lengths.push(usize::MAX); self.row_idx.push(row); } } } } impl PandasColumn<Option<char>> for StringColumn { #[throws(ConnectorXPythonError)] fn write(&mut self, val: Option<char>, row: usize) { match val { Some(b) => { let mut buffer = [0; 4]; // a char is max to 4 bytes let bytes = b.encode_utf8(&mut buffer).as_bytes(); self.string_lengths.push(bytes.len()); self.string_buf.extend_from_slice(bytes); self.row_idx.push(row); self.try_flush()?; } None => { self.string_lengths.push(usize::MAX); self.row_idx.push(row); } } } } impl<'r> HasPandasColumn for &'r str { type PandasColumn<'a> = StringColumn; } impl<'r> HasPandasColumn for Option<&'r str> { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for String { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for Option<String> { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for char { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for Option<char> { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for Box<str> { type PandasColumn<'a> = StringColumn; } impl HasPandasColumn for Option<Box<str>> { type PandasColumn<'a> = StringColumn; } impl StringColumn { pub fn partition(self, counts: usize) -> Vec<StringColumn> { let mut partitions = vec![]; for _ in 0..counts { partitions.push(StringColumn { data: self.data, string_lengths: vec![], row_idx: vec![], string_buf: Vec::with_capacity(self.buf_size), buf_size: self.buf_size, }); } partitions } #[throws(ConnectorXPythonError)] pub fn flush(&mut self, force: bool) { let nstrings = self.string_lengths.len(); if nstrings == 0 { return; } let guard = if force { GIL_MUTEX .lock() .map_err(|e| anyhow!("mutex poisoned {}", e))? } else { match GIL_MUTEX.try_lock() { Ok(guard) => guard, Err(_) => return, } }; let py = unsafe { Python::assume_gil_acquired() }; let mut string_infos = Vec::with_capacity(self.string_lengths.len()); let mut start = 0; for (i, &len) in self.string_lengths.iter().enumerate() { if len != usize::MAX { let end = start + len; unsafe { let string_info = StringInfo::detect(&self.string_buf[start..end]); *self.data.add(self.row_idx[i]) = string_info.pystring(py); string_infos.push(Some(string_info)); }; start = end; } else { string_infos.push(None); unsafe { *self.data.add(self.row_idx[i]) = PyString::none(py) }; } } // unlock GIL std::mem::drop(guard); if !string_infos.is_empty() { let mut start = 0; for (i, (len, info)) in self .string_lengths .drain(..) .zip_eq(string_infos) .enumerate() { if len != usize::MAX { let end = start + len; unsafe { (*self.data.add(self.row_idx[i])) .write(&self.string_buf[start..end], info.unwrap()) }; start = end; } } self.string_buf.truncate(0); self.row_idx.truncate(0); } } #[throws(ConnectorXPythonError)] pub fn try_flush(&mut self) { if self.string_buf.len() >= self.buf_size { self.flush(true)?; return; } #[cfg(feature = "nbstr")] if self.string_buf.len() >= self.buf_size / 2 { self.flush(false)?; } } }
#[doc = "Reader of register RCC_MP_APB1ENSETR"] pub type R = crate::R<u32, super::RCC_MP_APB1ENSETR>; #[doc = "Writer for register RCC_MP_APB1ENSETR"] pub type W = crate::W<u32, super::RCC_MP_APB1ENSETR>; #[doc = "Register RCC_MP_APB1ENSETR `reset()`'s with value 0"] impl crate::ResetValue for super::RCC_MP_APB1ENSETR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "TIM2EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM2EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM2EN_A> for bool { #[inline(always)] fn from(variant: TIM2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM2EN`"] pub type TIM2EN_R = crate::R<bool, TIM2EN_A>; impl TIM2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM2EN_A { match self.bits { false => TIM2EN_A::B_0X0, true => TIM2EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM2EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM2EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM2EN`"] pub struct TIM2EN_W<'a> { w: &'a mut W, } impl<'a> TIM2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM2EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM2EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "TIM3EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM3EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM3EN_A> for bool { #[inline(always)] fn from(variant: TIM3EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM3EN`"] pub type TIM3EN_R = crate::R<bool, TIM3EN_A>; impl TIM3EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM3EN_A { match self.bits { false => TIM3EN_A::B_0X0, true => TIM3EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM3EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM3EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM3EN`"] pub struct TIM3EN_W<'a> { w: &'a mut W, } impl<'a> TIM3EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM3EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM3EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM3EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "TIM4EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM4EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM4EN_A> for bool { #[inline(always)] fn from(variant: TIM4EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM4EN`"] pub type TIM4EN_R = crate::R<bool, TIM4EN_A>; impl TIM4EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM4EN_A { match self.bits { false => TIM4EN_A::B_0X0, true => TIM4EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM4EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM4EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM4EN`"] pub struct TIM4EN_W<'a> { w: &'a mut W, } impl<'a> TIM4EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM4EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM4EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM4EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } #[doc = "TIM5EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM5EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM5EN_A> for bool { #[inline(always)] fn from(variant: TIM5EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM5EN`"] pub type TIM5EN_R = crate::R<bool, TIM5EN_A>; impl TIM5EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM5EN_A { match self.bits { false => TIM5EN_A::B_0X0, true => TIM5EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM5EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM5EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM5EN`"] pub struct TIM5EN_W<'a> { w: &'a mut W, } impl<'a> TIM5EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM5EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM5EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM5EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3); self.w } } #[doc = "TIM6EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM6EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM6EN_A> for bool { #[inline(always)] fn from(variant: TIM6EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM6EN`"] pub type TIM6EN_R = crate::R<bool, TIM6EN_A>; impl TIM6EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM6EN_A { match self.bits { false => TIM6EN_A::B_0X0, true => TIM6EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM6EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM6EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM6EN`"] pub struct TIM6EN_W<'a> { w: &'a mut W, } impl<'a> TIM6EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM6EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM6EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM6EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "TIM7EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM7EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM7EN_A> for bool { #[inline(always)] fn from(variant: TIM7EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM7EN`"] pub type TIM7EN_R = crate::R<bool, TIM7EN_A>; impl TIM7EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM7EN_A { match self.bits { false => TIM7EN_A::B_0X0, true => TIM7EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM7EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM7EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM7EN`"] pub struct TIM7EN_W<'a> { w: &'a mut W, } impl<'a> TIM7EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM7EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM7EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM7EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5); self.w } } #[doc = "TIM12EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM12EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM12EN_A> for bool { #[inline(always)] fn from(variant: TIM12EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM12EN`"] pub type TIM12EN_R = crate::R<bool, TIM12EN_A>; impl TIM12EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM12EN_A { match self.bits { false => TIM12EN_A::B_0X0, true => TIM12EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM12EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM12EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM12EN`"] pub struct TIM12EN_W<'a> { w: &'a mut W, } impl<'a> TIM12EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM12EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM12EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM12EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6); self.w } } #[doc = "TIM13EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM13EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM13EN_A> for bool { #[inline(always)] fn from(variant: TIM13EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM13EN`"] pub type TIM13EN_R = crate::R<bool, TIM13EN_A>; impl TIM13EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM13EN_A { match self.bits { false => TIM13EN_A::B_0X0, true => TIM13EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM13EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM13EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM13EN`"] pub struct TIM13EN_W<'a> { w: &'a mut W, } impl<'a> TIM13EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM13EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM13EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM13EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "TIM14EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TIM14EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<TIM14EN_A> for bool { #[inline(always)] fn from(variant: TIM14EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TIM14EN`"] pub type TIM14EN_R = crate::R<bool, TIM14EN_A>; impl TIM14EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIM14EN_A { match self.bits { false => TIM14EN_A::B_0X0, true => TIM14EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == TIM14EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == TIM14EN_A::B_0X1 } } #[doc = "Write proxy for field `TIM14EN`"] pub struct TIM14EN_W<'a> { w: &'a mut W, } impl<'a> TIM14EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TIM14EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(TIM14EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(TIM14EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } #[doc = "LPTIM1EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LPTIM1EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<LPTIM1EN_A> for bool { #[inline(always)] fn from(variant: LPTIM1EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `LPTIM1EN`"] pub type LPTIM1EN_R = crate::R<bool, LPTIM1EN_A>; impl LPTIM1EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> LPTIM1EN_A { match self.bits { false => LPTIM1EN_A::B_0X0, true => LPTIM1EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == LPTIM1EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == LPTIM1EN_A::B_0X1 } } #[doc = "Write proxy for field `LPTIM1EN`"] pub struct LPTIM1EN_W<'a> { w: &'a mut W, } impl<'a> LPTIM1EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: LPTIM1EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(LPTIM1EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(LPTIM1EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "SPI2EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SPI2EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<SPI2EN_A> for bool { #[inline(always)] fn from(variant: SPI2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SPI2EN`"] pub type SPI2EN_R = crate::R<bool, SPI2EN_A>; impl SPI2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SPI2EN_A { match self.bits { false => SPI2EN_A::B_0X0, true => SPI2EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == SPI2EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == SPI2EN_A::B_0X1 } } #[doc = "Write proxy for field `SPI2EN`"] pub struct SPI2EN_W<'a> { w: &'a mut W, } impl<'a> SPI2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SPI2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(SPI2EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(SPI2EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "SPI3EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SPI3EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<SPI3EN_A> for bool { #[inline(always)] fn from(variant: SPI3EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SPI3EN`"] pub type SPI3EN_R = crate::R<bool, SPI3EN_A>; impl SPI3EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SPI3EN_A { match self.bits { false => SPI3EN_A::B_0X0, true => SPI3EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == SPI3EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == SPI3EN_A::B_0X1 } } #[doc = "Write proxy for field `SPI3EN`"] pub struct SPI3EN_W<'a> { w: &'a mut W, } impl<'a> SPI3EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SPI3EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(SPI3EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(SPI3EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "USART2EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USART2EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<USART2EN_A> for bool { #[inline(always)] fn from(variant: USART2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `USART2EN`"] pub type USART2EN_R = crate::R<bool, USART2EN_A>; impl USART2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USART2EN_A { match self.bits { false => USART2EN_A::B_0X0, true => USART2EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == USART2EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == USART2EN_A::B_0X1 } } #[doc = "Write proxy for field `USART2EN`"] pub struct USART2EN_W<'a> { w: &'a mut W, } impl<'a> USART2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USART2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(USART2EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(USART2EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "USART3EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USART3EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<USART3EN_A> for bool { #[inline(always)] fn from(variant: USART3EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `USART3EN`"] pub type USART3EN_R = crate::R<bool, USART3EN_A>; impl USART3EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> USART3EN_A { match self.bits { false => USART3EN_A::B_0X0, true => USART3EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == USART3EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == USART3EN_A::B_0X1 } } #[doc = "Write proxy for field `USART3EN`"] pub struct USART3EN_W<'a> { w: &'a mut W, } impl<'a> USART3EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: USART3EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(USART3EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(USART3EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "UART4EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UART4EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<UART4EN_A> for bool { #[inline(always)] fn from(variant: UART4EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UART4EN`"] pub type UART4EN_R = crate::R<bool, UART4EN_A>; impl UART4EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UART4EN_A { match self.bits { false => UART4EN_A::B_0X0, true => UART4EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == UART4EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == UART4EN_A::B_0X1 } } #[doc = "Write proxy for field `UART4EN`"] pub struct UART4EN_W<'a> { w: &'a mut W, } impl<'a> UART4EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UART4EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(UART4EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(UART4EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "UART5EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UART5EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<UART5EN_A> for bool { #[inline(always)] fn from(variant: UART5EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UART5EN`"] pub type UART5EN_R = crate::R<bool, UART5EN_A>; impl UART5EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UART5EN_A { match self.bits { false => UART5EN_A::B_0X0, true => UART5EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == UART5EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == UART5EN_A::B_0X1 } } #[doc = "Write proxy for field `UART5EN`"] pub struct UART5EN_W<'a> { w: &'a mut W, } impl<'a> UART5EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UART5EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(UART5EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(UART5EN_A::B_0X1) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "UART7EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UART7EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<UART7EN_A> for bool { #[inline(always)] fn from(variant: UART7EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UART7EN`"] pub type UART7EN_R = crate::R<bool, UART7EN_A>; impl UART7EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UART7EN_A { match self.bits { false => UART7EN_A::B_0X0, true => UART7EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == UART7EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == UART7EN_A::B_0X1 } } #[doc = "Write proxy for field `UART7EN`"] pub struct UART7EN_W<'a> { w: &'a mut W, } impl<'a> UART7EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UART7EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(UART7EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(UART7EN_A::B_0X1) } #[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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "UART8EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum UART8EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<UART8EN_A> for bool { #[inline(always)] fn from(variant: UART8EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `UART8EN`"] pub type UART8EN_R = crate::R<bool, UART8EN_A>; impl UART8EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> UART8EN_A { match self.bits { false => UART8EN_A::B_0X0, true => UART8EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == UART8EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == UART8EN_A::B_0X1 } } #[doc = "Write proxy for field `UART8EN`"] pub struct UART8EN_W<'a> { w: &'a mut W, } impl<'a> UART8EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: UART8EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(UART8EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(UART8EN_A::B_0X1) } #[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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "I2C1EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum I2C1EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<I2C1EN_A> for bool { #[inline(always)] fn from(variant: I2C1EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `I2C1EN`"] pub type I2C1EN_R = crate::R<bool, I2C1EN_A>; impl I2C1EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> I2C1EN_A { match self.bits { false => I2C1EN_A::B_0X0, true => I2C1EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == I2C1EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == I2C1EN_A::B_0X1 } } #[doc = "Write proxy for field `I2C1EN`"] pub struct I2C1EN_W<'a> { w: &'a mut W, } impl<'a> I2C1EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: I2C1EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(I2C1EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(I2C1EN_A::B_0X1) } #[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 << 21)) | (((value as u32) & 0x01) << 21); self.w } } #[doc = "I2C2EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum I2C2EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<I2C2EN_A> for bool { #[inline(always)] fn from(variant: I2C2EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `I2C2EN`"] pub type I2C2EN_R = crate::R<bool, I2C2EN_A>; impl I2C2EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> I2C2EN_A { match self.bits { false => I2C2EN_A::B_0X0, true => I2C2EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == I2C2EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == I2C2EN_A::B_0X1 } } #[doc = "Write proxy for field `I2C2EN`"] pub struct I2C2EN_W<'a> { w: &'a mut W, } impl<'a> I2C2EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: I2C2EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(I2C2EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(I2C2EN_A::B_0X1) } #[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 << 22)) | (((value as u32) & 0x01) << 22); self.w } } #[doc = "I2C3EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum I2C3EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<I2C3EN_A> for bool { #[inline(always)] fn from(variant: I2C3EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `I2C3EN`"] pub type I2C3EN_R = crate::R<bool, I2C3EN_A>; impl I2C3EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> I2C3EN_A { match self.bits { false => I2C3EN_A::B_0X0, true => I2C3EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == I2C3EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == I2C3EN_A::B_0X1 } } #[doc = "Write proxy for field `I2C3EN`"] pub struct I2C3EN_W<'a> { w: &'a mut W, } impl<'a> I2C3EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: I2C3EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(I2C3EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(I2C3EN_A::B_0X1) } #[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 << 23)) | (((value as u32) & 0x01) << 23); self.w } } #[doc = "I2C5EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum I2C5EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<I2C5EN_A> for bool { #[inline(always)] fn from(variant: I2C5EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `I2C5EN`"] pub type I2C5EN_R = crate::R<bool, I2C5EN_A>; impl I2C5EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> I2C5EN_A { match self.bits { false => I2C5EN_A::B_0X0, true => I2C5EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == I2C5EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == I2C5EN_A::B_0X1 } } #[doc = "Write proxy for field `I2C5EN`"] pub struct I2C5EN_W<'a> { w: &'a mut W, } impl<'a> I2C5EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: I2C5EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(I2C5EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(I2C5EN_A::B_0X1) } #[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 << 24)) | (((value as u32) & 0x01) << 24); self.w } } #[doc = "SPDIFEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SPDIFEN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<SPDIFEN_A> for bool { #[inline(always)] fn from(variant: SPDIFEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SPDIFEN`"] pub type SPDIFEN_R = crate::R<bool, SPDIFEN_A>; impl SPDIFEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SPDIFEN_A { match self.bits { false => SPDIFEN_A::B_0X0, true => SPDIFEN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == SPDIFEN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == SPDIFEN_A::B_0X1 } } #[doc = "Write proxy for field `SPDIFEN`"] pub struct SPDIFEN_W<'a> { w: &'a mut W, } impl<'a> SPDIFEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SPDIFEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(SPDIFEN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(SPDIFEN_A::B_0X1) } #[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 << 26)) | (((value as u32) & 0x01) << 26); self.w } } #[doc = "CECEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CECEN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<CECEN_A> for bool { #[inline(always)] fn from(variant: CECEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CECEN`"] pub type CECEN_R = crate::R<bool, CECEN_A>; impl CECEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CECEN_A { match self.bits { false => CECEN_A::B_0X0, true => CECEN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == CECEN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == CECEN_A::B_0X1 } } #[doc = "Write proxy for field `CECEN`"] pub struct CECEN_W<'a> { w: &'a mut W, } impl<'a> CECEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CECEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(CECEN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(CECEN_A::B_0X1) } #[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 << 27)) | (((value as u32) & 0x01) << 27); self.w } } #[doc = "DAC12EN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DAC12EN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<DAC12EN_A> for bool { #[inline(always)] fn from(variant: DAC12EN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DAC12EN`"] pub type DAC12EN_R = crate::R<bool, DAC12EN_A>; impl DAC12EN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DAC12EN_A { match self.bits { false => DAC12EN_A::B_0X0, true => DAC12EN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == DAC12EN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == DAC12EN_A::B_0X1 } } #[doc = "Write proxy for field `DAC12EN`"] pub struct DAC12EN_W<'a> { w: &'a mut W, } impl<'a> DAC12EN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DAC12EN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(DAC12EN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(DAC12EN_A::B_0X1) } #[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 << 29)) | (((value as u32) & 0x01) << 29); self.w } } #[doc = "MDIOSEN\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MDIOSEN_A { #[doc = "0: Writing has no effect, reading means\r\n that the peripheral clocks are\r\n disabled"] B_0X0 = 0, #[doc = "1: Writing enables the peripheral\r\n clocks, reading means that the peripheral clocks\r\n are enabled"] B_0X1 = 1, } impl From<MDIOSEN_A> for bool { #[inline(always)] fn from(variant: MDIOSEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MDIOSEN`"] pub type MDIOSEN_R = crate::R<bool, MDIOSEN_A>; impl MDIOSEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MDIOSEN_A { match self.bits { false => MDIOSEN_A::B_0X0, true => MDIOSEN_A::B_0X1, } } #[doc = "Checks if the value of the field is `B_0X0`"] #[inline(always)] pub fn is_b_0x0(&self) -> bool { *self == MDIOSEN_A::B_0X0 } #[doc = "Checks if the value of the field is `B_0X1`"] #[inline(always)] pub fn is_b_0x1(&self) -> bool { *self == MDIOSEN_A::B_0X1 } } #[doc = "Write proxy for field `MDIOSEN`"] pub struct MDIOSEN_W<'a> { w: &'a mut W, } impl<'a> MDIOSEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MDIOSEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Writing has no effect, reading means that the peripheral clocks are disabled"] #[inline(always)] pub fn b_0x0(self) -> &'a mut W { self.variant(MDIOSEN_A::B_0X0) } #[doc = "Writing enables the peripheral clocks, reading means that the peripheral clocks are enabled"] #[inline(always)] pub fn b_0x1(self) -> &'a mut W { self.variant(MDIOSEN_A::B_0X1) } #[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 = "Bit 0 - TIM2EN"] #[inline(always)] pub fn tim2en(&self) -> TIM2EN_R { TIM2EN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TIM3EN"] #[inline(always)] pub fn tim3en(&self) -> TIM3EN_R { TIM3EN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - TIM4EN"] #[inline(always)] pub fn tim4en(&self) -> TIM4EN_R { TIM4EN_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - TIM5EN"] #[inline(always)] pub fn tim5en(&self) -> TIM5EN_R { TIM5EN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - TIM6EN"] #[inline(always)] pub fn tim6en(&self) -> TIM6EN_R { TIM6EN_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bit 5 - TIM7EN"] #[inline(always)] pub fn tim7en(&self) -> TIM7EN_R { TIM7EN_R::new(((self.bits >> 5) & 0x01) != 0) } #[doc = "Bit 6 - TIM12EN"] #[inline(always)] pub fn tim12en(&self) -> TIM12EN_R { TIM12EN_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - TIM13EN"] #[inline(always)] pub fn tim13en(&self) -> TIM13EN_R { TIM13EN_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - TIM14EN"] #[inline(always)] pub fn tim14en(&self) -> TIM14EN_R { TIM14EN_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - LPTIM1EN"] #[inline(always)] pub fn lptim1en(&self) -> LPTIM1EN_R { LPTIM1EN_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 11 - SPI2EN"] #[inline(always)] pub fn spi2en(&self) -> SPI2EN_R { SPI2EN_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - SPI3EN"] #[inline(always)] pub fn spi3en(&self) -> SPI3EN_R { SPI3EN_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 14 - USART2EN"] #[inline(always)] pub fn usart2en(&self) -> USART2EN_R { USART2EN_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 15 - USART3EN"] #[inline(always)] pub fn usart3en(&self) -> USART3EN_R { USART3EN_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 16 - UART4EN"] #[inline(always)] pub fn uart4en(&self) -> UART4EN_R { UART4EN_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - UART5EN"] #[inline(always)] pub fn uart5en(&self) -> UART5EN_R { UART5EN_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - UART7EN"] #[inline(always)] pub fn uart7en(&self) -> UART7EN_R { UART7EN_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - UART8EN"] #[inline(always)] pub fn uart8en(&self) -> UART8EN_R { UART8EN_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 21 - I2C1EN"] #[inline(always)] pub fn i2c1en(&self) -> I2C1EN_R { I2C1EN_R::new(((self.bits >> 21) & 0x01) != 0) } #[doc = "Bit 22 - I2C2EN"] #[inline(always)] pub fn i2c2en(&self) -> I2C2EN_R { I2C2EN_R::new(((self.bits >> 22) & 0x01) != 0) } #[doc = "Bit 23 - I2C3EN"] #[inline(always)] pub fn i2c3en(&self) -> I2C3EN_R { I2C3EN_R::new(((self.bits >> 23) & 0x01) != 0) } #[doc = "Bit 24 - I2C5EN"] #[inline(always)] pub fn i2c5en(&self) -> I2C5EN_R { I2C5EN_R::new(((self.bits >> 24) & 0x01) != 0) } #[doc = "Bit 26 - SPDIFEN"] #[inline(always)] pub fn spdifen(&self) -> SPDIFEN_R { SPDIFEN_R::new(((self.bits >> 26) & 0x01) != 0) } #[doc = "Bit 27 - CECEN"] #[inline(always)] pub fn cecen(&self) -> CECEN_R { CECEN_R::new(((self.bits >> 27) & 0x01) != 0) } #[doc = "Bit 29 - DAC12EN"] #[inline(always)] pub fn dac12en(&self) -> DAC12EN_R { DAC12EN_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 31 - MDIOSEN"] #[inline(always)] pub fn mdiosen(&self) -> MDIOSEN_R { MDIOSEN_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TIM2EN"] #[inline(always)] pub fn tim2en(&mut self) -> TIM2EN_W { TIM2EN_W { w: self } } #[doc = "Bit 1 - TIM3EN"] #[inline(always)] pub fn tim3en(&mut self) -> TIM3EN_W { TIM3EN_W { w: self } } #[doc = "Bit 2 - TIM4EN"] #[inline(always)] pub fn tim4en(&mut self) -> TIM4EN_W { TIM4EN_W { w: self } } #[doc = "Bit 3 - TIM5EN"] #[inline(always)] pub fn tim5en(&mut self) -> TIM5EN_W { TIM5EN_W { w: self } } #[doc = "Bit 4 - TIM6EN"] #[inline(always)] pub fn tim6en(&mut self) -> TIM6EN_W { TIM6EN_W { w: self } } #[doc = "Bit 5 - TIM7EN"] #[inline(always)] pub fn tim7en(&mut self) -> TIM7EN_W { TIM7EN_W { w: self } } #[doc = "Bit 6 - TIM12EN"] #[inline(always)] pub fn tim12en(&mut self) -> TIM12EN_W { TIM12EN_W { w: self } } #[doc = "Bit 7 - TIM13EN"] #[inline(always)] pub fn tim13en(&mut self) -> TIM13EN_W { TIM13EN_W { w: self } } #[doc = "Bit 8 - TIM14EN"] #[inline(always)] pub fn tim14en(&mut self) -> TIM14EN_W { TIM14EN_W { w: self } } #[doc = "Bit 9 - LPTIM1EN"] #[inline(always)] pub fn lptim1en(&mut self) -> LPTIM1EN_W { LPTIM1EN_W { w: self } } #[doc = "Bit 11 - SPI2EN"] #[inline(always)] pub fn spi2en(&mut self) -> SPI2EN_W { SPI2EN_W { w: self } } #[doc = "Bit 12 - SPI3EN"] #[inline(always)] pub fn spi3en(&mut self) -> SPI3EN_W { SPI3EN_W { w: self } } #[doc = "Bit 14 - USART2EN"] #[inline(always)] pub fn usart2en(&mut self) -> USART2EN_W { USART2EN_W { w: self } } #[doc = "Bit 15 - USART3EN"] #[inline(always)] pub fn usart3en(&mut self) -> USART3EN_W { USART3EN_W { w: self } } #[doc = "Bit 16 - UART4EN"] #[inline(always)] pub fn uart4en(&mut self) -> UART4EN_W { UART4EN_W { w: self } } #[doc = "Bit 17 - UART5EN"] #[inline(always)] pub fn uart5en(&mut self) -> UART5EN_W { UART5EN_W { w: self } } #[doc = "Bit 18 - UART7EN"] #[inline(always)] pub fn uart7en(&mut self) -> UART7EN_W { UART7EN_W { w: self } } #[doc = "Bit 19 - UART8EN"] #[inline(always)] pub fn uart8en(&mut self) -> UART8EN_W { UART8EN_W { w: self } } #[doc = "Bit 21 - I2C1EN"] #[inline(always)] pub fn i2c1en(&mut self) -> I2C1EN_W { I2C1EN_W { w: self } } #[doc = "Bit 22 - I2C2EN"] #[inline(always)] pub fn i2c2en(&mut self) -> I2C2EN_W { I2C2EN_W { w: self } } #[doc = "Bit 23 - I2C3EN"] #[inline(always)] pub fn i2c3en(&mut self) -> I2C3EN_W { I2C3EN_W { w: self } } #[doc = "Bit 24 - I2C5EN"] #[inline(always)] pub fn i2c5en(&mut self) -> I2C5EN_W { I2C5EN_W { w: self } } #[doc = "Bit 26 - SPDIFEN"] #[inline(always)] pub fn spdifen(&mut self) -> SPDIFEN_W { SPDIFEN_W { w: self } } #[doc = "Bit 27 - CECEN"] #[inline(always)] pub fn cecen(&mut self) -> CECEN_W { CECEN_W { w: self } } #[doc = "Bit 29 - DAC12EN"] #[inline(always)] pub fn dac12en(&mut self) -> DAC12EN_W { DAC12EN_W { w: self } } #[doc = "Bit 31 - MDIOSEN"] #[inline(always)] pub fn mdiosen(&mut self) -> MDIOSEN_W { MDIOSEN_W { w: self } } }
struct Solution; impl Solution { // 题解中没有使用滚动数组优化的动态规划解法。 pub fn is_interleave(s1: String, s2: String, s3: String) -> bool { let (s1, s2, s3) = (s1.as_bytes(), s2.as_bytes(), s3.as_bytes()); let (m, n) = (s1.len(), s2.len()); if m + n != s3.len() { return false; } // f[i][j] 表示 s1 的前 i 个和 s2 的前 j 个是否能组合成 s3. let mut f = vec![vec![false; n + 1]; m + 1]; f[0][0] = true; for i in 0..=m { for j in 0..=n { // 当 i=0,j=0 时,这里的 p 是 -1,但 p 的类型是 usize,所以我们移到下面再计算。 // let p = i + j - 1; // 对应的 s3 的下标 if i > 0 { f[i][j] = f[i - 1][j] && s1[i - 1] == s3[i + j - 1]; } if j > 0 { // 可能上面计算出来了 f[i][j] == true 了,那这里就不用再计算了 f[i][j] = f[i][j] || (f[i][j - 1] && s2[j - 1] == s3[i + j - 1]); } } } f[m][n] } // by zhangyuchen. 通过了,但是 用时 804ms,内存 2M。用时过长。 pub fn is_interleave1(s1: String, s2: String, s3: String) -> bool { if s1.len() + s2.len() != s3.len() { return false; } Self::is_interleave1_helper(s1.as_bytes(), 0, s2.as_bytes(), 0, s3.as_bytes(), 0) } fn is_interleave1_helper( s1: &[u8], i: usize, s2: &[u8], j: usize, s3: &[u8], k: usize, ) -> bool { // 都到达终点了,匹配 if k == s3.len() { return i == s1.len() && j == s2.len(); } if i < s1.len() && s3[k] == s1[i] && Self::is_interleave1_helper(s1, i + 1, s2, j, s3, k + 1) { return true; } if j < s2.len() && s3[k] == s2[j] && Self::is_interleave1_helper(s1, i, s2, j + 1, s3, k + 1) { return true; } false } } #[cfg(test)] mod tests { use super::*; #[test] fn test_is_interleave1() { assert_eq!( Solution::is_interleave( "aabcc".to_owned(), "dbbca".to_owned(), "aadbbcbcac".to_owned(), ), true ); } #[test] fn test_is_interleave2() { assert_eq!( Solution::is_interleave( "aabcc".to_owned(), "dbbca".to_owned(), "aadbbbaccc".to_owned(), ), false ); } }
use { onex_loader::job_object::create_process_in_job_object, std::{ env, fs::{self, File}, path::PathBuf, process, }, util::{get_temp_dir, OffsetSeeker, OnexFile, ProjfsProvider, ReadSeek, Result}, uuid::Uuid, winapi::um::wincon::FreeConsole, zip::ZipArchive, }; fn main() -> Result<()> { enable_logging(); let exe_path = env::current_exe()?; let mut file = OnexFile::new(File::open(exe_path)?)?; let seeker = file.data_accessor()?; let exit_code = run_app(seeker)?; process::exit(exit_code as i32); } fn run_app(seeker: OffsetSeeker) -> Result<u32> { let mut uuid_buffer = Uuid::encode_buffer(); let instance_id = Uuid::new_v4() .to_hyphenated() .encode_lower(&mut uuid_buffer); let dir_name = format!("onex_{}", instance_id); let temp_dir = [get_temp_dir()?, PathBuf::from(dir_name)] .iter() .collect::<PathBuf>(); let seeker: Box<dyn ReadSeek> = Box::new(seeker); let archive = ZipArchive::new(seeker)?; let _provider = ProjfsProvider::new(&temp_dir, archive)?; let exe_name_file = [&temp_dir, &PathBuf::from("onex_run")] .iter() .collect::<PathBuf>(); let exe_name = fs::read_to_string(exe_name_file)?.trim().to_owned(); let exe_file = [&temp_dir, &PathBuf::from(exe_name)] .iter() .collect::<PathBuf>(); let args = env::args().skip(1).collect::<Vec<String>>(); let job = create_process_in_job_object(exe_file, args)?; unsafe { FreeConsole() }; let exit_code = job.wait()?; Ok(exit_code) } #[cfg(debug_assertions)] fn enable_logging() { flexi_logger::Logger::with_str("trace") .log_to_file() .directory(get_temp_dir().unwrap()) .discriminant("onex") .print_message() .start() .unwrap(); } #[cfg(not(debug_assertions))] fn enable_logging() {}
use crate::estimate::Statistic; use crate::plot::gnuplot_backend::{gnuplot_escape, Colors, DEFAULT_FONT, LINEWIDTH, SIZE}; use crate::plot::Size; use crate::plot::{FilledCurve as FilledArea, Line, LineCurve, Rectangle}; use crate::report::BenchmarkId; use crate::stats::univariate::Sample; use criterion_plot::prelude::*; pub fn abs_distribution( colors: &Colors, id: &BenchmarkId, statistic: Statistic, size: Option<Size>, x_unit: &str, distribution_curve: LineCurve, bootstrap_area: FilledArea, point_estimate: Line, ) -> Figure { let xs_sample = Sample::new(distribution_curve.xs); let mut figure = Figure::new(); figure .set(Font(DEFAULT_FONT)) .set(criterion_plot::Size::from(size.unwrap_or(SIZE))) .set(Title(format!( "{}: {}", gnuplot_escape(id.as_title()), statistic ))) .configure(Axis::BottomX, |a| { a.set(Label(format!("Average time ({})", x_unit))) .set(Range::Limits(xs_sample.min(), xs_sample.max())) }) .configure(Axis::LeftY, |a| a.set(Label("Density (a.u.)"))) .configure(Key, |k| { k.set(Justification::Left) .set(Order::SampleText) .set(Position::Outside(Vertical::Top, Horizontal::Right)) }) .plot( Lines { x: distribution_curve.xs, y: distribution_curve.ys, }, |c| { c.set(colors.current_sample) .set(LINEWIDTH) .set(Label("Bootstrap distribution")) .set(LineType::Solid) }, ) .plot( FilledCurve { x: bootstrap_area.xs, y1: bootstrap_area.ys_1, y2: bootstrap_area.ys_2, }, |c| { c.set(colors.current_sample) .set(Label("Confidence interval")) .set(Opacity(0.25)) }, ) .plot( Lines { x: &[point_estimate.start.x, point_estimate.end.x], y: &[point_estimate.start.y, point_estimate.end.y], }, |c| { c.set(colors.current_sample) .set(LINEWIDTH) .set(Label("Point estimate")) .set(LineType::Dash) }, ); figure } pub fn rel_distribution( colors: &Colors, id: &BenchmarkId, statistic: Statistic, size: Option<Size>, distribution_curve: LineCurve, confidence_interval: FilledArea, point_estimate: Line, noise_threshold: Rectangle, ) -> Figure { let xs_ = Sample::new(&distribution_curve.xs); let x_min = xs_.min(); let x_max = xs_.max(); let mut figure = Figure::new(); figure .set(Font(DEFAULT_FONT)) .set(criterion_plot::Size::from(size.unwrap_or(SIZE))) .configure(Axis::LeftY, |a| a.set(Label("Density (a.u.)"))) .configure(Key, |k| { k.set(Justification::Left) .set(Order::SampleText) .set(Position::Outside(Vertical::Top, Horizontal::Right)) }) .set(Title(format!( "{}: {}", gnuplot_escape(id.as_title()), statistic ))) .configure(Axis::BottomX, |a| { a.set(Label("Relative change (%)")) .set(Range::Limits(x_min * 100., x_max * 100.)) .set(ScaleFactor(100.)) }) .plot( Lines { x: distribution_curve.xs, y: distribution_curve.ys, }, |c| { c.set(colors.current_sample) .set(LINEWIDTH) .set(Label("Bootstrap distribution")) .set(LineType::Solid) }, ) .plot( FilledCurve { x: confidence_interval.xs, y1: confidence_interval.ys_1, y2: confidence_interval.ys_2, }, |c| { c.set(colors.current_sample) .set(Label("Confidence interval")) .set(Opacity(0.25)) }, ) .plot(to_lines!(point_estimate), |c| { c.set(colors.current_sample) .set(LINEWIDTH) .set(Label("Point estimate")) .set(LineType::Dash) }) .plot( FilledCurve { x: &[noise_threshold.left, noise_threshold.right], y1: &[noise_threshold.bottom, noise_threshold.bottom], y2: &[noise_threshold.top, noise_threshold.top], }, |c| { c.set(Axes::BottomXRightY) .set(colors.severe_outlier) .set(Label("Noise threshold")) .set(Opacity(0.1)) }, ); figure }
use hocon::Error; use hocon::Hocon; use hocon::HoconLoader; use std::time::Duration; pub struct Config { pub wait_timeout: Duration, pub num_threads: usize, pub num_nodes: usize, pub ble_hb_delay: u64, pub ble_initial_delay_factor: Option<u64>, pub num_proposals: u64, pub num_elections: u64, pub gc_idx: u64, } impl Config { pub fn load(path: &str) -> Result<Config, Error> { let cfg = HoconLoader::new().load_file(path)?.hocon()?; Ok(Config { wait_timeout: cfg["wait_timeout"].as_duration().unwrap_or_default(), num_threads: cfg["num_threads"].as_i64().unwrap_or_default() as usize, num_nodes: cfg["num_nodes"].as_i64().unwrap_or_default() as usize, ble_hb_delay: cfg["ble_hb_delay"].as_i64().unwrap_or_default() as u64, num_proposals: cfg["num_proposals"].as_i64().unwrap_or_default() as u64, num_elections: cfg["num_elections"].as_i64().unwrap_or_default() as u64, gc_idx: cfg["gc_idx"].as_i64().unwrap_or_default() as u64, ble_initial_delay_factor: cfg["ble_initial_delay_factor"].as_i64().map(|x| x as u64), }) } }
use std::{ sync::{Arc, Mutex}, time::Duration, }; use futures::TryStreamExt; use futures_util::{future::try_join_all, FutureExt}; use crate::{ bson::{doc, Document}, client::options::ClientOptions, error::{ErrorKind, Result}, event::command::{CommandEvent, CommandEventHandler, CommandStartedEvent}, options::SessionOptions, runtime::process::Process, test::{ log_uncaptured, spec::unified_runner::run_unified_tests, util::Event, EventClient, TestClient, CLIENT_OPTIONS, }, Client, }; #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn run_unified() { // TODO RUST-1414: unskip this file let mut skipped_files = vec!["implicit-sessions-default-causal-consistency.json"]; let client = TestClient::new().await; if client.is_sharded() && client.server_version_gte(7, 0) { // TODO RUST-1666: unskip this file skipped_files.push("snapshot-sessions.json"); } run_unified_tests(&["sessions"]) .skip_files(&skipped_files) .await; } // Sessions prose test 1 #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn snapshot_and_causal_consistency_are_mutually_exclusive() { let options = SessionOptions::builder() .snapshot(true) .causal_consistency(true) .build(); let client = TestClient::new().await; assert!(client.start_session(options).await.is_err()); } #[cfg_attr(feature = "tokio-runtime", tokio::test(flavor = "multi_thread"))] #[cfg_attr(feature = "async-std-runtime", async_std::test)] #[function_name::named] async fn explicit_session_created_on_same_client() { let client0 = TestClient::new().await; let client1 = TestClient::new().await; let mut session0 = client0.start_session(None).await.unwrap(); let mut session1 = client1.start_session(None).await.unwrap(); let db = client0.database(function_name!()); let err = db .list_collections_with_session(None, None, &mut session1) .await .unwrap_err(); match *err.kind { ErrorKind::InvalidArgument { message } => assert!(message.contains("session provided")), other => panic!("expected InvalidArgument error, got {:?}", other), } let coll = client1 .database(function_name!()) .collection(function_name!()); let err = coll .insert_one_with_session(doc! {}, None, &mut session0) .await .unwrap_err(); match *err.kind { ErrorKind::InvalidArgument { message } => assert!(message.contains("session provided")), other => panic!("expected InvalidArgument error, got {:?}", other), } } // Sessions prose test 14 #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn implicit_session_after_connection() { struct EventHandler { lsids: Mutex<Vec<Document>>, } impl CommandEventHandler for EventHandler { fn handle_command_started_event(&self, event: CommandStartedEvent) { self.lsids .lock() .unwrap() .push(event.command.get_document("lsid").unwrap().clone()); } } let event_handler = Arc::new(EventHandler { lsids: Mutex::new(vec![]), }); let mut min_lsids = usize::MAX; let mut max_lsids = 0usize; for _ in 0..5 { let client = { let mut options = CLIENT_OPTIONS.get().await.clone(); options.max_pool_size = Some(1); options.retry_writes = Some(true); options.hosts.drain(1..); options.command_event_handler = Some(event_handler.clone()); Client::with_options(options).unwrap() }; let coll = client .database("test_lazy_implicit") .collection::<Document>("test"); let mut ops = vec![]; fn ignore_val<T>(r: Result<T>) -> Result<()> { r.map(|_| ()) } ops.push(coll.insert_one(doc! {}, None).map(ignore_val).boxed()); ops.push(coll.delete_one(doc! {}, None).map(ignore_val).boxed()); ops.push( coll.update_one(doc! {}, doc! { "$set": { "a": 1 } }, None) .map(ignore_val) .boxed(), ); ops.push( coll.find_one_and_delete(doc! {}, None) .map(ignore_val) .boxed(), ); ops.push( coll.find_one_and_update(doc! {}, doc! { "$set": { "a": 1 } }, None) .map(ignore_val) .boxed(), ); ops.push( coll.find_one_and_replace(doc! {}, doc! { "a": 1 }, None) .map(ignore_val) .boxed(), ); ops.push( async { let cursor = coll.find(doc! {}, None).await.unwrap(); let r: Result<Vec<_>> = cursor.try_collect().await; r.map(|_| ()) } .boxed(), ); let _ = try_join_all(ops).await.unwrap(); let mut lsids = event_handler.lsids.lock().unwrap(); let mut unique = vec![]; 'outer: for lsid in lsids.iter() { for u in &unique { if lsid == *u { continue 'outer; } } unique.push(lsid); } min_lsids = std::cmp::min(min_lsids, unique.len()); max_lsids = std::cmp::max(max_lsids, unique.len()); lsids.clear(); } // The spec says the minimum should be 1; however, the background async nature of the Rust // driver's session cleanup means that sometimes a session has not yet been returned to the pool // when the next one is checked out. assert!( min_lsids <= 2, "min lsids is {}, expected <= 2 (max is {})", min_lsids, max_lsids, ); assert!( max_lsids < 7, "max lsids is {}, expected < 7 (min is {})", max_lsids, min_lsids, ); } async fn spawn_mongocryptd(name: &str) -> Option<(EventClient, Process)> { let util_client = TestClient::new().await; if util_client.server_version_lt(4, 2) { log_uncaptured(format!( "Skipping {name}: cannot spawn mongocryptd due to server version < 4.2" )); return None; } let pid_file_path = format!("--pidfilepath={name}.pid"); let args = vec!["--port=47017", &pid_file_path]; let Ok(process) = Process::spawn("mongocryptd", args) else { if std::env::var("SESSION_TEST_REQUIRE_MONGOCRYPTD").is_ok() { panic!("Failed to spawn mongocryptd"); } log_uncaptured(format!("Skipping {name}: failed to spawn mongocryptd")); return None; }; let options = ClientOptions::parse("mongodb://localhost:47017") .await .unwrap(); let client = EventClient::with_options(options).await; assert!(client.server_info.logical_session_timeout_minutes.is_none()); Some((client, process)) } async fn clean_up_mongocryptd(mut process: Process, name: &str) { let _ = std::fs::remove_file(format!("{name}.pid")); let _ = process.kill(); let _ = process.wait().await; } // Sessions prose test 18 #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn sessions_not_supported_implicit_session_ignored() { let name = "sessions_not_supported_implicit_session_ignored"; let Some((client, process)) = spawn_mongocryptd(name).await else { return; }; let mut subscriber = client.handler.subscribe(); let coll = client.database(name).collection(name); let _ = coll.find(doc! {}, None).await; let event = subscriber .filter_map_event(Duration::from_millis(500), |event| match event { Event::Command(CommandEvent::Started(command_started_event)) if command_started_event.command_name == "find" => { Some(command_started_event) } _ => None, }) .await .expect("Did not observe a command started event for find operation"); assert!(!event.command.contains_key("lsid")); let _ = coll.insert_one(doc! { "x": 1 }, None).await; let event = subscriber .filter_map_event(Duration::from_millis(500), |event| match event { Event::Command(CommandEvent::Started(command_started_event)) if command_started_event.command_name == "insert" => { Some(command_started_event) } _ => None, }) .await .expect("Did not observe a command started event for insert operation"); assert!(!event.command.contains_key("lsid")); clean_up_mongocryptd(process, name).await; } // Sessions prose test 19 #[cfg_attr(feature = "tokio-runtime", tokio::test)] #[cfg_attr(feature = "async-std-runtime", async_std::test)] async fn sessions_not_supported_explicit_session_error() { let name = "sessions_not_supported_explicit_session_error"; let Some((client, process)) = spawn_mongocryptd(name).await else { return; }; let mut session = client.start_session(None).await.unwrap(); let coll = client.database(name).collection(name); let error = coll .find_one_with_session(doc! {}, None, &mut session) .await .unwrap_err(); assert!(matches!(*error.kind, ErrorKind::SessionsNotSupported)); let error = coll .insert_one_with_session(doc! { "x": 1 }, None, &mut session) .await .unwrap_err(); assert!(matches!(*error.kind, ErrorKind::SessionsNotSupported)); clean_up_mongocryptd(process, name).await; }
/// A LaTeX fragment. /// /// # Semantics /// /// # Syntax /// /// Follows one of these patterns: /// /// ```text /// \NAME BRACKETS /// \(CONTENTS\) /// \[CONTENTS\] /// $$CONTENTS$$ /// PRE$CHAR$POST /// PRE$BORDER1 BODY BORDER2$POST /// ``` /// /// `NAME` can contain any alphabetical character and can end with an asterisk. `NAME` must not /// be in [`entities`] or the user defined `org_entities_user` variable otherwise it will /// be parsed as a [`Entity`]. /// /// `BRACKETS` is optional and is not separated from `NAME` with whitespace. It can contain any /// number of the following patterns (not separated by anything): `[CONTENTS1]`, `{CONTENTS2}`. /// /// `CONTENTS1` and `CONTENTS2` can contain any character except `{`, `}` and newline. /// Additionally `CONTENTS1` can't contain `[` and `]`. /// /// `CONTENTS` can contain any character but the closing characters of the pattern used. /// /// `PRE` is either the beginning of the line or any character except `$`. /// /// `CHAR` is a non-whitspace character except `.`, `,`, `?`, `;`, `'` or `"`. /// /// `POST` is any punctuation (including parantheses and quotes) or space character or the end /// of the line. /// /// `BORDER1` is any non-whitespace character except `.`, `,`, `;` and `$`. /// /// `BODY` can contain any character except `$` and may not span over more than 3 lines. /// /// `BORDER2` is any non-whitespace character except `.`, `,` and `$`. /// /// [`entities`]: ../../entities/index.html #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct LatexFragment { /// Contains the entire parsed string, except the `PRE` and `POST` parts. pub value: String, }
#[doc = "Register `GPIOA_HWCFGR2` reader"] pub type R = crate::R<GPIOA_HWCFGR2_SPEC>; #[doc = "Field `AFRL_RES` reader - AFRL_RES"] pub type AFRL_RES_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - AFRL_RES"] #[inline(always)] pub fn afrl_res(&self) -> AFRL_RES_R { AFRL_RES_R::new(self.bits) } } #[doc = "GPIO hardware configuration register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`gpioa_hwcfgr2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct GPIOA_HWCFGR2_SPEC; impl crate::RegisterSpec for GPIOA_HWCFGR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`gpioa_hwcfgr2::R`](R) reader structure"] impl crate::Readable for GPIOA_HWCFGR2_SPEC {} #[doc = "`reset()` method sets GPIOA_HWCFGR2 to value 0"] impl crate::Resettable for GPIOA_HWCFGR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use super::utils::parse_string; use crate::ast::rules; #[test] fn test_exp_terminals() { assert_eq!(parse_string("nil", rules::exp), "[Single(Nil)]"); assert_eq!( parse_string("false", rules::exp), "[Single(Boolean(false))]" ); assert_eq!(parse_string("true", rules::exp), "[Single(Boolean(true))]"); assert_eq!(parse_string("...", rules::exp), "[Single(Ellipsis)]"); assert_eq!(parse_string("42.42", rules::exp), "[Single(Number(42.42))]"); assert_eq!( parse_string(r#""Hello""#, rules::exp), r#"[Single(String("Hello"))]"# ); } #[test] fn test_explist() { assert_eq!( parse_string("nil, false", rules::explist), "[Repetition([Nil, Boolean(false)])]" ); assert_eq!( parse_string("nil, false, 42", rules::explist), "[Repetition([Nil, Boolean(false), Number(42.0)])]" ); } #[test] fn test_exp_unop() { assert_eq!( parse_string("-3", rules::exp), "[Single(Unop(MINUS, Number(3.0)))]" ); assert_eq!( parse_string("#7", rules::exp), "[Single(Unop(HASH, Number(7.0)))]" ); assert_eq!( parse_string("~false", rules::exp), "[Single(Unop(TILDA, Boolean(false)))]" ); } #[test] fn test_exp_binop() { assert_eq!( parse_string("1 - 3", rules::exp), "[Single(Binop(MINUS, Number(1.0), Number(3.0)))]" ); assert_eq!( parse_string("1 - 3 + 4", rules::exp), "[Single(Binop(PLUS, Binop(MINUS, Number(1.0), Number(3.0)), Number(4.0)))]" ); assert_eq!( parse_string("-1 - -3", rules::exp), "[Single(Binop(MINUS, Unop(MINUS, Number(1.0)), Unop(MINUS, Number(3.0))))]" ); } #[test] fn test_exp_prefixexp() { assert_eq!( parse_string("Hello.world", rules::exp), r#"[Single(Indexing { object: Id("Hello"), index: String("world") })]"# ); } #[test] fn test_exp_tableconstructor() { assert_eq!( parse_string("{ [true] = false }", rules::exp), "[Single(Table([TableField { key: Some(Boolean(true)), value: Boolean(false) }]))]" ); } /* fn test_exp_functiondef() { assert_eq!( parse_exp(&mut make_lexer("function f () break end")), Ok(make_assignment( vec!["f"], exp!(function::Function { params: vec![], body: exp!(common::Expressions(vec![exp!(Statement::Break)])), }), )) ) }*/
use crate::infinite_memory_intcomputer::*; pub fn one() { let mut computer = IntcodeComputer::new_from_file("input/day_nine.txt"); computer.provide_input(1); loop { match computer.run().unwrap() { IntcodeComputerState::Halted => break, IntcodeComputerState::OutputProduced(output) => println!("Output {}", output), IntcodeComputerState::WaitingForInput => panic!("Unexpected waiting for input"), } } } pub fn two() { let mut computer = IntcodeComputer::new_from_file("input/day_nine.txt"); computer.provide_input(2); loop { match computer.run().unwrap() { IntcodeComputerState::Halted => break, IntcodeComputerState::OutputProduced(output) => println!("Output {}", output), IntcodeComputerState::WaitingForInput => panic!("Unexpected waiting for input"), } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { let program = vec![ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99, ]; let mut computer = IntcodeComputer::new(program.clone()); let mut output_vec = vec![]; while let Ok(IntcodeComputerState::OutputProduced(output)) = computer.run() { output_vec.push(output); } assert_eq!(output_vec, program); } #[test] fn large_number() { let program = vec![1102, 34915192, 34915192, 7, 4, 7, 99, 0]; let mut computer = IntcodeComputer::new(program.clone()); let mut output_vec = vec![]; while let Ok(IntcodeComputerState::OutputProduced(output)) = computer.run() { output_vec.push(output); } assert_eq!(output_vec, vec![1219070632396864]); } #[test] fn middle_number() { let program = vec![104, 1125899906842624, 99]; let mut computer = IntcodeComputer::new(program.clone()); let mut output_vec = vec![]; while let Ok(IntcodeComputerState::OutputProduced(output)) = computer.run() { output_vec.push(output); } assert_eq!(output_vec, vec![1125899906842624]); } #[test] fn int_code_computer_self_test() { let mut computer = IntcodeComputer::new_from_file("input/day_nine.txt"); computer.provide_input(1); loop { match computer.run().unwrap() { IntcodeComputerState::Halted => break, IntcodeComputerState::OutputProduced(output) => assert_eq!(output, 3100786347), IntcodeComputerState::WaitingForInput => panic!("Unexpected waiting for input"), } } } #[test] fn int_computer_extended_self_test() { let mut computer = IntcodeComputer::new_from_file("input/day_nine.txt"); computer.provide_input(2); computer.run_ignore_output().unwrap(); assert_eq!(computer.get_output(), vec![87023]) } }
#![feature(use_extern_macros)] #[macro_use] extern crate serde_derive; extern crate wasm_bindgen; use wasm_bindgen::prelude::*; mod mandelbrot; use mandelbrot::get_mandelbrot_set; #[derive(Deserialize)] pub struct Configuration { pub iterations: usize, pub width: u32, pub height: u32, pub xmin: f64, pub xmax: f64, pub ymin: f64, pub ymax: f64, } #[wasm_bindgen] extern "C" { pub type ImageData; #[wasm_bindgen(constructor)] pub fn new(arr: &Uint8ClampedArray, width: u32, height: u32) -> ImageData; } #[wasm_bindgen] extern "C" { pub type Uint8ClampedArray; #[wasm_bindgen(constructor)] pub fn new(arr: &[u8]) -> Uint8ClampedArray; } #[wasm_bindgen] extern "C" { pub type CanvasRenderingContext2D; #[wasm_bindgen(method, js_name=putImageData)] pub fn put_image_data(this: &CanvasRenderingContext2D, image_data: &ImageData, p_1: i32, p_2: i32); } #[wasm_bindgen] extern "C" { #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); } #[wasm_bindgen] pub fn draw(context: &CanvasRenderingContext2D, conf_js: &JsValue) { let configuration: Configuration = conf_js.into_serde().unwrap(); log("Starting draw"); log(&format!("Width = {}; Height = {}", configuration.width, configuration.height)); let data = get_mandelbrot_set(&configuration); log(&format!("Generated {} numbers", data.len())); let uint8_array = Uint8ClampedArray::new(&data); log("uint8 array generated"); context.put_image_data(&ImageData::new(&uint8_array, configuration.width, configuration.height), 0, 0); }
fn main() { println!("{}", chessboard_cell_color("A1", "A2")); } fn chessboard_cell_color(cell1: &str, cell2: &str) -> bool { let b1 = cell1.chars().nth(0).unwrap(); let b2 = cell1.chars().nth(1).unwrap(); let p1 = cell2.chars().nth(0).unwrap(); let p2 = cell2.chars().nth(1).unwrap(); (b1 as i16 + b2 as i16).abs() % 2 == (p1 as i16 + p2 as i16).abs() % 2 } #[test] fn basic_tests() { assert_eq!(chessboard_cell_color("A1", "C3"), true); assert_eq!(chessboard_cell_color("A1", "H3"), false); assert_eq!(chessboard_cell_color("A1", "A2"), false); assert_eq!(chessboard_cell_color("A1", "C1"), true); assert_eq!(chessboard_cell_color("A1", "A1"), true); }
use std::fmt; use std::env::var; use std::process::Command; pub mod colors; pub use crate::colors::Colors; #[derive(Debug)] pub struct Title { username: String, hostname: String } pub fn username() -> String { var("USERNAME").unwrap() } #[cfg(target_family = "unix")] pub fn hostname() -> Result<String, ()> { Ok(var("HOSTNAME").unwrap()) } #[cfg(target_family = "windows")] pub fn hostname() -> Result<String, ()> { let output = Command::new("hostname") .output(); match output { Ok(output) => return Ok(String::from_utf8(output.stdout).unwrap()), Err(_) => return Err(()), } } pub fn title() -> Title { let username = username(); let hostname = hostname().unwrap_or("Unknown".to_string()); Title { username, hostname } } #[cfg(target_family = "unix")] pub fn os() -> Result<String, ()> { let output = Command::new("lsb_release") .arg("-sd") .output(); match output { Ok(output) => return Ok(String::from_utf8(output.stdout).unwrap()), Err(_) => return Err(()), } } #[cfg(target_family = "windows")] pub fn os() -> Result<String, ()> { let output = Command::new("wmic") .args(&["os", "get", "Caption"]) .output(); match output { Ok(output_) => { let output = String::from_utf8(output_.stdout).unwrap(); let pat: Vec<&str> = output.split_terminator("\r\r\n").collect(); let os = pat[1]; return Ok(os.trim().to_string().split_off(10)) }, Err(_) => return Err(()), } } #[cfg(target_family = "unix")] pub fn kernel() -> Result<String, ()> { let output = Command::new("uname") .arg("-r") .output(); match output { Ok(output) => return Ok(String::from_utf8(output.stdout).unwrap()), Err(_) => return Err(()), } } #[cfg(target_family = "windows")] pub fn kernel() -> Result<String, ()> { let output = Command::new("wmic") .args(&["os", "get", "Version"]) .output(); match output { Ok(output_) => { let output = String::from_utf8(output_.stdout).unwrap(); let pat: Vec<&str> = output.split_terminator("\r\r\n").collect(); let os = pat[1]; return Ok(os.trim().to_string()) }, Err(_) => return Err(()), } } #[cfg(target_family = "unix")] pub fn de() -> Result<String, ()> { Ok("Unknown".to_string()) } #[cfg(target_family = "windows")] pub fn de() -> Result<String, ()> { let os = os().unwrap(); let pat: Vec<&str> = os.split_terminator(" ").collect(); if pat[1].trim() == "7" { Ok("Aero".to_string()) } else { Ok("Metro".to_string()) } } impl fmt::Display for Title { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}@{}", self.username, self.hostname) } } #[macro_export] macro_rules! printr { () => (print!("\x1b[0m")); ($($arg:tt)*) => ({ print!("{}\x1b[0m", format_args!($($arg)*)); }) } #[macro_export] macro_rules! printlnr { () => (println!("\x1b[0m")); ($($arg:tt)*) => ({ println!("{}\x1b[0m", format_args!($($arg)*)); }) }
use crate::demo::data::DemoTick; use bitbuffer::{BitRead, BitReadStream, BitWrite, BitWriteStream, Endianness}; use serde::{Deserialize, Serialize}; #[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] #[derive(Debug, PartialEq, Serialize, Deserialize, Clone)] pub struct StopPacket { pub tick: DemoTick, } impl<'a, E: Endianness> BitRead<'a, E> for StopPacket { fn read(stream: &mut BitReadStream<'a, E>) -> bitbuffer::Result<Self> { Ok(StopPacket { tick: stream.read_int::<u32>(24)?.into(), }) } } impl<E: Endianness> BitWrite<E> for StopPacket { fn write(&self, stream: &mut BitWriteStream<E>) -> bitbuffer::Result<()> { stream.write_int::<u32>(self.tick.into(), 24) } }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(warnings)] #[macro_use] extern crate bitfield; extern crate byteorder; extern crate failure; extern crate fuchsia_app as app; extern crate fuchsia_async as async; extern crate fuchsia_zircon as zx; extern crate wlantap_client; extern crate fidl_fuchsia_wlan_device as wlan_device; extern crate fidl_fuchsia_wlan_service as fidl_wlan_service; extern crate fidl_fuchsia_wlan_tap as wlantap; extern crate futures; use futures::prelude::*; use std::sync::{Arc, Mutex}; use wlantap_client::Wlantap; use zx::prelude::*; mod mac_frames; #[cfg(test)] mod test_utils; fn create_2_4_ghz_band_info() -> wlan_device::BandInfo { wlan_device::BandInfo{ description: String::from("2.4 GHz"), ht_caps: wlan_device::HtCapabilities{ ht_capability_info: 0x01fe, ampdu_params: 0, supported_mcs_set: [ // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0xff, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0x01, 0, 0, 0 ], ht_ext_capabilities: 0, tx_beamforming_capabilities: 0, asel_capabilities: 0 }, vht_caps: None, basic_rates: vec![2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108], supported_channels: wlan_device::ChannelList{ base_freq: 2407, channels: vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] } } } fn create_wlantap_config() -> wlantap::WlantapPhyConfig { use wlan_device::SupportedPhy; wlantap::WlantapPhyConfig { phy_info: wlan_device::PhyInfo{ id: 0, dev_path: None, hw_mac_address: [ 0x67, 0x62, 0x6f, 0x6e, 0x69, 0x6b ], supported_phys: vec![ SupportedPhy::Dsss, SupportedPhy::Cck, SupportedPhy::Ofdm, SupportedPhy::Ht ], driver_features: vec![], mac_roles: vec![wlan_device::MacRole::Client], caps: vec![], bands: vec![ create_2_4_ghz_band_info() ] }, name: String::from("wlantap0") } } struct State { current_channel: wlan_device::Channel, frame_buf: Vec<u8>, } impl State { fn new() -> Self { Self { current_channel: wlan_device::Channel { primary: 0, cbw: 0, secondary80: 0 }, frame_buf: vec![] } } } fn send_beacon(frame_buf: &mut Vec<u8>, channel: &wlan_device::Channel, bss_id: &[u8; 6], ssid: &str, proxy: &wlantap::WlantapPhyProxy) -> Result<(), failure::Error> { frame_buf.clear(); mac_frames::MacFrameWriter::<&mut Vec<u8>>::new(frame_buf) .beacon( &mac_frames::MgmtHeader{ frame_control: mac_frames::FrameControl(0), // will be filled automatically duration: 0, addr1: mac_frames::BROADCAST_ADDR.clone(), addr2: bss_id.clone(), addr3: bss_id.clone(), seq_control: mac_frames::SeqControl { frag_num: 0, seq_num: 123 }, ht_control: None }, &mac_frames::BeaconFields{ timestamp: 0, beacon_interval: 100, capability_info: 0, })? .ssid(ssid.as_bytes())? .supported_rates(&[0x82, 0x84, 0x8b, 0x0c, 0x12, 0x96, 0x18, 0x24])? .dsss_parameter_set(channel.primary)?; let rx_info = &mut wlantap::WlanRxInfo { rx_flags: 0, valid_fields: 0, phy: 0, data_rate: 0, chan: wlan_device::Channel { // TODO(FIDL-54): use clone() primary: channel.primary, cbw: channel.cbw, secondary80: channel.secondary80 }, mcs: 0, rssi_dbm: 0, rcpi_dbmh: 0, snr_dbh: 0, }; proxy.rx(0, &mut frame_buf.iter().cloned(), rx_info)?; Ok(()) } fn main() -> Result<(), failure::Error> { let mut exec = async::Executor::new()?; let wlantap = Wlantap::open()?; let state = Arc::new(Mutex::new(State::new())); let proxy = wlantap.create_phy(create_wlantap_config())?; let event_listener = { let state = state.clone(); proxy.take_event_stream().for_each(move |event| { match event { wlantap::WlantapPhyEvent::SetChannel{ args } => { let mut state = state.lock().unwrap(); state.current_channel = args.chan; println!("setting channel to {:?}", state.current_channel); }, _ => {} } Ok(()) }) .map(|_| ()) .recover(|e| eprintln!("error running wlantap event listener: {:?}", e)) }; let beacon_timer = async::Interval::<zx::Status>::new(102_400_000.nanos()) .for_each(move |_| { let state = &mut *state.lock().map_err(|e| { eprintln!("beacon timer callback: Failed to lock mutex: {:?}", e); zx::Status::INTERNAL })?; if state.current_channel.primary == 6 { eprintln!("sending beacon!"); send_beacon(&mut state.frame_buf, &state.current_channel, &[0x62, 0x73, 0x73, 0x62, 0x73, 0x73], "fakenet", &proxy).unwrap(); } Ok(()) }) .map(|_| ()) .recover::<Never, _>(|e| eprintln!("error running beacon timer: {:?}", e)); // Unwrap is OK since the error type is Never, which doesn't work with '?' exec.run_singlethreaded(event_listener.join(beacon_timer)).unwrap(); Ok(()) } #[cfg(test)] mod tests { use super::*; const BSS_FOO: [u8; 6] = [0x62, 0x73, 0x73, 0x66, 0x6f, 0x6f]; const SSID_FOO: &str = "foo"; const BSS_BAR: [u8; 6] = [0x62, 0x73, 0x73, 0x62, 0x61, 0x72]; const SSID_BAR: &str = "bar"; const BSS_BAZ: [u8; 6] = [0x62, 0x73, 0x73, 0x62, 0x61, 0x7a]; const SSID_BAZ: &str = "baz"; #[test] fn simulate_scan() { let mut exec = async::Executor::new().expect("Failed to create an executor"); let mut helper = test_utils::TestHelper::begin_test(&mut exec, create_wlantap_config()); let wlan_service = app::client::connect_to_service::<fidl_wlan_service::WlanMarker>() .expect("Failed to connect to wlan service"); // A temporary workaround for NET-1102 // TODO(gbonik): remove this once we transition to wlanstack2 ::std::thread::sleep(::std::time::Duration::from_millis(500)); let proxy = helper.proxy(); let scan_result = scan(&mut exec, &wlan_service, &proxy, &mut helper); assert_eq!(fidl_wlan_service::ErrCode::Ok, scan_result.error.code, "The error message was: {}", scan_result.error.description); let mut aps:Vec<_> = scan_result.aps.expect("Got empty scan results") .into_iter().map(|ap| (ap.ssid, ap.bssid)).collect(); aps.sort(); let mut expected_aps = [ ( SSID_FOO.to_string(), BSS_FOO.to_vec() ), ( SSID_BAR.to_string(), BSS_BAR.to_vec() ), ( SSID_BAZ.to_string(), BSS_BAZ.to_vec() ), ]; expected_aps.sort(); assert_eq!(&expected_aps, &aps[..]); } fn scan(exec: &mut async::Executor, wlan_service: &fidl_wlan_service::WlanProxy, phy: &wlantap::WlantapPhyProxy, helper: &mut test_utils::TestHelper) -> fidl_wlan_service::ScanResult { let mut wlanstack_retry = test_utils::RetryWithBackoff::new(1.seconds()); loop { let scan_result = helper.run(exec, 10.seconds(), "receive a scan response", |event| { match event { wlantap::WlantapPhyEvent::SetChannel { args } => { println!("set channel to {:?}", args.chan); if args.chan.primary == 1 { send_beacon(&mut vec![], &args.chan, &BSS_FOO, SSID_FOO, &phy) .unwrap(); } else if args.chan.primary == 6 { send_beacon(&mut vec![], &args.chan, &BSS_BAR, SSID_BAR, &phy) .unwrap(); } else if args.chan.primary == 11 { send_beacon(&mut vec![], &args.chan, &BSS_BAZ, SSID_BAZ, &phy) .unwrap(); } }, _ => {} } }, wlan_service.scan(&mut fidl_wlan_service::ScanRequest { timeout: 5 })).unwrap(); if scan_result.error.code == fidl_wlan_service::ErrCode::NotFound { let slept = wlanstack_retry.sleep_unless_timed_out(); assert!(slept, "Wlanstack did not recognize the interface in time"); } else { return scan_result; } } } }
use super::data::{ Object, Game, Tcod, UseResult, MessageLog, Item }; use super::spellcasting; use super::equipment; use crate::PLAYER; use crate::app::equipment::get_equipped_in_slot; pub fn pick_item_up( object_id: usize, objects: &mut Vec<Object>, game: &mut Game, ) { if game.inventory.len() >= 26 { game.log.add( format!( "Your inventory is full, cannot pick up {}.", objects[object_id].name ), tcod::colors::RED, ); } else { let item = objects.swap_remove(object_id); game.log.add( format!("You picked up a {}!", item.name), tcod::colors::GREEN, ); let index = game.inventory.len(); let slot = item.equipment.map(|e| e.slot); game.inventory.push(item); if let Some(slot) = slot { if get_equipped_in_slot(slot, &game.inventory).is_none() { game.inventory[index].equip(&mut game.log); } } } } pub fn drop_item( inventory_id: usize, objects: &mut Vec<Object>, game: &mut Game, ) { let mut item = game.inventory.remove(inventory_id); if item.equipment.is_some() { item.dequip(&mut game.log); } item.set_pos(objects[PLAYER].x, objects[PLAYER].y); game.log.add( format!("You dropped a {}.", item.name), tcod::colors::YELLOW, ); objects.push(item); } pub fn use_item( inventory_id: usize, objects: &mut [Object], game: &mut Game, tcod: &mut Tcod, ) { // use data::Item::*; if let Some(item) = game.inventory[inventory_id].item { let on_use = match item { Item::Heal => spellcasting::cast_heal, Item::Lightning => spellcasting::cast_lightning, Item::Confuse => spellcasting::cast_confuse, Item::Fireball => spellcasting::cast_fireball, Item::Sword => equipment::toggle_equipment, Item::Shield => equipment::toggle_equipment, }; match on_use(inventory_id, objects, game, tcod) { UseResult::UsedUp => { game.inventory.remove(inventory_id); } UseResult::UsedAndKept => {}, // Do nothing UseResult::Cancelled => { game.log.add("Cancelled", tcod::colors::WHITE); } } } else { game.log.add( format!("The {} cannot be used.", game.inventory[inventory_id].name), tcod::colors::WHITE, ); } }
// Handles conversion from/to string use super::u512; impl std::str::FromStr for u512 { type Err = &'static str; fn from_str(number_str: &str) -> Result<u512, &'static str> { let mut result = u512::zero(); for digit_char in number_str.chars() { let cur_digit: u32 = match digit_char.to_digit(10) { None => return Err("Bad digit"), Some(digit) => digit }; result = &result * &u512::from(10) + &u512::from(cur_digit as u64); } return Ok(result); } } // It cant be std::str::ToString because Display causes ToString impl u512 { fn to_string(&self) -> String { if *self == u512::zero() { return String::from("0"); } let mut result = String::from(""); let mut self_copy: u512 = *self; while self_copy != u512::zero() { let cur_digit: u64 = (&self_copy % &u512::from(10)).to_u64(); result = cur_digit.to_string() + &result; self_copy = &self_copy / &u512::from(10); } return result; } } impl std::fmt::Display for u512 { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { return write!(f, "{}", self.to_string()); } } #[cfg(test)] mod tests { use super::super::u512; use std::str::FromStr; #[test] fn from_str() { assert_eq!(Ok(u512::from(0)), u512::from_str("0")); assert_eq!(Ok(u512::from(123412)), u512::from_str("123412")); let assert_err = | result | { if let Ok(_) = result { panic!("Ok should be error!"); }}; assert_err(u512::from_str("non digit")); assert_eq!(Ok(u512::from(0)), u512::from_str("0")); let max_value: u512 = u512::from_str("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095").unwrap(); assert_eq!(&max_value, &u512::max_value()); } }
fn main() { let n: usize = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); line.trim_end().parse().unwrap() }; let mut sum: u64 = 0; (0..n).for_each(|_| { let (a, b) = { let mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); let mut ws = line.trim_end().split_whitespace(); let n1: u64 = ws.next().unwrap().parse().unwrap(); let n2: u64 = ws.next().unwrap().parse().unwrap(); (n1, n2) }; (a..=b).for_each(|v| sum += v); }); println!("{}", sum); }
/** A container for aspects of a Portage Category A portage [`Category`](crate::atom::Category) is a unique qualifier of a *class* of [`Package`](crate::atom::Package)'s, but without an actual package name or version and does not support range or requality specifiers ### Usage ```rust use grease::atom::Category; let c: Category = "dev-perl".parse().unwrap(); ``` */ #[derive(Debug, Clone)] pub struct Category { pub(crate) category: String, } use crate::{atom::regex, err}; use std::{ cmp::Ordering, fmt::{self, Display}, str::FromStr, }; impl Category { /** a getter for this instances category */ pub fn category(&self) -> &str { &self.category } } impl Display for Category { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.category) } } impl FromStr for Category { type Err = err::AtomParseError; fn from_str(s: &str) -> Result<Self, Self::Err> { use crate::err::AtomParseError; if regex::CATEGORY_NAME.is_match(s) { Ok(Category { category: s.to_owned() }) } else { Err(AtomParseError::BadCategory(s.to_owned())) } } } impl PartialEq for Category { fn eq(&self, other: &Category) -> bool { self.category == other.category } } impl PartialOrd for Category { fn partial_cmp(&self, other: &Category) -> Option<Ordering> { chain_cmp!(self.category.partial_cmp(&other.category)) } }
use super::super::{head, navbar, scripts}; use maud::{DOCTYPE, Markup}; pub fn index() -> Markup { html! { (DOCTYPE) html .no-js lang="en" dir="ltr" { (head()) body { (navbar()) div .grid-container { div .grid-x .grid-padding-x { div class="large-12 cell" { h1 "Create a Build" } } form { div .grid-x .grid-padding-x { div class="large-2 medium-2 cell" { label .text-right .middle for="weapon-primary" "Primary weapon:" } div class="large-2 medium-2 cell" { select .form-control #weapon-primary {} } } div .grid-x .grid-padding-x { div class="large-2 medium-2 cell" { label .text-right .middle for="weapon-secondary" "Secondary weapon:" } div class="large-2 medium-2 cell" { select .form-control #weapon-secondary {} } } hr / div .grid-x .grid-padding-x { div class="large-2 medium-2 cell" { label .text-right .middle for="basic-ability" "Basic ability:" } div class="large-2 medium-2 cell" { select .form-control #basic-ability {} } } @for i in 1..6 { div .grid-x .grid-padding-x { div class="large-2 medium-2 cell" { label .text-right .middle for={"active-"(i)} { "Active " (i) ":" } } div class="large-4 medium-4 cell" { select .form-control id={"active-"(i)} {} } } } hr / @for i in 1..6 { div .grid-x .grid-padding-x { div class="large-2 medium-2 cell" { label .text-right .middle for={"passive-"(i)} { "Passive " (i) ":" } } div class="large-4 medium-4 cell" { select .form-control id={"passive-"(i)} {} } } } button .expanded .button #submit type="button" "Submit" } } (scripts()) script src="/static/js/BigInteger.js" {} script src="/static/js/weapons.js" {} script src="/static/js/build/index.js" {} } } } }
use std::io::{stdin, Read, StdinLock}; use std::str::FromStr; #[allow(dead_code)] struct Scanner<'a> { cin: StdinLock<'a>, } #[allow(dead_code)] impl<'a> Scanner<'a> { fn new(cin: StdinLock<'a>) -> Scanner<'a> { Scanner { cin: cin } } fn read<T: FromStr>(&mut self) -> Option<T> { let token = self.cin.by_ref().bytes().map(|c| c.unwrap() as char) .skip_while(|c| c.is_whitespace()) .take_while(|c| !c.is_whitespace()) .collect::<String>(); token.parse::<T>().ok() } fn input<T: FromStr>(&mut self) -> T { self.read().unwrap() } } fn main() { let cin = stdin(); let cin = cin.lock(); let mut sc = Scanner::new(cin); let n: isize = sc.input(); let mut min = 100_000; for w in 1..n { let h = n / w; let diff = (h - w).abs(); let sum = diff + n - (w * h); if sum < min { min = sum; } } if n != 1 { println!("{}", min); } else { println!("0"); } }
/// Error structure representing the basic error scenarios for `pg_query`. #[derive(Debug, Clone, Eq, PartialEq)] pub enum Error { ParseError(String), InvalidAst(String), InvalidJson(String), } /// Convenient Result alias for returning `pg_query::Error`. pub type Result<T> = core::result::Result<T, Error>;
use Error; use regex; use std; use tempdir; // RAII wrapper for a child process that kills the process when dropped. struct AutoKillProcess(std::process::Child); impl Drop for AutoKillProcess { fn drop(&mut self) { let AutoKillProcess(ref mut process) = *self; process.kill().unwrap(); process.wait().unwrap(); } } /// Runs a CouchDB server process suitable for testing. /// /// The `FakeServer` type is a RAII wrapper for a CouchDB server process. The /// server remains up and running until the `FakeServer` instance drops—or until /// a server error occurs. /// /// The server's underlying storage persists to the system's default temporary /// directory (e.g., `/tmp`) and is deleted when the `FakeServer` instance /// drops. /// pub struct FakeServer { // Rust drops structure fields in forward order, not reverse order. The child process must exit // before we remove the temporary directory. _process: AutoKillProcess, _tmp_root: tempdir::TempDir, uri: String, } impl FakeServer { /// Spawns a CouchDB server process. pub fn new() -> Result<FakeServer, Error> { let tmp_root = try!(tempdir::TempDir::new("chill_test").map_err(|e| { Error::Io { cause: e, description: "Failed to create temporary directory for CouchDB server", } })); { use std::io::Write; let path = tmp_root.path().join("couchdb.conf"); let mut f = try!(std::fs::File::create(&path).map_err(|e| { Error::Io { cause: e, description: "Failed to open CouchDB server configuration file", } })); try!( f.write_all( b"[couchdb]\n\ database_dir = var\n\ uri_file = couchdb.uri\n\ view_index_dir = view\n\ \n\ [log]\n\ file = couchdb.log\n\ \n\ [httpd]\n\ port = 0\n\ ", ).map_err(|e| { Error::Io { cause: e, description: "Failed to write CouchDB server configuration file", } }) ); } let child = try!(new_test_server_command(&tmp_root).spawn().map_err(|e| { Error::Io { cause: e, description: "Failed to spawn CouchDB server process", } })); let mut process = AutoKillProcess(child); let (tx, rx) = std::sync::mpsc::channel(); let mut process_out; { let AutoKillProcess(ref mut process) = process; let stdout = std::mem::replace(&mut process.stdout, None).unwrap(); process_out = std::io::BufReader::new(stdout); } let t = std::thread::spawn(move || { let re = regex::Regex::new(r"Apache CouchDB has started on (http.*)").unwrap(); let mut line = String::new(); loop { use std::io::BufRead; line.clear(); process_out.read_line(&mut line).unwrap(); let line = line.trim_right(); match re.captures(line) { None => (), Some(caps) => { tx.send(caps.get(1).unwrap().as_str().to_owned()).unwrap(); break; } } } // Drain stdout. loop { use std::io::BufRead; line.clear(); process_out.read_line(&mut line).unwrap(); if line.is_empty() { break; } } }); // Wait for the CouchDB server to start its HTTP service. let uri = try!(rx.recv().map_err(|e| { t.join().unwrap_err(); Error::ChannelReceive { cause: e, description: "Failed to extract URI from CouchDB server", } })); Ok(FakeServer { _process: process, _tmp_root: tmp_root, uri: uri, }) } /// Returns the CouchDB server URI. pub fn uri(&self) -> &str { &self.uri } } #[cfg(any(windows))] fn new_test_server_command(tmp_root: &tempdir::TempDir) -> std::process::Command { // Getting a one-shot CouchDB server running on Windows is tricky: // http://stackoverflow.com/questions/11812365/how-to-use-a-custom-couch-ini-on-windows // // TODO: Support CouchDB being installed in a non-default directory. let couchdb_dir = "c:/program files (x86)/apache software foundation/couchdb"; let erl = format!("{}/bin/erl", couchdb_dir); let default_ini = format!("{}/etc/couchdb/default.ini", couchdb_dir); let local_ini = format!("{}/etc/couchdb/local.ini", couchdb_dir); let mut c = std::process::Command::new(erl); c.arg("-couch_ini"); c.arg(default_ini); c.arg(local_ini); c.arg("couchdb.conf"); c.arg("-s"); c.arg("couch"); c.current_dir(tmp_root.path()); c.stdout(std::process::Stdio::piped()); c } #[cfg(any(not(windows)))] fn new_test_server_command(tmp_root: &tempdir::TempDir) -> std::process::Command { let mut c = std::process::Command::new("couchdb"); c.arg("-a"); c.arg("couchdb.conf"); c.current_dir(tmp_root.path()); c.stdout(std::process::Stdio::piped()); c }
use ::Result; extern "C" { pub fn SOC_Initialize(context_addr: *mut u32, context_size: u32) -> Result; pub fn SOC_Shutdown() -> Result; }
mod calendar; mod common; mod events; mod venues; fn main() { println!( " __________ .____ ______________________ _________ .__ .__ \\______ \\| | \\__ ___/\\_ _____/ \\_ ___ \\ | | |__| | ___/| | | | | __)_ ______ / \\ \\/ | | | | | | | |___ | | | \\ /_____/ \\ \\____| |__| | |____| |_______ \\|____| /_______ / \\______ /|____/|__| \\/ \\/ \\/ " ); println!("\t\t\t - Portland Local Tech Events Command-line Tool Sets."); println!("\n\n---- PLTE Menu ----"); loop { println!("\n1. Scraping home page events data"); println!("2. Scraping all events data"); println!("3. Scraping all venues data"); println!("0. Exit"); // use the > as the prompt print!("\n> "); let input = common::user_input(); let command = input.trim().split_whitespace().next().unwrap(); match &*command { "1" => calendar::menu(), "2" => events::menu(), "3" => venues::menu(), "0" => return, "q" => return, "quit" => return, "exit" => return, _ => println!("[{}]: command not found, Please try again!", command), } } }
struct Solution; impl Solution { // bfs pub fn solve(board: &mut Vec<Vec<char>>) { if board.is_empty() || board[0].is_empty() { return; } let (m, n) = (board.len(), board[0].len()); let mut queue = Vec::new(); // 上下边界 for i in 0..m { if board[i][0] == 'O' { queue.push((i, 0)); } if board[i][n - 1] == 'O' { queue.push((i, n - 1)); } } // 左右边界 for i in 1..(n - 1) { if board[0][i] == 'O' { queue.push((0, i)); } if board[m - 1][i] == 'O' { queue.push((m - 1, i)); } } // 标记 while !queue.is_empty() { if let Some((x, y)) = queue.pop() { board[x][y] = 'A'; // 检查四个方向 if x > 0 && board[x - 1][y] == 'O' { queue.push((x - 1, y)); } if y + 1 < n && board[x][y + 1] == 'O' { queue.push((x, y + 1)); } if y > 0 && board[x][y - 1] == 'O' { queue.push((x, y - 1)); } if x + 1 < m && board[x + 1][y] == 'O' { queue.push((x + 1, y)); } } } // 修改 for x in 0..m { for y in 0..n { match board[x][y] { 'A' => board[x][y] = 'O', 'O' => board[x][y] = 'X', _ => {} } } } } // dfs pub fn solve1(board: &mut Vec<Vec<char>>) { if board.is_empty() || board[0].is_empty() { return; } let (m, n) = (board.len(), board[0].len()); // 检查左右边界 for i in 0..m { Self::dfs(board, i, 0, m, n); Self::dfs(board, i, n - 1, m, n); } // 检查上下边界 for i in 1..(n - 1) { Self::dfs(board, 0, i, m, n); Self::dfs(board, m - 1, i, m, n); } // 把被包围的改成 'X',没有被包围的改成 'O' for x in 0..m { for y in 0..n { match board[x][y] { 'A' => board[x][y] = 'O', 'O' => board[x][y] = 'X', _ => {} } } } } fn dfs(board: &mut Vec<Vec<char>>, x: usize, y: usize, m: usize, n: usize) { if board[x][y] != 'O' { return; } board[x][y] = 'A'; // 左边相邻 if x > 0 { Self::dfs(board, x - 1, y, m, n); } // 右边相邻 if y + 1 < n { Self::dfs(board, x, y + 1, m, n); } // 上边相邻 if y > 0 { Self::dfs(board, x, y - 1, m, n); } // 下边相邻 if x + 1 < m { Self::dfs(board, x + 1, y, m, n); } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_solve1() { let mut board = vec![ vec!['X', 'X', 'X', 'X'], vec!['X', 'O', 'O', 'X'], vec!['X', 'X', 'O', 'X'], vec!['X', 'O', 'X', 'X'], ]; Solution::solve(&mut board); let want = vec![ vec!['X', 'X', 'X', 'X'], vec!['X', 'X', 'X', 'X'], vec!['X', 'X', 'X', 'X'], vec!['X', 'O', 'X', 'X'], ]; assert_eq!(want, board); } }
use crate::network::{ Network }; use std::hash::{Hash}; use crate::cell::{Merge}; use std::collections::HashSet; use std::rc::{Rc}; use std::cell::RefCell; use std::fmt::Debug; pub type Premise = String; #[derive(Clone)] pub struct TruthManagementSystem<A> { network: Rc<RefCell<Network<A>>>, invalid: HashSet<Premise>, } impl<A: Merge + Debug + Clone + PartialEq> TruthManagementSystem<A> { pub fn new(network: &Rc<RefCell<Network<A>>>) -> Self { Self { network: Rc::clone(network), invalid: HashSet::new() } } pub fn premise_is_valid(&self, premise: Premise) -> bool { !self.invalid.contains(&premise) } pub fn kick_out_premise(&mut self, premise: Premise) { self.invalid.remove(&premise); } pub fn brin_in_premise(&mut self, premise: Premise) { if self.invalid.contains(&premise) { self.network.borrow_mut().alert_all_propagators(); } self.invalid.remove(&premise); } }
use anyhow::Result; use crate::Challenge; pub struct Day06; impl Challenge for Day06 { const DAY_NUMBER: u32 = 6; type InputType = Vec<Vec<u32>>; type OutputType = u32; fn part1(input: &Self::InputType) -> Result<Self::OutputType> { Ok(input .iter() .map(|group| group[1..].iter().fold(group[0], |s, p| s | p).count_ones()) .sum()) } fn part2(input: &Self::InputType) -> Result<Self::OutputType> { Ok(input .iter() .map(|group| group[1..].iter().fold(group[0], |s, p| s & p).count_ones()) .sum()) } fn parse(content: &str) -> Result<Self::InputType> { Ok(content .split("\n\n") .map(|group| { group .lines() .map(|person| person.bytes().fold(0, |b, c| b | (1 << (c - b'a')))) .collect() }) .collect()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_parse() { let groups = Day06::parse( "abc cde ab", ) .expect("Should have parsed"); assert_eq!(groups.len(), 2); assert_eq!(groups[0].len(), 2); assert_eq!(groups[0][0], 0b111); assert_eq!(groups[0][1], 0b11100); } const EXAMPLE: &str = "abc a b c ab ac a a a a b"; #[test] fn test_part1() { assert_eq!(Day06::solve1(EXAMPLE).unwrap(), 11); } #[test] fn test_part2() { assert_eq!(Day06::solve2(EXAMPLE).unwrap(), 6); } } crate::benchmark_challenge!(crate::day06::Day06);
pub mod controller; pub mod cron_job; pub mod model; pub mod service;
use super::expressions::*; use super::lex_token::{Token, TokenType}; use super::statements::*; use super::LangConfig; use bitflags; type StmtBox<'a> = Box<StatementWrapper<'a>>; const SPACE: &str = " "; const TAB: &str = "\t"; const NEWLINE: &str = "\n"; const LPAREN: &str = "("; const RPAREN: &str = ")"; const LBRACE: &str = "{"; const RBRACE: &str = "}"; const COMMA: &str = ","; const SEMICOLON: &str = ";"; pub struct Printer<'a> { output: Vec<&'a str>, lang_config: &'a LangConfig, indentation: usize, do_not_print_single_newline_statement: bool, block_instructions: Vec<BlockInstruction>, group_instructions: Vec<GroupInstruction>, user_indentation_instructions: Vec<usize>, do_dot_indent: bool, in_a_for_loop: Vec<()>, do_not_need_semicolon: Vec<()>, } impl<'a> Printer<'a> { pub fn new(size: usize, lang_config: &'a LangConfig) -> Printer<'a> { Printer { output: Vec::with_capacity(size), lang_config, indentation: 0, do_not_print_single_newline_statement: false, block_instructions: Vec::new(), group_instructions: Vec::new(), user_indentation_instructions: Vec::new(), do_dot_indent: true, in_a_for_loop: Vec::new(), do_not_need_semicolon: Vec::new(), } } pub fn get_output(self, size: usize) -> String { let mut output = String::with_capacity(size); for this_one in self.output { output.push_str(this_one); } output } pub fn autoformat(mut self, ast: &'a [StmtBox<'a>]) -> Printer { for this_statement in ast { self.print_statement(this_statement); } // Make sure we only have one blank line: // this is our emergency break! let mut pos = self.output.len(); if pos != 0 { pos -= 1; loop { match self.output[pos] { SPACE | TAB | NEWLINE => { self.output.remove(pos); if pos == 0 { break; } else { pos -= 1; } } _ => { for _ in 0..self.lang_config.newlines_at_end { self.print(NEWLINE, false); } break; } }; } } self } fn print_statement(&mut self, stmt: &'a StatementWrapper<'a>) { match &stmt.statement { Statement::VariableDeclList { starting_var_type, comments_after_control_word, var_decl: var_decl_list, } => { self.print_token(starting_var_type, true); let already_started_indent = self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); // let mut forced_semicolon_already = false; let mut indented_vars = already_started_indent; let mut iter = var_decl_list.lines.iter().peekable(); while let Some(delimited_var) = iter.next() { if let Some(var_token) = &delimited_var.expr.say_var { self.print_token(&var_token, true); if let Some(comments) = &delimited_var.expr.say_var_comments { let did_move = self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new( if indented_vars { IndentationMove::Stay } else { IndentationMove::Right }, LeadingNewlines::One, ), ); if did_move { indented_vars = true; } } }; self.allow_user_indentation(); self.print_expr(&delimited_var.expr.var_expr); self.backspace(); self.rewind_user_indentation(); let last_line = iter.peek().is_none(); if last_line == false { self.print(COMMA, true); } else { if var_decl_list.has_end_delimiter { self.print(COMMA, true); } else { self.print(SEMICOLON, true); } }; if let Some(_) = &delimited_var.trailing_comment { self.allow_user_indentation(); let did_newlines = self.print_comments_and_newlines( &delimited_var.trailing_comment, CommentAndNewlinesInstruction::new_respect_users( if indented_vars { IndentationMove::Stay } else { IndentationMove::Right }, LeadingNewlines::All, ), ); if did_newlines { indented_vars = true; } else { self.rewind_user_indentation(); } } } if indented_vars { if self.on_whitespace_line() == false { self.print_newline(IndentationMove::Left); } else { self.backspace_till_newline(); self.print_indentation(IndentationMove::Left); } } if self.on_whitespace_line() == false && self.in_a_for_loop.is_empty() { self.print_newline(IndentationMove::Stay); self.do_not_print_single_newline_statement = true; } // let did_newline = if stmt.has_semicolon && !forced_semicolon_already { // self.print_semicolon(true); // false // } else { // self.print_newline(if indented_vars { // IndentationMove::Left // } else { // IndentationMove::Stay // }); // true // }; // if indented_vars && did_newline == false { // self.print_newline(IndentationMove::Left); // } } Statement::EnumDeclaration { comments_after_control_word, name, comments_after_lbrace, members, } => { self.print("enum", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_expr(name); self.print(LBRACE, true); let did_move = self.print_comments_and_newlines( comments_after_lbrace, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); if did_move == false { self.print_newline(IndentationMove::Right); } self.backspace(); self.print_delimited_lines(members, COMMA, true, true); self.set_indentation(IndentationMove::Left); self.backspace_till_newline(); self.print(RBRACE, false); self.print_semicolon(stmt.has_semicolon); } Statement::ExpresssionStatement { expression } => { // let final_newlines: Option<&CommentsAndNewlines> = { // if stmt.has_semicolon { // None // } else { // if let Some(trailing_comments) = &expression.trailing_comments { // if Printer::only_newlines(&trailing_comments) { // Some(&expression.trailing_comments) // } else { // None // } // } else { // None // } // } // }; self.print_expr(expression); // if let Some(trailing_newline) = final_newlines { // self.print_semicolon(true); // self.print_comments_and_newlines( // trailing_newline, // IndentationMove::Stay, // LeadingNewlines::One, // true, // ); // } else { self.print_semicolon(stmt.has_semicolon); // } } Statement::Block { statements, comments_after_lbrace, } => { if self.on_whitespace_line() == false { self.ensure_space(); } let block_instructions = if self.block_instructions.is_empty() { BlockInstruction::NONE } else { self.block_instructions.pop().unwrap() }; self.print(LBRACE, false); // if we have more than one statement, or if our statement isn't an expression statement, then we indent. let must_indent = block_instructions.contains(BlockInstruction::MUST_INDENT) || statements.len() > 1 || (statements.len() == 1 && statements[0].hold_expr() == false); let did_move = self.print_comments_and_newlines( comments_after_lbrace, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); if must_indent && did_move == false { self.print_newline(IndentationMove::Right); } let did_newline = did_move || must_indent; if did_newline == false { self.ensure_space(); } for stmt in statements { self.print_statement(stmt); if did_newline { if self.on_whitespace_line() == false { self.print_newline(IndentationMove::Stay); self.do_not_print_single_newline_statement = true; } } } if did_newline { self.backspace_whitespace(); self.print_newline(IndentationMove::Left); } else { self.backspace(); if self.last_entry().unwrap() != "{" { self.ensure_space(); } } self.print(RBRACE, false); self.print_semicolon(stmt.has_semicolon); if block_instructions.contains(BlockInstruction::NO_NEWLINE_AFTER_BLOCK) == false { self.ensure_newline(IndentationMove::Stay); } self.do_not_print_single_newline_statement = true; } Statement::If { comments_after_control_word, condition, then_branch, comments_between, else_branch, } => { self.print("if", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); let has_block = if let Statement::Block { .. } = &then_branch.statement { self.block_instructions.push(BlockInstruction::NO_NEWLINE_AFTER_BLOCK); true } else { false }; let current_indentation = self.indentation; if has_block == false { if let Expr::Grouping { .. } = &condition.expr { self.group_instructions.push(GroupInstruction { force_respect: Some(true), force_indentation: Some(IndentationMove::Right), ..Default::default() }); } } self.print_expr(condition); let forcible_indent = self.indentation != current_indentation && has_block == false; self.print_statement(then_branch); let did_move = self.print_comments_and_newlines( comments_between, CommentAndNewlinesInstruction { indentation_move: if forcible_indent { IndentationMove::Left } else { IndentationMove::Stay }, leading_newlines: LeadingNewlines::All, respect_user_newline: true, trailing_comment: true, }, ); if did_move == false { self.print_newline(if forcible_indent { IndentationMove::Left } else { IndentationMove::Stay }); } if let Some(else_branch) = else_branch { if forcible_indent == false { self.backspace_whitespace(); } self.ensure_space(); self.print("else", true); self.print_statement(else_branch); } self.print_semicolon(stmt.has_semicolon); } Statement::WhileWithRepeat { token, condition, body, comments_after_control_word, } => { self.print_token(token, true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_expr(condition); self.print_statement(body); self.print_semicolon(stmt.has_semicolon); } Statement::DoUntil { comments_after_control_word, condition, comments_between, body, } => { self.print("do", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.block_instructions .push(BlockInstruction::NO_NEWLINE_AFTER_BLOCK | BlockInstruction::MUST_INDENT); self.print_statement(body); self.print_comments_and_newlines( comments_between, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::None), ); self.backspace_whitespace(); if self.last_entry().unwrap() == RBRACE { self.ensure_space(); } else { self.print_newline(IndentationMove::Stay); } self.print("until", true); self.print_expr(condition); self.backspace(); self.print_semicolon_and_newline(stmt.has_semicolon, IndentationMove::Stay); } Statement::For { comments_after_control_word, comments_after_lparen, initializer, comments_after_initializer, condition, comments_after_condition, increment, comments_after_increment, comments_after_rparen, body, } => { self.print("for", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print(LPAREN, false); self.in_a_for_loop.push(()); let did_move = self.print_comments_and_newlines( comments_after_lparen, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Right, LeadingNewlines::One), ); if let Some(initializer) = initializer { self.print_statement(initializer); self.ensure_space(); } else { self.print(SEMICOLON, true); } self.print_comments_and_newlines( comments_after_initializer, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); if let Some(condition) = condition { self.print_expr(condition); } self.backspace(); self.print(SEMICOLON, true); self.print_comments_and_newlines( comments_after_condition, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); if let Some(increment) = increment { self.print_expr(increment); } else { self.backspace(); } let did_move_final_comment = self.print_comments_and_newlines( comments_after_increment, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); if did_move_final_comment == false { self.backspace(); } if did_move { self.print_newline(IndentationMove::Left); } self.print(RPAREN, true); self.in_a_for_loop.pop(); self.print_comments_and_newlines( comments_after_rparen, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_statement(body); self.print_semicolon(stmt.has_semicolon); } Statement::Return { expression } => { self.print("return", false); if let Some(expression) = expression { self.print(SPACE, false); self.print_expr(expression); } self.print_semicolon_and_newline(stmt.has_semicolon, IndentationMove::Stay); } Statement::Break => { self.print("break", false); self.print_semicolon_and_newline(stmt.has_semicolon, IndentationMove::Stay); } Statement::Exit => { self.print("exit", false); self.print_semicolon_and_newline(stmt.has_semicolon, IndentationMove::Stay); } Statement::Switch { comments_after_control_word, condition, comments_after_lbrace, cases, } => { self.print("switch", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_expr(condition); self.ensure_space(); self.print(LBRACE, true); let did_newline = self.print_comments_and_newlines( comments_after_lbrace, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); if did_newline == false { self.print_newline(IndentationMove::Right); } for case in cases { match &case.control_word { CaseType::Case(case_constant) => { self.print("case", true); self.print_comments_and_newlines( &case.comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_expr(case_constant); } CaseType::Default => { self.print("default", true); } } self.backspace(); self.print(":", true); let saved_indentation = self.indentation; let did_move = self.print_comments_and_newlines( &case.comments_after_colon, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); if did_move == false { self.print_newline(IndentationMove::Right); } // @jack do we handle blocks here in a special way? for this_statement in &case.statements { self.print_statement(this_statement); } self.backspace_till_newline(); self.print_indentation_raw(saved_indentation); } self.backspace_whitespace(); self.print_newline(IndentationMove::Left); self.print(RBRACE, false); self.print_semicolon(stmt.has_semicolon); } Statement::Comment { comment } => self.print_token(comment, true), Statement::MultilineComment { multiline_comment } => self.print_token(multiline_comment, true), Statement::RegionBegin(comment) | Statement::RegionEnd(comment) | Statement::Macro(comment) => { self.print_token(comment, false); self.backspace(); } Statement::Define { comments_after_control_word, script_name, body, } => { self.print("#define", true); self.print_comments_and_newlines( comments_after_control_word, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::One), ); self.print_expr(script_name); self.backspace(); self.print_newline(IndentationMove::Stay); for this_stmt in body { self.print_statement(this_stmt); } } } // no semicolon // Statement::Comment { comment } => self.print_token(comment, true), // Statement::MultilineComment { multiline_comment } => self.print_token(multiline_comment, true), // Statement::RegionBegin(comment) | Statement::RegionEnd(comment) | Statement::Macro(comment) => { // self.print_token(comment, false); // self.backspace(); // } // Statement::Define { let okay_to_not_have_semicolon = self.do_not_need_semicolon.pop().is_some(); if stmt.has_semicolon == false && okay_to_not_have_semicolon == false { match stmt.statement { Statement::Comment { .. } | Statement::MultilineComment { .. } | Statement::RegionBegin { .. } | Statement::RegionEnd { .. } | Statement::Macro { .. } => {} _ => { // we do this so we *always* print a newline. let mut newlines = self.backspace_whitespace(); if let Some(last_entry) = self.last_entry() { match last_entry { RBRACE => {} SEMICOLON => { newlines = usize::max(newlines, 1); } _ => { self.print_semicolon(true); newlines = usize::max(newlines, 1); } } if last_entry != RBRACE && last_entry != SEMICOLON {} for _ in 0..newlines { self.print_newline(IndentationMove::Stay); } } } }; }; } fn print_expr(&mut self, expr: &'a ExprBox<'a>) { match &expr.expr { Expr::Call { procedure_name, comments_and_newlines_after_lparen, arguments, } => { self.print_expr(procedure_name); self.backspace(); self.print(LPAREN, false); let did_move = self.print_comments_and_newlines( comments_and_newlines_after_lparen, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Right, LeadingNewlines::One), ); self.print_delimited_lines(arguments, COMMA, false, false); self.backspace_whitespace(); if did_move { self.print_newline(IndentationMove::Left); } self.print(RPAREN, true); } Expr::Binary { left, operator, comments_and_newlines_between_op_and_r, right, } => { self.print_expr(left); self.ensure_space(); self.print_token(operator, true); self.allow_user_indentation(); self.print_comments_and_newlines( comments_and_newlines_between_op_and_r, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Stay, LeadingNewlines::All), ); self.print_expr(right); self.rewind_user_indentation(); } Expr::Grouping { expressions, comments_and_newlines_after_lparen, comments_and_newlines_after_rparen, } => { self.print(LPAREN, false); let did_move = self.print_comments_and_newlines( comments_and_newlines_after_lparen, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Right, LeadingNewlines::One), ); for expression in expressions { self.print_expr(expression); } self.backspace(); if did_move { if self.on_whitespace_line() { self.backspace_till_newline(); self.print_indentation(IndentationMove::Left); } else { self.print_newline(IndentationMove::Left); } } self.print(RPAREN, true); let instructions = match self.group_instructions.pop() { Some(instruction) => instruction, None => Default::default(), }; self.print_comments_and_newlines( comments_and_newlines_after_rparen, CommentAndNewlinesInstruction { indentation_move: instructions.force_indentation(), leading_newlines: instructions.force_leading_newlines(), respect_user_newline: instructions.force_respect(), trailing_comment: false, }, ); } Expr::ArrayLiteral { comments_and_newlines_after_lbracket, arguments, } => { self.print("[", false); let did_move = self.print_comments_and_newlines( comments_and_newlines_after_lbracket, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Right, LeadingNewlines::One), ); self.print_delimited_lines(arguments, COMMA, false, false); if did_move { self.print_newline(IndentationMove::Left); } self.print("]", false); } Expr::Literal { literal_token, comments, } => { self.print_token(&literal_token, true); self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); } Expr::NumberStartDot { literal_token, comments, } => { self.print("0", false); self.print_token(&literal_token, true); self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); } Expr::NumberEndDot { literal_token, comments, } => { self.print_token(&literal_token, false); self.print("0", true); self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); } Expr::Unary { operator, comments_and_newlines_between, right, } => { self.print_token(&operator, operator.token_type == TokenType::NotAlias); self.print_comments_and_newlines( comments_and_newlines_between, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); self.print_expr(right); } Expr::Postfix { operator, comments_and_newlines_between, expr, } => { self.print_expr(expr); self.backspace(); self.print_token(&operator, true); self.print_comments_and_newlines( comments_and_newlines_between, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); } Expr::Assign { left, operator, comments_and_newlines_between_op_and_r, right, } => { self.print_expr(left); self.print_token(&operator, true); self.print_comments_and_newlines( comments_and_newlines_between_op_and_r, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); self.print_expr(right); } Expr::Identifier { name, comments } => { self.print_token(name, true); self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); } Expr::DotAccess { object_name, comments_between, instance_variable, } => { self.print_expr(object_name); self.backspace(); self.print(".", false); self.allow_user_indentation(); let mut can_unlock = false; let indentation = if self.do_dot_indent { can_unlock = true; self.do_dot_indent = false; IndentationMove::Right } else { IndentationMove::Stay }; self.print_comments_and_newlines( comments_between, CommentAndNewlinesInstruction::new_respect_users(indentation, LeadingNewlines::One), ); self.print_expr(instance_variable); self.rewind_user_indentation(); if can_unlock && self.do_dot_indent == false { self.do_dot_indent = true; } } Expr::DataStructureAccess { ds_name, access_type, access_exprs, } => { self.print_expr(ds_name); self.backspace(); self.print_token(&access_type, access_type.token_type != TokenType::LeftBracket); let mut iter = access_exprs.into_iter().peekable(); while let Some((comments, expr)) = iter.next() { self.allow_user_indentation(); self.print_comments_and_newlines( comments, CommentAndNewlinesInstruction::new(IndentationMove::Stay, LeadingNewlines::All), ); self.print_expr(expr); self.rewind_user_indentation(); self.backspace(); if let Some(_) = iter.peek() { self.print(COMMA, true); } } self.backspace(); self.print("]", true); } /* result = foo == bar ? result1 : foo == baz ? result2 : foo == qux ? result3 : foo == quux ? result4 : fail_result; */ Expr::Ternary { conditional, comments_and_newlines_after_q, left, comments_and_newlines_after_colon, right, } => { self.print_expr(conditional); self.print("?", true); self.allow_user_indentation(); self.print_comments_and_newlines( comments_and_newlines_after_q, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::All), ); self.print_expr(left); self.print(":", true); let did_move = self.print_comments_and_newlines( comments_and_newlines_after_colon, CommentAndNewlinesInstruction::new(IndentationMove::Right, LeadingNewlines::One), ); self.print_expr(right); self.rewind_user_indentation(); if did_move { self.set_indentation(IndentationMove::Left); } } Expr::Newline => { self.do_not_need_semicolon.push(()); if self.do_not_print_single_newline_statement == false { self.print_newline(IndentationMove::Stay); } } Expr::Comment { comment } => { self.do_not_need_semicolon.push(()); self.print_token(comment, false); } Expr::MultilineComment { multiline_comment } => { self.do_not_need_semicolon.push(()); self.print_token(multiline_comment, false); } Expr::UnidentifiedAsLiteral { literal_token } => { self.print_token(&literal_token, true); } } self.print_comments_and_newlines( &expr.trailing_comments, CommentAndNewlinesInstruction { indentation_move: IndentationMove::Stay, leading_newlines: LeadingNewlines::All, respect_user_newline: true, trailing_comment: true, }, ); self.do_not_print_single_newline_statement = false; } fn print_token(&mut self, token: &'a Token<'a>, space_after: bool) { self.print(Printer::get_token_name(&token.token_type), space_after); } fn print(&mut self, this_string: &'a str, space_after: bool) { self.output.push(this_string); if space_after { self.output.push(SPACE); } } fn on_whitespace_line(&self) -> bool { let mut pos = self.output.len(); if pos == 0 { return true; }; pos -= 1; while pos != 0 { match self.output[pos] { SPACE | TAB => { pos -= 1; } NEWLINE => return true, _ => break, } } false } fn prev_line_was_whitespace(&self) -> bool { let mut pos = self.output.len(); if pos < 2 { return false; }; pos -= 1; let mut ignore_newline = true; while pos != 0 { match self.output[pos] { SPACE | TAB => { pos -= 1; } NEWLINE => { if ignore_newline { pos -= 1; ignore_newline = false; } else { return true; } } _ => break, } } false } fn backspace_till_newline(&mut self) { let mut pos = self.output.len(); if pos == 0 { return; }; pos -= 1; while pos != 0 { match self.output[pos] { NEWLINE => break, _ => { self.output.remove(pos); pos -= 1; } }; } } fn backspace_whitespace(&mut self) -> usize { let mut pos = self.output.len(); if pos == 0 { return 0; }; let mut newline_number = 0; pos -= 1; while pos != 0 { match self.output[pos] { NEWLINE => { self.output.remove(pos); pos -= 1; newline_number += 1; } TAB | SPACE => { self.output.remove(pos); pos -= 1; } _ => break, }; } newline_number } fn backspace(&mut self) { let pos = self.output.len(); if pos != 0 && self.on_whitespace_line() == false && self.output[pos - 1] == SPACE { self.output.remove(pos - 1); } } fn ensure_space(&mut self) { if let Some(last_entry) = self.last_entry() { if last_entry == SPACE || last_entry == TAB || last_entry == NEWLINE { return; } } self.print(SPACE, false); } fn ensure_newline(&mut self, indentation_move: IndentationMove) { if let Some(last_entry) = self.last_entry() { if last_entry == NEWLINE { return; } } self.print_newline(indentation_move); } fn last_entry(&mut self) -> Option<&'a str> { let pos = self.output.len(); if pos != 0 { Some(self.output[pos - 1]) } else { None } } fn print_newline(&mut self, indentation_move: IndentationMove) { if self.output.len() == 0 || self.prev_line_was_whitespace() { return; } self.backspace(); self.print(NEWLINE, false); self.print_indentation(indentation_move); } fn print_indentation(&mut self, indentation_move: IndentationMove) { self.set_indentation(indentation_move); self.print_indentation_final(); } fn print_indentation_raw(&mut self, indent_size: usize) { self.indentation = indent_size; self.print_indentation_final(); } fn print_indentation_final(&mut self) { for _ in 0..self.indentation { if self.lang_config.use_spaces { for _ in 0..self.lang_config.space_size { self.print(SPACE, false); } } else { self.print(TAB, false); } } } fn set_indentation(&mut self, indentation_move: IndentationMove) { match indentation_move { IndentationMove::Right => self.indentation += 1, IndentationMove::Stay => {} IndentationMove::Left => { self.indentation -= 1; } } } fn check_indentation(&self, indentation_move: IndentationMove) -> usize { match indentation_move { IndentationMove::Right => self.indentation + 1, IndentationMove::Stay => self.indentation, IndentationMove::Left => self.indentation - 1, } } fn only_newlines(vec: &'a Vec<Token<'a>>) -> bool { for this_token in vec { if let TokenType::Newline(_) = this_token.token_type { continue; } return false; } true } fn print_comments_and_newlines( &mut self, vec: &'a Option<Vec<Token<'a>>>, instructions: CommentAndNewlinesInstruction, ) -> bool { if let Some(vec) = vec { if vec.len() == 0 || (Printer::only_newlines(&vec) && instructions.respect_user_newline == false) { return false; } let mut did_move = false; let mut ignore_newline = instructions.leading_newlines != LeadingNewlines::All; let mut iter = vec.into_iter().peekable(); while let Some(this_one) = iter.next() { match this_one.token_type { TokenType::Newline(user_indentation) => { if ignore_newline { while let Some(next_one) = iter.peek() { if let TokenType::Newline(_) = next_one.token_type { iter.next(); } else { break; } } ignore_newline = false; if instructions.leading_newlines == LeadingNewlines::None { continue; } } if did_move { self.print_newline(IndentationMove::Stay); } else { did_move = true; // check for a force indentation if self.user_indentation_instructions.is_empty() == false && instructions.respect_user_newline && user_indentation >= self.check_indentation(instructions.indentation_move) { if self.prev_line_was_whitespace() { self.backspace_till_newline(); } else { self.backspace(); self.print(NEWLINE, false); } self.print_indentation_raw(user_indentation); } else { self.print_newline(instructions.indentation_move); } } } TokenType::Comment(_) | TokenType::MultilineComment(_) => { if instructions.trailing_comment { self.do_not_need_semicolon.push(()); } self.ensure_space(); self.print_token(&this_one, false); ignore_newline = false; } TokenType::RegionEnd(_) | TokenType::RegionBegin(_) => { if instructions.trailing_comment { self.do_not_need_semicolon.push(()) } self.ensure_space(); self.print_token(&this_one, true); ignore_newline = false; } TokenType::Then => { if instructions.trailing_comment { self.do_not_need_semicolon.push(()) } self.ensure_space(); self.print_token(&this_one, true); ignore_newline = false; } _ => { println!( "Printing {} which isn't newline, comment, or region in a comment_newline section...", this_one ); if instructions.trailing_comment { self.do_not_need_semicolon.push(()) } self.print_token(&this_one, true); } } } did_move } else { false } } pub fn get_token_name(token_type: &'a TokenType<'a>) -> &'a str { match token_type { TokenType::LeftParen => "(", TokenType::RightParen => ")", TokenType::LeftBrace => "{", TokenType::RightBrace => "}", TokenType::LeftBracket => "[", TokenType::RightBracket => "]", TokenType::Comma => ",", TokenType::Dot => ".", TokenType::Colon => ":", TokenType::Semicolon => ";", TokenType::Slash => "/", TokenType::Backslash => "\\", TokenType::Star => "*", TokenType::Mod => "%", TokenType::Hashtag => "#", TokenType::Then => "then", TokenType::ListIndexer => "[|", TokenType::MapIndexer => "[?", TokenType::GridIndexer => "[#", TokenType::ArrayIndexer => "[@", TokenType::LessThanGreaterThan => "<>", TokenType::Minus => "-", TokenType::Plus => "+", TokenType::Incrementer => "++", TokenType::Decrementer => "--", TokenType::Bang => "!", TokenType::Hook => "?", TokenType::Tilde => "~", TokenType::PlusEquals => "+=", TokenType::MinusEquals => "-=", TokenType::StarEquals => "*=", TokenType::SlashEquals => "/=", TokenType::BitXorEquals => "^=", TokenType::BitOrEquals => "|=", TokenType::BitAndEquals => "&=", TokenType::ModEquals => "%=", TokenType::LogicalAnd => "&&", TokenType::LogicalOr => "||", TokenType::LogicalXor => "^^", TokenType::BitAnd => "&", TokenType::BitOr => "|", TokenType::BitXor => "^", TokenType::BitLeft => "<<", TokenType::BitRight => ">>", TokenType::BangEqual => "!=", TokenType::Equal => "=", TokenType::EqualEqual => "==", TokenType::Greater => ">", TokenType::GreaterEqual => ">=", TokenType::Less => "<", TokenType::LessEqual => "<=", TokenType::Define => "#define", TokenType::Var => "var", TokenType::GlobalVar => "globalvar", TokenType::If => "if", TokenType::Else => "else", TokenType::Return => "return", TokenType::For => "for", TokenType::Repeat => "repeat", TokenType::While => "while", TokenType::With => "with", TokenType::Do => "do", TokenType::Until => "until", TokenType::Switch => "switch", TokenType::Case => "case", TokenType::DefaultCase => "default", TokenType::Break => "break", TokenType::Exit => "exit", TokenType::Enum => "enum", TokenType::AndAlias => "and", TokenType::OrAlias => "or", TokenType::XorAlias => "xor", TokenType::NotAlias => "not", TokenType::ModAlias => "mod", TokenType::Div => "div", TokenType::Newline(_) => "\n", TokenType::Macro(literal) | TokenType::RegionBegin(literal) | TokenType::RegionEnd(literal) | TokenType::Identifier(literal) | TokenType::String(literal) | TokenType::Number(literal) | TokenType::NumberStartDot(literal) | TokenType::NumberEndDot(literal) | TokenType::Comment(literal) | TokenType::MultilineComment(literal) | TokenType::UnidentifiedInput(literal) => literal, } } fn print_delimited_lines( &mut self, delimited_lines: &'a DelimitedLines<'a, ExprBox<'a>>, delimiter: &'static str, force_newline_between: bool, force_newline_at_end: bool, ) { let mut iter = delimited_lines.lines.iter().peekable(); while let Some(delimited_line) = iter.next() { self.print_expr(&delimited_line.expr); self.backspace(); let at_end = if let Some(_) = iter.peek() { self.print(delimiter, true); false } else { if delimited_lines.has_end_delimiter { self.print(delimiter, true); } true }; if let Some(_) = &delimited_line.trailing_comment { let did_newlines = self.print_comments_and_newlines( &delimited_line.trailing_comment, CommentAndNewlinesInstruction::new_respect_users(IndentationMove::Stay, LeadingNewlines::All), ); if did_newlines == false && force_newline_between { self.print_newline(IndentationMove::Stay); } } else { if at_end { if force_newline_at_end { self.print_newline(IndentationMove::Stay); } } else { if force_newline_between { self.print_newline(IndentationMove::Stay); } } } } } fn print_semicolon(&mut self, do_it: bool) { if do_it { self.backspace(); self.print(SEMICOLON, true); } } fn print_semicolon_and_newline(&mut self, do_it: bool, indentation_move: IndentationMove) -> bool { if do_it { self.print_semicolon(true); false } else { self.print_semicolon(true); self.print_newline(indentation_move); true } } fn allow_user_indentation(&mut self) { self.user_indentation_instructions.push(self.indentation); } fn rewind_user_indentation(&mut self) { self.indentation = self.user_indentation_instructions.pop().unwrap(); } } #[derive(Debug, Copy, Clone)] enum IndentationMove { Right, Stay, Left, } #[derive(Debug, Copy, Clone, PartialEq)] enum LeadingNewlines { All, One, None, } bitflags::bitflags! { pub struct BlockInstruction: u8 { const NONE = 0b00000000; const NO_NEWLINE_AFTER_BLOCK = 0b00000001; const MUST_INDENT = 0b00000010; } } #[derive(Default)] struct GroupInstruction { force_indentation: Option<IndentationMove>, force_leading_newlines: Option<LeadingNewlines>, force_respect: Option<bool>, } impl GroupInstruction { fn force_indentation(&self) -> IndentationMove { if let Some(ret) = self.force_indentation { ret } else { IndentationMove::Stay } } fn force_leading_newlines(&self) -> LeadingNewlines { if let Some(ret) = self.force_leading_newlines { ret } else { LeadingNewlines::All } } fn force_respect(&self) -> bool { if let Some(ret) = self.force_respect { ret } else { false } } } struct CommentAndNewlinesInstruction { indentation_move: IndentationMove, leading_newlines: LeadingNewlines, respect_user_newline: bool, trailing_comment: bool, } impl CommentAndNewlinesInstruction { pub fn new(indentation_move: IndentationMove, leading_newlines: LeadingNewlines) -> Self { CommentAndNewlinesInstruction { indentation_move, leading_newlines, ..Default::default() } } pub fn new_respect_users(indentation_move: IndentationMove, leading_newlines: LeadingNewlines) -> Self { CommentAndNewlinesInstruction { indentation_move, leading_newlines, respect_user_newline: true, ..Default::default() } } } impl Default for CommentAndNewlinesInstruction { fn default() -> Self { CommentAndNewlinesInstruction { indentation_move: IndentationMove::Stay, leading_newlines: LeadingNewlines::One, respect_user_newline: false, trailing_comment: false, } } }
/// Known identifiers for the types of packets that might be captured in a `pcap` file. This tells /// you how to interpret the packets you receive. /// /// Look at [tcpdump.org](http://www.tcpdump.org/linktypes.html) for the canonical list with /// descriptions. #[derive(Copy, Clone, Debug, PartialEq, FromPrimitive, ToPrimitive)] #[repr(u32)] #[allow(non_camel_case_types)] pub enum LinkType { NULL = 0, /// Ethernet packets ETHERNET = 1, AX25 = 3, IEEE802_5 = 6, ARCNET_BSD = 7, SLIP = 8, PPP = 9, FDDI = 10, PPP_HDLC = 50, PPP_ETHER = 51, ATM_RFC1483 = 100, /// IP packets (IPv4 or IPv6) RAW = 101, C_HDLC = 104, IEEE802_11 = 105, FRELAY = 107, LOOP = 108, LINUX_SLL = 113, LTALK = 114, PFLOG = 117, IEEE802_11_PRISM = 119, IP_OVER_FC = 122, SUNATM = 123, IEEE802_11_RADIOTAP = 127, ARCNET_LINUX = 129, APPLE_IP_OVER_IEEE1394 = 138, MTP2_WITH_PHDR = 139, MTP2 = 140, MTP3 = 141, SCCP = 142, DOCSIS = 143, LINUX_IRDA = 144, USER00_LINKTYPE = 147, USER01_LINKTYPE = 148, USER02_LINKTYPE = 149, USER03_LINKTYPE = 150, USER04_LINKTYPE = 151, USER05_LINKTYPE = 152, USER06_LINKTYPE = 153, USER07_LINKTYPE = 154, USER08_LINKTYPE = 155, USER09_LINKTYPE = 156, USER10_LINKTYPE = 157, USER11_LINKTYPE = 158, USER12_LINKTYPE = 159, USER13_LINKTYPE = 160, USER14_LINKTYPE = 161, USER15_LINKTYPE = 162, IEEE802_11_AVS = 163, BACNET_MS_TP = 165, PPP_PPPD = 166, GPRS_LLC = 169, GPF_T = 170, GPF_F = 171, LINUX_LAPD = 177, BLUETOOTH_HCI_H4 = 187, USB_LINUX = 189, PPI = 192, IEEE802_15_4 = 195, SITA = 196, ERF = 197, BLUETOOTH_HCI_H4_WITH_PHDR = 201, AX25_KISS = 202, LAPD = 203, PPP_WITH_DIR = 204, C_HDLC_WITH_DIR = 205, FRELAY_WITH_DIR = 206, IPMB_LINUX = 209, IEEE802_15_4_NONASK_PHY = 215, USB_LINUX_MMAPPED = 220, FC_2 = 224, FC_2_WITH_FRAME_DELIMS = 225, IPNET = 226, CAN_SOCKETCAN = 227, IPV4 = 228, IPV6 = 229, IEEE802_15_4_NOFCS = 230, DBUS = 231, DVB_CI = 235, MUX27010 = 236, STANAG_5066_D_PDU = 237, NFLOG = 239, NETANALYZER = 240, NETANALYZER_TRANSPARENT = 241, IPOIB = 242, MPEG_2_TS = 243, NG40 = 244, NFC_LLCP = 245, INFINIBAND = 247, SCTP = 248, USBPCAP = 249, RTAC_SERIAL = 250, BLUETOOTH_LE_LL = 251, NETLINK = 253, BLUETOOTH_LINUX_MONITOR = 254, BLUETOOTH_BREDR_BB = 255, BLUETOOTH_LE_LL_WITH_PHDR = 256, PROFIBUS_DL = 257, PKTAP = 258, EPON = 259, IPMI_HPM_2 = 260, ZWAVE_R1_R2 = 261, ZWAVE_R3 = 262, WATTSTOPPER_DLM = 263, ISO_14443 = 264, RDS = 265, USB_DARWIN = 266, } impl Default for LinkType { fn default() -> Self { LinkType::NULL } }
extern crate wasmer_runtime; extern crate wasmer_runtime_core; use libc::{uint32_t, uint8_t}; pub mod error; pub mod export; pub mod global; pub mod import; pub mod instance; pub mod memory; pub mod module; pub mod table; pub mod value; #[allow(non_camel_case_types)] #[repr(C)] pub enum wasmer_result_t { WASMER_OK = 1, WASMER_ERROR = 2, } #[repr(C)] pub struct wasmer_limits_t { pub min: uint32_t, pub max: wasmer_limit_option_t, } #[repr(C)] pub struct wasmer_limit_option_t { pub has_some: bool, pub some: uint32_t, } #[repr(C)] pub struct wasmer_byte_array { bytes: *const uint8_t, bytes_len: uint32_t, }
fn is_prime(i: &u32) -> bool { let mut temp: u32 = 2; while i > &temp { if i % &temp == 0 { return false; } temp += 1; } true } pub fn nth(n: u32) -> Option<u32> { let mut init_vec: Vec<u32> = Vec::new(); let mut i: u32 = 2; let mut counter: u32 = 0; if n == 0 { return None; } loop { if is_prime(&i) { counter += 1; init_vec.push(i); } i += 1; if counter == n { break; } } init_vec.pop() }
pub use crate::{ ApplyLog, AsyncOnceCell, Ctx, Entity, Get, HashTable, Insert, InsertMut, OnceCell, ProviderContainer, QueueRwLock, Remove, Tag, Transaction, VecTable, }; #[cfg(feature = "derive")] pub use crate::indexing;
// q0103_binary_tree_zigzag_level_order_traversal struct Solution; use crate::util::TreeNode; use std::cell::RefCell; use std::rc::Rc; impl Solution { pub fn zigzag_level_order(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<Vec<i32>> { if let Some(rrc_root) = root { let mut ret = vec![]; let mut level_node = vec![rrc_root]; let mut reserve = false; loop { let mut new_level_node = vec![]; let mut level_ret = vec![]; for node in level_node.iter() { let val = node.borrow().val; level_ret.push(val); if let Some(ref ln) = node.borrow().left { new_level_node.push(Rc::clone(ln)); } if let Some(ref rn) = node.borrow().right { new_level_node.push(Rc::clone(rn)); } } if !reserve { ret.push(level_ret); } else { let reserved = level_ret.into_iter().rev().collect(); ret.push(reserved); } reserve = !reserve; if new_level_node.is_empty() { break; } else { std::mem::replace(&mut level_node, new_level_node); } } return ret; } else { return vec![]; } } } #[cfg(test)] mod tests { use super::Solution; use crate::util::TreeNode; #[test] fn it_works() { assert_eq!( Solution::zigzag_level_order(TreeNode::build(vec![ Some(3), Some(9), Some(20), None, None, Some(15), Some(7) ])), vec![vec![3], vec![20, 9], vec![15, 7]] ); assert_eq!( Solution::zigzag_level_order(TreeNode::build(vec![ Some(1), Some(2), Some(3), Some(4), None, None, Some(5) ])), vec![vec![1], vec![3, 2], vec![4, 5]] ); } }
use serde::{Deserialize, Serialize}; /// Version number. #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Serialize, Deserialize)] pub struct VersionNumber(u64); impl VersionNumber { pub(crate) fn initial() -> Self { Self(1) } pub(crate) fn next(&self) -> Self { Self(self.0 + 1) } /// Raw version number. pub fn to_u64(&self) -> u64 { self.0 } } impl From<u64> for VersionNumber { fn from(n: u64) -> Self { Self(n) } } impl From<i64> for VersionNumber { fn from(n: i64) -> Self { Self(n as u64) } }
#[doc = "Register `CR` reader"] pub type R = crate::R<CR_SPEC>; #[doc = "Register `CR` writer"] pub type W = crate::W<CR_SPEC>; #[doc = "Field `RNGEN` reader - Random number generator enable"] pub type RNGEN_R = crate::BitReader<RNGEN_A>; #[doc = "Random number generator enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RNGEN_A { #[doc = "0: Random number generator is disabled"] Disabled = 0, #[doc = "1: Random number generator is enabled"] Enabled = 1, } impl From<RNGEN_A> for bool { #[inline(always)] fn from(variant: RNGEN_A) -> Self { variant as u8 != 0 } } impl RNGEN_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RNGEN_A { match self.bits { false => RNGEN_A::Disabled, true => RNGEN_A::Enabled, } } #[doc = "Random number generator is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == RNGEN_A::Disabled } #[doc = "Random number generator is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == RNGEN_A::Enabled } } #[doc = "Field `RNGEN` writer - Random number generator enable"] pub type RNGEN_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, RNGEN_A>; impl<'a, REG, const O: u8> RNGEN_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Random number generator is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(RNGEN_A::Disabled) } #[doc = "Random number generator is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(RNGEN_A::Enabled) } } #[doc = "Field `IE` reader - Interrupt enable"] pub type IE_R = crate::BitReader<IE_A>; #[doc = "Interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IE_A { #[doc = "0: RNG interrupt is disabled"] Disabled = 0, #[doc = "1: RNG interrupt is enabled"] Enabled = 1, } impl From<IE_A> for bool { #[inline(always)] fn from(variant: IE_A) -> Self { variant as u8 != 0 } } impl IE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> IE_A { match self.bits { false => IE_A::Disabled, true => IE_A::Enabled, } } #[doc = "RNG interrupt is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == IE_A::Disabled } #[doc = "RNG interrupt is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == IE_A::Enabled } } #[doc = "Field `IE` writer - Interrupt enable"] pub type IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, IE_A>; impl<'a, REG, const O: u8> IE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "RNG interrupt is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(IE_A::Disabled) } #[doc = "RNG interrupt is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(IE_A::Enabled) } } #[doc = "Field `CED` reader - Clock error detection Note: The clock error detection can be used only when ck_rc48 or ck_pll1_q (ck_pll1_q = 48MHz) source is selected otherwise, CED bit must be equal to 1. The clock error detection cannot be enabled nor disabled on the fly when RNG peripheral is enabled, to enable or disable CED the RNG must be disabled."] pub type CED_R = crate::BitReader<CED_A>; #[doc = "Clock error detection Note: The clock error detection can be used only when ck_rc48 or ck_pll1_q (ck_pll1_q = 48MHz) source is selected otherwise, CED bit must be equal to 1. The clock error detection cannot be enabled nor disabled on the fly when RNG peripheral is enabled, to enable or disable CED the RNG must be disabled.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum CED_A { #[doc = "0: Clock error detection is enabled"] Enabled = 0, #[doc = "1: Clock error detection is disabled"] Disabled = 1, } impl From<CED_A> for bool { #[inline(always)] fn from(variant: CED_A) -> Self { variant as u8 != 0 } } impl CED_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CED_A { match self.bits { false => CED_A::Enabled, true => CED_A::Disabled, } } #[doc = "Clock error detection is enabled"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CED_A::Enabled } #[doc = "Clock error detection is disabled"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CED_A::Disabled } } #[doc = "Field `CED` writer - Clock error detection Note: The clock error detection can be used only when ck_rc48 or ck_pll1_q (ck_pll1_q = 48MHz) source is selected otherwise, CED bit must be equal to 1. The clock error detection cannot be enabled nor disabled on the fly when RNG peripheral is enabled, to enable or disable CED the RNG must be disabled."] pub type CED_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, CED_A>; impl<'a, REG, const O: u8> CED_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Clock error detection is enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut crate::W<REG> { self.variant(CED_A::Enabled) } #[doc = "Clock error detection is disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut crate::W<REG> { self.variant(CED_A::Disabled) } } impl R { #[doc = "Bit 2 - Random number generator enable"] #[inline(always)] pub fn rngen(&self) -> RNGEN_R { RNGEN_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Interrupt enable"] #[inline(always)] pub fn ie(&self) -> IE_R { IE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 5 - Clock error detection Note: The clock error detection can be used only when ck_rc48 or ck_pll1_q (ck_pll1_q = 48MHz) source is selected otherwise, CED bit must be equal to 1. The clock error detection cannot be enabled nor disabled on the fly when RNG peripheral is enabled, to enable or disable CED the RNG must be disabled."] #[inline(always)] pub fn ced(&self) -> CED_R { CED_R::new(((self.bits >> 5) & 1) != 0) } } impl W { #[doc = "Bit 2 - Random number generator enable"] #[inline(always)] #[must_use] pub fn rngen(&mut self) -> RNGEN_W<CR_SPEC, 2> { RNGEN_W::new(self) } #[doc = "Bit 3 - Interrupt enable"] #[inline(always)] #[must_use] pub fn ie(&mut self) -> IE_W<CR_SPEC, 3> { IE_W::new(self) } #[doc = "Bit 5 - Clock error detection Note: The clock error detection can be used only when ck_rc48 or ck_pll1_q (ck_pll1_q = 48MHz) source is selected otherwise, CED bit must be equal to 1. The clock error detection cannot be enabled nor disabled on the fly when RNG peripheral is enabled, to enable or disable CED the RNG must be disabled."] #[inline(always)] #[must_use] pub fn ced(&mut self) -> CED_W<CR_SPEC, 5> { CED_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 = "RNG control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr::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 [`cr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct CR_SPEC; impl crate::RegisterSpec for CR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`cr::R`](R) reader structure"] impl crate::Readable for CR_SPEC {} #[doc = "`write(|w| ..)` method takes [`cr::W`](W) writer structure"] impl crate::Writable for CR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets CR to value 0"] impl crate::Resettable for CR_SPEC { const RESET_VALUE: Self::Ux = 0; }
mod query_grammar; mod query_parser; mod user_input_ast; pub mod logical_ast; pub use self::query_parser::QueryParser; pub use self::query_parser::QueryParserError;
//! Types used to deserialize and work with data received from the API. use std::fmt; use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; use optfield::optfield; use serde::{Deserialize, Serialize}; use url::Url; use crate::error::*; use crate::params::{EpisodeParams, EpisodeQuery, EpisodeQueryParams}; use crate::serialization as ser; use crate::urls; mod movie; pub use movie::*; #[derive(Debug, Deserialize)] pub(crate) struct ResponseData<T> { pub(crate) data: T, } /// Custom type used for [`Series`] ids. /// /// [`Series`]: struct.Series.html #[derive( Clone, Copy, Debug, Default, Hash, PartialEq, PartialOrd, Ord, Eq, Deserialize, Serialize, )] pub struct SeriesID(pub u32); impl fmt::Display for SeriesID { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl From<u32> for SeriesID { fn from(i: u32) -> Self { Self(i) } } impl From<&SearchSeries> for SeriesID { fn from(s: &SearchSeries) -> SeriesID { s.id } } impl From<&Series> for SeriesID { fn from(s: &Series) -> SeriesID { s.id } } impl From<&SeriesUpdate> for SeriesID { fn from(s: &SeriesUpdate) -> SeriesID { s.id } } /// Custom type used for [`Episode`] ids. /// /// [`Episode`]: struct.Episode.html #[derive( Clone, Copy, Debug, Default, Hash, PartialEq, PartialOrd, Ord, Eq, Deserialize, Serialize, )] pub struct EpisodeID(pub u32); impl fmt::Display for EpisodeID { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl From<u32> for EpisodeID { fn from(i: u32) -> Self { Self(i) } } impl From<&Episode> for EpisodeID { fn from(e: &Episode) -> EpisodeID { e.id } } /// Series data returned by [`Client::search`]. /// /// Contains less information than `Series`, but can be used /// to get all the data. /// /// See [`Client::search`] and [`Client::series`] for more info. /// /// [`Client::search`]: ../client/struct.Client.html#method.search /// [`Client::series`]: ../client/struct.Client.html#method.series #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct SearchSeries { /// Series aliases. pub aliases: Vec<String>, /// Path to the series' banner. /// /// Use [`banner_url`](#method.banner_url) for a full URL. #[serde(deserialize_with = "ser::optional_string")] pub banner: Option<String>, /// Date when series was first aired. #[serde(with = "ser::optional_naive_date")] pub first_aired: Option<NaiveDate>, /// ID of the series. pub id: SeriesID, /// The series' network. #[serde(deserialize_with = "ser::optional_string")] pub network: Option<String>, /// Short description of the series. pub overview: Option<String>, /// Name of the series. pub series_name: Option<String>, /// Slug used to create the full [`website_url`](#method.website_url) for /// this series. pub slug: String, /// Status of the series. /// /// See [`SeriesStatus`](./enum.SeriesStatus.html) for more info. pub status: SeriesStatus, } macro_rules! series_banner_url_method { () => { /// Returns the full URL to the series' banner. /// /// # Errors /// Will fail if series `banner` is `None`. pub fn banner_url(&self) -> Result<Url> { urls::opt_image(&self.banner) } }; } macro_rules! series_website_url_method { () => { /// Returns the full `thetvdb.com` website series URL. /// /// # Errors /// Will fail if the series `slug` is somehow malformed /// and cannot be parsed into an `Url`. pub fn website_url(&self) -> Result<Url> { urls::series_website(&self.slug) } }; } impl SearchSeries { series_banner_url_method!(); series_website_url_method!(); } #[optfield( pub FilteredSeries, doc = r#" Series data returned by [`Client::series_filter`]. Contains the same fields as [`Series`], but all values are optional. Will only contain values of the selected fields that the API returned. For more info see [`Client::series_filter`]. [`Client::series_filter`]: ../client/struct.Client.html#method.series_filter [`Series`]: struct.Series.html "#, attrs = ( derive(Clone, Debug, PartialEq, Deserialize, Serialize), cfg_attr(test, derive(Default)), non_exhaustive, serde(rename_all = "camelCase") ), field_doc, field_attrs = add( serde(default) ) )] /// Full series data returned by [`Client::series`]. /// /// See linked method for more info. /// /// [`Client::series`]: ../client/struct.Client.html#method.series #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct Series { /// ID of the series. pub id: SeriesID, /// Name of the series. #[serde(deserialize_with = "ser::optional_string")] pub series_name: Option<String>, /// The date and time when the series was added to TheTVDB. #[serde(with = "ser::optional_date_time")] pub added: Option<DateTime<Utc>>, // although not in the official docs, // `added_by` is returned by the API /// ID of the user that added the series to TheTVDB. pub added_by: Option<u32>, /// Day or days of week when series airs. #[serde(deserialize_with = "ser::optional_string")] pub airs_day_of_week: Option<String>, /// Time of day when the episodes air. #[serde(with = "ser::optional_naive_time")] pub airs_time: Option<NaiveTime>, /// Series aliases. pub aliases: Vec<String>, /// Series current season. pub season: String, /// Path to the series' banner. /// /// Use [`banner_url`](#method.banner_url) for a full URL. #[serde(deserialize_with = "ser::optional_string")] pub banner: Option<String>, /// Path to the series' poster. /// /// Use [`poster_url`](#method.poster_url) for a full URL. #[serde(deserialize_with = "ser::optional_string")] pub poster: Option<String>, /// Path to the series' fanart. /// /// Use [`fanart_url`](#method.fanart_url) for a full URL. #[serde(deserialize_with = "ser::optional_string")] pub fanart: Option<String>, /// Date when series was first aired. #[serde(with = "ser::optional_naive_date")] pub first_aired: Option<NaiveDate>, /// List of the series' genres. pub genre: Vec<String>, /// IMDb ID of the series. #[serde(deserialize_with = "ser::optional_string")] pub imdb_id: Option<String>, /// Time and date when series was last updated. #[serde(with = "ser::optional_ts_seconds_date_time")] pub last_updated: Option<DateTime<Utc>>, /// The series' network. pub network: Option<String>, /// The series' network ID. #[serde(deserialize_with = "ser::optional_string")] pub network_id: Option<String>, /// Short description of the series. #[serde(deserialize_with = "ser::optional_string")] pub overview: Option<String>, /// Series parental guide rating. #[serde(deserialize_with = "ser::optional_string")] pub rating: Option<String>, /// Series episode runtime. pub runtime: String, /// Series language abbreviation. pub language: String, /// Series rating. #[serde(deserialize_with = "ser::optional_float")] pub site_rating: Option<f32>, /// Number of rating votes. pub site_rating_count: u32, /// Series website slug. /// /// Use [`website_url`](#method.website_url) for the full URL. pub slug: String, /// Status of the series. /// /// See [`SeriesStatus`](./enum.SeriesStatus.html) for more info. pub status: SeriesStatus, /// Zap2it ID of the series. #[serde(deserialize_with = "ser::optional_string")] pub zap2it_id: Option<String>, } macro_rules! series_url_methods { () => { series_banner_url_method!(); /// Returns the full URL to the series' poster. /// /// # Errors /// Will fail if series `poster` is `None`. pub fn poster_url(&self) -> Result<Url> { urls::opt_image(&self.poster) } /// Returns the full URL to the series' fanart. /// /// # Errors /// Will fail if series `fanart` is `None`. pub fn fanart_url(&self) -> Result<Url> { urls::opt_image(&self.fanart) } }; } impl Series { series_url_methods!(); series_website_url_method!(); } impl FilteredSeries { series_url_methods!(); /// Returns the full `thetvdb.com` website series URL. /// /// # Errors /// Will fail if the series `slug` is somehow malformed /// and cannot be parsed into an `Url`. pub fn website_url(&self) -> Result<Url> { match self.slug.as_ref() { Some(s) => urls::series_website(&s), None => Err(Error::MissingSeriesSlug), } } } /// Possible series status. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[non_exhaustive] pub enum SeriesStatus { /// Series has ended and no more episodes will be aired. Ended, /// Series is continuing and more episodes will air. Continuing, /// Series is upcoming and no episodes have aired so far. Upcoming, /// Status is unknown. Means that the API didn't return a status. #[serde(rename = "")] Unknown, } #[cfg(test)] impl Default for SeriesStatus { fn default() -> Self { Self::Unknown } } /// Actor data returned by [`Client::series_actors`]. /// /// See linked method for more info. /// /// [`Client::series_actors`]: ../client/struct.Client.html#method.series_actors #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct Actor { /// ID of the actor. pub id: u32, /// ID of the series the actor played this role in. pub series_id: SeriesID, /// Actor's name. pub name: String, /// Role played by actor in this series. pub role: String, /// Sort order as returned by the API. pub sort_order: u32, /// Actor's image path for this series. /// /// Use [`image_url`](#method.image_url) for a full URL. #[serde(deserialize_with = "ser::optional_string")] pub image: Option<String>, /// Image author. pub image_author: Option<u32>, #[serde(with = "ser::optional_date_time")] /// Date and time when the image was added. pub image_added: Option<DateTime<Utc>>, /// Date and time when this actor/role was last updated. #[serde(with = "ser::optional_date_time")] pub last_updated: Option<DateTime<Utc>>, } impl Actor { /// Returns the full URL of an actor's image. /// /// # Errors /// Will fail if series `image` is `None`. pub fn image_url(&self) -> Result<Url> { urls::opt_image(&self.image) } } /// Episode data returned by [`Client::series_episodes`], /// [`Client::series_episodes_query`] and [`Client::episode`]. /// /// See linked methods for more info. /// /// [`Client::series_episodes`]: ../client/struct.Client.html#method.series_episodes /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query /// [`Client::episode`]: ../client/struct.Client.html#method.episode #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct Episode { /// ID of the episode. pub id: EpisodeID, /// Season that episode is part of. pub aired_season: Option<u32>, /// Episode season ID. #[serde(rename = "airedSeasonID")] pub aired_season_id: Option<u32>, /// Episode number in season. pub aired_episode_number: u32, /// Name of the episode. #[serde(deserialize_with = "ser::optional_string")] pub episode_name: Option<String>, /// Date when episode was first aired. #[serde(with = "ser::optional_naive_date")] pub first_aired: Option<NaiveDate>, /// List of guest stars playing in this episode. pub guest_stars: Vec<String>, /// List of this episode's directors. pub directors: Vec<String>, /// List of this episode's writers. pub writers: Vec<String>, /// Short description of this episode. #[serde(deserialize_with = "ser::optional_string")] pub overview: Option<String>, /// Language info of episode data. /// /// See [`EpisodeLanguage`](./struct.EpisodeLanguage.html) /// for more info. pub language: EpisodeLanguage, /// Episode production code. #[serde(deserialize_with = "ser::optional_string")] pub production_code: Option<String>, /// Show URL. #[serde(deserialize_with = "ser::optional_string")] pub show_url: Option<String>, /// Date and time when episode was last updated. #[serde(with = "ser::optional_ts_seconds_date_time")] pub last_updated: Option<DateTime<Utc>>, /// Episode DVD ID. #[serde(deserialize_with = "ser::optional_string")] pub dvd_discid: Option<String>, /// DVD season. pub dvd_season: Option<u32>, /// Episode's number on DVD. pub dvd_episode_number: Option<u32>, /// DVD chapter. pub dvd_chapter: Option<u32>, /// Episode's absolute number. pub absolute_number: Option<u32>, /// Path to episode's image. /// /// For the full URL use [`filename_url`](#method.filename_url). #[serde(deserialize_with = "ser::optional_string")] pub filename: Option<String>, /// ID of series that episode is part of. pub series_id: SeriesID, /// User ID that last updated this episode. pub last_updated_by: Option<u32>, /// Season this episode airs after. pub airs_after_season: Option<u32>, /// Season thie episode airs before. pub airs_before_season: Option<u32>, /// Episode this episode airs before. pub airs_before_episode: Option<u32>, /// Author of episode image. pub thumb_author: Option<u32>, /// Date and time image was added. #[serde(with = "ser::optional_date_time")] pub thumb_added: Option<DateTime<Utc>>, /// Image width. pub thumb_width: Option<String>, /// Image height. pub thumb_height: Option<String>, /// Episode's IMDb ID. #[serde(deserialize_with = "ser::optional_string")] pub imdb_id: Option<String>, /// Episode parental guideline rating. pub content_rating: Option<String>, /// Episode rating. #[serde(deserialize_with = "ser::optional_float")] pub site_rating: Option<f32>, /// Number of rating votes. pub site_rating_count: u32, /// Is this episode a movie? #[serde(with = "ser::int_bool")] pub is_movie: bool, } impl Episode { /// Returns the full URL of the episode's image. /// /// # Errors /// Will fail if episode `filename` is `None`. pub fn filename_url(&self) -> Result<Url> { urls::opt_image(&self.filename) } } /// Episode language info. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct EpisodeLanguage { /// Abbreviation of the episode name language. pub episode_name: String, /// Abbreviation of the episode overview language. pub overview: String, } /// Struct used for episode pagination returned by [`Client::series_episodes`]. /// /// Can be used to generate params for querying the next or previous pages. /// /// See [`Client::series_episodes`] for more info. /// /// [`Client::series_episodes`]: ../client/struct.Client.html#method.series_episodes #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct EpisodePage<E = Episode> { /// The episodes on this page. #[serde(rename = "data")] pub episodes: Vec<E>, #[serde(skip)] pub(crate) series_id: SeriesID, links: PageLinks, } impl<E> EpisodePage<E> { /// Generate `EpisodeParams` to fetch the next page with /// [`Client::series_episodes`]. /// /// Will return `None` if there is no next page. /// /// [`Client::series_episodes`]: ../client/struct.Client.html#method.series_episodes pub fn next_page_params(&self) -> Option<EpisodeParams> { self.next_page() .map(|n| EpisodeParams::with_page(self.series_id, n)) } /// Generate `EpisodeParams` to fetch the previous page with /// [`Client::series_episodes`]. /// /// Will return `None` if there is no previous page. /// /// [`Client::series_episodes`]: ../client/struct.Client.html#method.series_episodes pub fn prev_page_params(&self) -> Option<EpisodeParams> { self.prev_page() .map(|p| EpisodeParams::with_page(self.series_id, p)) } /// Generate `EpisodeParams` to fetch the first page with /// [`Client::series_episodes`](../client/struct.Client.html#method.series_episodes) pub fn first_page_params(&self) -> EpisodeParams { EpisodeParams::with_page(self.series_id, self.first_page()) } /// Generate `EpisodeParams` to fetch the last page with /// [`Client::series_episodes`](../client/struct.Client.html#method.series_episodes) pub fn last_page_params(&self) -> EpisodeParams { EpisodeParams::with_page(self.series_id, self.last_page()) } } /// Struct used for queried episode pagination returned by /// [`Client::series_episodes_query`]. /// /// Works the same as [`EpisodePage`]. /// /// See [`Client::series_episodes_query`] and [`Client::series_episodes`] for more /// info. /// /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query /// [`Client::series_episodes`]: ../client/struct.Client.html#method.series_episodes /// [`EpisodePage`]: struct.EpisodePage.html #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct EpisodeQueryPage<E = Episode> { /// The episodes on this page. #[serde(rename = "data")] pub episodes: Vec<E>, #[serde(skip)] pub(crate) series_id: SeriesID, #[serde(skip)] pub(crate) query: EpisodeQuery, links: PageLinks, } impl<E> EpisodeQueryPage<E> { /// Generate `EpisodeQueryParams` to fetch the next page of query results /// with [`Client::series_episodes_query`]. /// /// Will return `None` if there is no next page. /// /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query pub fn next_page_query_params(&self) -> Option<EpisodeQueryParams> { self.next_page() .map(|n| EpisodeQueryParams::with_page_query(self.series_id, n, self.query.clone())) } /// Generate `EpisodeQueryParams` to fetch the previous page of query /// results with [`Client::series_episodes_query`]. /// /// Will return `None` if there is no previous page. /// /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query pub fn prev_page_query_params(&self) -> Option<EpisodeQueryParams> { self.prev_page() .map(|p| EpisodeQueryParams::with_page_query(self.series_id, p, self.query.clone())) } /// Generate `EpisodeQueryParams` to fetch the first page of query results /// with [`Client::series_episodes_query`]. /// /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query pub fn first_page_query_params(&self) -> EpisodeQueryParams { EpisodeQueryParams::with_page_query(self.series_id, self.first_page(), self.query.clone()) } /// Generate `EpisodeQueryParams` to fetch the last page of query results /// with [`Client::series_episodes_query`]. /// /// [`Client::series_episodes_query`]: ../client/struct.Client.html#method.series_episodes_query pub fn last_page_query_params(&self) -> EpisodeQueryParams { EpisodeQueryParams::with_page_query(self.series_id, self.last_page(), self.query.clone()) } } /// Struct used for page links in paginated API results. #[derive(Clone, Debug, PartialEq, Deserialize)] pub struct PageLinks { first: u16, last: u16, next: Option<u16>, prev: Option<u16>, } impl PageLinks { fn current_page(&self) -> u16 { match (self.next, self.prev) { (Some(n), _) => n - 1, (None, Some(p)) => p + 1, _ => self.first, } } } /// Used for pagination related methods. pub trait Pagination { /// Method to get a reference to the page links. /// /// Used by all the other methods in this trait. fn links(&self) -> &PageLinks; /// The current page. fn current_page(&self) -> u16 { self.links().current_page() } /// The first page. fn first_page(&self) -> u16 { self.links().first } /// The last page. fn last_page(&self) -> u16 { self.links().last } /// The next page, if available. fn next_page(&self) -> Option<u16> { self.links().next } /// The previous page, if available. fn prev_page(&self) -> Option<u16> { self.links().prev } } impl<E> Pagination for EpisodePage<E> { fn links(&self) -> &PageLinks { &self.links } } impl<E> Pagination for EpisodeQueryPage<E> { fn links(&self) -> &PageLinks { &self.links } } /// Episode summary data returned by [`Client::series_episodes_summary`]. /// /// See linked method for more info. /// /// [`Client::series_episodes_summary`]: ../client/struct.Client.html#method.series_episodes_summary #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct EpisodeSummary { /// Number of aired seasons. pub aired_seasons: Vec<String>, /// Number of aired episodes. #[serde(with = "ser::u32_string")] pub aired_episodes: u32, /// Number of seasons on DVD. pub dvd_seasons: Vec<String>, /// Number of episodes on DVD. #[serde(with = "ser::u32_string")] pub dvd_episodes: u32, } /// Series image count data returned by [`Client::series_images`]. /// /// See linked method for more info. /// /// [`Client::series_images`]: ../client/struct.Client.html#method.series_images #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[non_exhaustive] pub struct SeriesImages { /// Number of fan art images. pub fanart: Option<u32>, /// Number of poster images. pub poster: Option<u32>, /// Number of season images. pub season: Option<u32>, /// Number of wide season images. pub seasonwide: Option<u32>, /// Number of series images. pub series: Option<u32>, } /// Image data returned by [`Client::series_images_query`]. /// /// [`Client::series_images_query`]: ../client/struct.Client.html#method.series_images_query #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct Image { /// ID of the image. pub id: u32, /// Image key type (season, series, poster, etc...). pub key_type: String, /// Image subkey. #[serde(deserialize_with = "ser::optional_string")] pub sub_key: Option<String>, /// Image file path. /// /// For the full URL use [`file_name_url`](#method.file_name_url). pub file_name: String, /// ID of image's language. pub language_id: u16, /// Image language abbreviation. pub language: String, /// Image resolution. #[serde(deserialize_with = "ser::optional_string")] pub resolution: Option<String>, /// Image ratings data. /// /// See [`ImageRatingsInfo`](./struct.ImageRatingsInfo.html) for more info. pub ratings_info: ImageRatingsInfo, /// Image thumbnail file path. /// /// For the full URL use [`thumbnail_url`](#method.thumbnail_url). pub thumbnail: String, } impl Image { /// Returns the full URL of the image file. pub fn file_name_url(&self) -> Result<Url> { urls::image(&self.file_name) } /// Returns the full URL of the image's thumbnail. pub fn thumbnail_url(&self) -> Result<Url> { urls::image(&self.thumbnail) } } /// Image ratings data. #[derive(Clone, Debug, PartialEq, Deserialize, Serialize)] #[cfg_attr(test, derive(Default))] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct ImageRatingsInfo { /// Average rating. pub average: f32, /// Number of rating votes. pub count: u32, } /// Image query key data returned by [`Client::series_images_query_params`]. /// /// Can be used to see what types of images can be queried for a series. /// /// See [`Client::series_images_query_params`] and [`Client::series_images_query`] /// for more info. /// /// [`Client::series_images_query_params`]: ../client/struct.Client.html#method.series_images_query_params /// [`Client::series_images_query`]: ../client/struct.Client.html#method.series_images_query #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct ImageQueryKey { /// Key type name. pub key_type: String, /// Key language ID. #[serde(default, deserialize_with = "ser::optional_string")] pub language_id: Option<String>, /// Available resolutions. pub resolution: Vec<String>, /// Available subkeys. pub sub_key: Vec<String>, } /// Series update data returned by [`Client::updated`]. /// /// See linked method for more info. /// /// [`Client::updated`]: ../client/struct.Client.html#method.updated #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] #[non_exhaustive] #[serde(rename_all = "camelCase")] pub struct SeriesUpdate { /// ID of the series. pub id: SeriesID, /// Date and time that series was last updated. #[serde(with = "chrono::serde::ts_seconds")] pub last_updated: DateTime<Utc>, } #[cfg(test)] mod tests;
// PowerPC uses the following registers for args 1-6: // // arg1: r3 // arg2: r4 // arg3: r5 // arg4: r6 // arg5: r7 // arg6: r8 // // Register r0 specifies the syscall number. // Register r3 is also used for the return value. // Registers r0, r3-r12, and cr0 are always clobbered. // // The `sc` instruction is used to perform the syscall. If successful, then it // sets the summary overflow bit (S0) in field 0 of the condition register // (cr0). This is then used to decide if the return value should be negated. use core::arch::asm; use crate::arch::powerpc64::Sysno; /// Issues a raw system call with 0 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall0(n: Sysno) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, lateout("r3") ret, lateout("r4") _, lateout("r5") _, lateout("r6") _, lateout("r7") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 1 argument. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall1(n: Sysno, arg1: usize) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, lateout("r4") _, lateout("r5") _, lateout("r6") _, lateout("r7") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 2 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall2(n: Sysno, arg1: usize, arg2: usize) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, inlateout("r4") arg2 => _, lateout("r5") _, lateout("r6") _, lateout("r7") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 3 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall3( n: Sysno, arg1: usize, arg2: usize, arg3: usize, ) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, inlateout("r4") arg2 => _, inlateout("r5") arg3 => _, lateout("r6") _, lateout("r7") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 4 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall4( n: Sysno, arg1: usize, arg2: usize, arg3: usize, arg4: usize, ) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, inlateout("r4") arg2 => _, inlateout("r5") arg3 => _, inlateout("r6") arg4 => _, lateout("r7") _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 5 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall5( n: Sysno, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, ) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, inlateout("r4") arg2 => _, inlateout("r5") arg3 => _, inlateout("r6") arg4 => _, inlateout("r7") arg5 => _, lateout("r8") _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret } /// Issues a raw system call with 6 arguments. /// /// # Safety /// /// Running a system call is inherently unsafe. It is the caller's /// responsibility to ensure safety. #[inline] pub unsafe fn syscall6( n: Sysno, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) -> usize { let mut ret: usize; asm!( "sc", "bns 1f", "neg 3, 3", "1:", inlateout("r0") n as usize => _, inlateout("r3") arg1 => ret, inlateout("r4") arg2 => _, inlateout("r5") arg3 => _, inlateout("r6") arg4 => _, inlateout("r7") arg5 => _, inlateout("r8") arg6 => _, lateout("r9") _, lateout("r10") _, lateout("r11") _, lateout("r12") _, lateout("cr0") _, options(nostack, preserves_flags) ); ret }
fn main() { tonic_build::compile_protos("proto/plugin/plugin.proto").unwrap(); }
use core::ptr; //Page flags pub const PF_PRESENT: usize = 1; pub const PF_WRITE: usize = 1 << 1; pub const PF_USER: usize = 1 << 2; pub const PF_WRITE_THROUGH: usize = 1 << 3; pub const PF_CACHE_DISABLE: usize = 1 << 4; pub const PF_ACCESSED: usize = 1 << 5; pub const PF_DIRTY: usize = 1 << 6; pub const PF_SIZE: usize = 1 << 7; pub const PF_GLOBAL: usize = 1 << 8; //Extra flags (Redox specific) pub const PF_ALLOC: usize = 1 << 9; pub const PF_EXEC: usize = 1 << 10; pub const PF_STACK: usize = 1 << 11; pub const PF_ALL: usize = 0xFFF; pub const PF_NONE: usize = 0xFFFFFFFFFFFFF000; // PAGE_LEVEL_4: // 512 qwords pointing to page directory pointers // PAGE_DIR_PTRS: // 512 qwords pointing to page directories // PAGE_DIRECTORIES: // 512 qwords pointing to page tables // PAGE_TABLES: // 512 * 512 qwords pointing to pages // PAGE_END: // pub const PAGE_TABLE_SIZE: usize = 512; pub const PAGE_ENTRY_SIZE: usize = 8; pub const PAGE_SIZE: usize = 4096; extern { static mut __bss_end: u8; } pub const PAGE_LEVEL_4: usize = 0x1000000; pub const PAGE_DIR_PTRS: usize = PAGE_LEVEL_4 + PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE; pub const PAGE_DIRECTORIES: usize = PAGE_DIR_PTRS + PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE; pub const PAGE_TABLES: usize = PAGE_DIRECTORIES + 4 * PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE; pub const PAGE_END: usize = PAGE_TABLES + 4 * PAGE_TABLE_SIZE * PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE; /// A memory page pub struct Page { /// The virtual address virtual_address: usize, } impl Page { /// Initialize the memory page pub unsafe fn init() { for l4_i in 0..PAGE_TABLE_SIZE { if l4_i == 0 { ptr::write((PAGE_LEVEL_4 + l4_i * PAGE_ENTRY_SIZE) as *mut usize, (PAGE_DIR_PTRS + l4_i * PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE) | PF_USER | PF_WRITE | PF_PRESENT); //Allow userspace, read/write, present } else { ptr::write((PAGE_LEVEL_4 + l4_i * PAGE_ENTRY_SIZE) as *mut usize, 0); } } for dp_i in 0..PAGE_TABLE_SIZE { if dp_i < 4 { ptr::write((PAGE_DIR_PTRS + dp_i * PAGE_ENTRY_SIZE) as *mut usize, (PAGE_DIRECTORIES + dp_i * PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE) | PF_USER | PF_WRITE | PF_PRESENT); //Allow userspace, read/write, present } else { ptr::write((PAGE_DIR_PTRS + dp_i * PAGE_ENTRY_SIZE) as *mut usize, 0); } } for table_i in 0..4 * PAGE_TABLE_SIZE { ptr::write((PAGE_DIRECTORIES + table_i * PAGE_ENTRY_SIZE) as *mut usize, (PAGE_TABLES + table_i * PAGE_TABLE_SIZE * PAGE_ENTRY_SIZE) | PF_USER | PF_WRITE | PF_PRESENT); //Allow userspace, read/write, present for entry_i in 0..PAGE_TABLE_SIZE { let addr = (table_i * PAGE_TABLE_SIZE + entry_i) * PAGE_SIZE; Page::new(addr).map_kernel_write(addr); } } asm!("mov cr3, $0 mov $0, cr0 or $0, $1 mov cr0, $0" : : "r"(PAGE_LEVEL_4), "r"((1 << 31 | 1 << 16) as usize) : "memory" : "intel", "volatile"); } /// Create a new memory page from a virtual address pub fn new(virtual_address: usize) -> Self { Page { virtual_address: virtual_address } } /// Get the entry address fn entry_address(&self) -> usize { let page = self.virtual_address / PAGE_SIZE; let table = page / PAGE_TABLE_SIZE; let entry = page % PAGE_TABLE_SIZE; PAGE_TABLES + (table * PAGE_TABLE_SIZE + entry) * PAGE_ENTRY_SIZE } /// Flush the memory page unsafe fn flush(&self) { asm!("invlpg [$0]" : : "{rax}"(self.virtual_address) : "memory" : "intel", "volatile"); } /// Get the current physical address pub fn phys_addr(&self) -> usize { unsafe { (ptr::read(self.entry_address() as *mut usize) & PF_NONE) as usize } } /// Get the current virtual address pub fn virt_addr(&self) -> usize { self.virtual_address & PF_NONE } /// Map the memory page to a given physical memory address pub unsafe fn map_kernel_read(&mut self, physical_address: usize) { ptr::write(self.entry_address() as *mut usize, (physical_address & PF_NONE) | PF_PRESENT); //present self.flush(); } /// Map the memory page to a given physical memory address and allow userspace read access pub unsafe fn map_kernel_write(&mut self, physical_address: usize) { ptr::write(self.entry_address() as *mut usize, (physical_address & PF_NONE) | PF_WRITE | PF_PRESENT); //Allow write, present self.flush(); } /// Map the memory page to a given physical memory address and allow userspace read access pub unsafe fn map_user_read(&mut self, physical_address: usize) { ptr::write(self.entry_address() as *mut usize, (physical_address & PF_NONE) | PF_USER | PF_PRESENT); //Allow userspace, present self.flush(); } /// Map the memory page to a given physical memory address and allow userspace read/write access pub unsafe fn map_user_write(&mut self, physical_address: usize) { ptr::write(self.entry_address() as *mut usize, (physical_address & PF_NONE) | PF_USER | PF_WRITE | PF_PRESENT); //Allow userspace, read/write, present self.flush(); } /// Unmap the memory page pub unsafe fn unmap(&mut self) { ptr::write(self.entry_address() as *mut usize, 0); self.flush(); } }
// Copyright (c) 2016, <daggerbot@gmail.com> // This software is available under the terms of the zlib license. // See COPYING.md for more information. use std::cell::RefCell; use std::collections::BTreeMap; use std::convert::TryFrom; use std::ffi::{CStr, CString}; use std::mem; use std::os::raw::*; use std::ptr; use std::rc::Rc; use std::str; use std::sync::Arc; use aurum::linear::Vec2; use x11_dl::xlib; use ::Coord; use error::Result; use event::Event; use id::{Id, IdLock}; use imp::x11::Geometry; use imp::x11::device::DeviceProvider; use imp::x11::display::DisplayShared; use imp::x11::pixel_format::PixelFormatProvider; use util::Get; use window::{WindowBridge, WindowStyle}; // Constants const EVENT_MASK: c_long = xlib::ExposureMask | xlib::StructureNotifyMask; /// Data shared between a `WindowProvider` and its `DisplayProvider`. struct WindowShared { id_lock: Rc<IdLock>, xid: RefCell<Option<xlib::Window>>, size: RefCell<Option<Vec2<c_int>>>, } /// Manages a map of windows by their `XID`. pub struct WindowManager { map: RefCell<BTreeMap<xlib::Window, Rc<WindowShared>>>, } impl WindowManager { pub fn id (&self, xid: xlib::Window) -> Option<Id> { match self.map.borrow().get(&xid) { Some(window) => Some(window.id_lock.id()), None => None, } } pub fn new () -> WindowManager { WindowManager { map: RefCell::new(BTreeMap::new()), } } pub fn remove (&self, xid: xlib::Window) -> Option<Id> { match self.map.borrow_mut().remove(&xid) { Some(window) => { *window.xid.borrow_mut() = None; Some(window.id_lock.id()) }, None => None, } } pub fn resize (&self, xid: xlib::Window, size: Vec2<c_int>) -> Result<Option<Event>> { match self.map.borrow().get(&xid) { Some(window) => { let mut size_ref = window.size.borrow_mut(); if *size_ref == Some(size) { Ok(None) } else { *size_ref = Some(size); Ok(Some(Event::Resize(window.id_lock.id(), try!(Vec2::try_from(size))))) } }, None => Ok(None), } } } impl WindowManager { fn expire (&self, xid: xlib::Window) { if let Some(window) = self.map.borrow().get(&xid) { *window.xid.borrow_mut() = None; } } fn insert (&self, window: Rc<WindowShared>) { let xid = window.xid.borrow().unwrap(); let prev = self.map.borrow_mut().insert(xid, window); assert!(prev.is_none()); } } /// X11 implementation for `Window`. pub struct WindowProvider { display: Rc<DisplayShared>, xlib: Arc<xlib::Xlib>, display_ptr: *mut xlib::Display, shared: Rc<WindowShared>, manager: Rc<WindowManager>, } impl WindowProvider { pub fn geometry (&self) -> Result<Geometry> { Geometry::get(self, try!(self.try_xid())) } pub fn get_attributes (&self) -> Result<xlib::XWindowAttributes> { let xid = try!(self.try_xid()); let mut attr: xlib::XWindowAttributes; unsafe { attr = mem::uninitialized(); if (self.xlib.XGetWindowAttributes)(self.display_ptr, xid, &mut attr) == 0 { return Err(err!(RequestFailed("XGetWindowAttributes"))); } } Ok(attr) } pub fn set_wm_protocols (&self) -> Result<()> { let xid = try!(self.try_xid()); let mut protocols = [ try!(self.display.intern_atom("WM_DELETE_WINDOW")), ]; unsafe { if (self.xlib.XSetWMProtocols)(self.display_ptr, xid, protocols.as_mut_ptr(), try!(c_int::try_from(protocols.len()))) == 0 { return Err(err!(RequestFailed("XSetWMProtocols"))); } } Ok(()) } pub fn try_xid (&self) -> Result<xlib::Window> { match *self.shared.xid.borrow() { Some(xid) => Ok(xid), None => Err(err!(ResourceExpired("Window"))), } } pub fn xid (&self) -> Option<xlib::Window> { *self.shared.xid.borrow() } } impl Drop for WindowProvider { fn drop (&mut self) { if let Some(xid) = self.xid() { unsafe { (self.xlib.XDestroyWindow)(self.display_ptr, xid); } self.manager.expire(xid); } } } impl Get<Rc<DisplayShared>> for WindowProvider { fn get (&self) -> Rc<DisplayShared> { self.display.clone() } } impl WindowBridge for WindowProvider { type Device = DeviceProvider; type PixelFormat = PixelFormatProvider; fn is_alive (&self) -> bool { self.xid().is_some() } fn is_visible (&self) -> Result<bool> { Ok(try!(self.get_attributes()).map_state != xlib::IsUnmapped) } fn new (device: &DeviceProvider, id_lock: Rc<IdLock>, pixel_format: &PixelFormatProvider, size: Vec2<Coord>, _: WindowStyle) -> Result<WindowProvider> { let display: Rc<DisplayShared> = device.get(); let pf_display: Rc<DisplayShared> = pixel_format.get(); let screen_num = device.screen_num(); if display != pf_display || screen_num != pixel_format.screen_num() { return Err(err!(IncompatibleResource("PixelFormat"))); } let display_ptr = display.ptr(); let xlib = display.xlib(); let manager: Rc<WindowManager> = device.get(); let width = try!(c_uint::try_from(size.x)); let height = try!(c_uint::try_from(size.y)); let xid; unsafe { let mut attr: xlib::XSetWindowAttributes = mem::uninitialized(); attr.event_mask = EVENT_MASK; let root = (xlib.XRootWindow)(display_ptr, screen_num); xid = (xlib.XCreateWindow)(display_ptr, root, 0, 0, width, height, 0, pixel_format.depth(), xlib::InputOutput as c_uint, pixel_format.ptr(), xlib::CWEventMask, &mut attr); } let shared = Rc::new(WindowShared { id_lock: id_lock, xid: RefCell::new(Some(xid)), size: RefCell::new(None), }); let window = WindowProvider { display: display, xlib: xlib, display_ptr: display_ptr, shared: shared.clone(), manager: manager.clone(), }; try!(window.set_wm_protocols()); manager.insert(shared); Ok(window) } fn pixel_format (&self) -> Result<PixelFormatProvider> { unsafe { PixelFormatProvider::from_ptr(self, try!(self.get_attributes()).visual) } } fn set_size (&self, size: Vec2<Coord>) -> Result<()> { let xid = try!(self.try_xid()); let width = try!(c_uint::try_from(size.x)); let height = try!(c_uint::try_from(size.y)); unsafe { (self.xlib.XResizeWindow)(self.display_ptr, xid, width, height); } Ok(()) } fn set_title (&self, title: &str) -> Result<()> { let xid = try!(self.try_xid()); let c_title = try!(CString::new(title)); unsafe { (self.xlib.XStoreName)(self.display_ptr, xid, c_title.as_ptr() as *mut c_char); } Ok(()) } fn set_visible (&self, visible: bool) -> Result<()> { let xid = try!(self.try_xid()); unsafe { match visible { true => { (self.xlib.XMapWindow)(self.display_ptr, xid); }, false => { (self.xlib.XUnmapWindow)(self.display_ptr, xid); }, } } Ok(()) } fn size (&self) -> Result<Vec2<Coord>> { Ok(try!(Vec2::try_from(try!(self.geometry()).size))) } fn title (&self, title: &mut String) -> Result<()> { let xid = try!(self.try_xid()); let mut ptr = ptr::null_mut(); unsafe { if (self.xlib.XFetchName)(self.display_ptr, xid, &mut ptr) == 0 { title.clear(); return Ok(()); } let s = try!(str::from_utf8(CStr::from_ptr(ptr as *const c_char).to_bytes())); title.clear(); title.push_str(s); (self.xlib.XFree)(ptr as *mut _); } Ok(()) } }
#[macro_use] extern crate lazy_static; mod component_manager; mod constants; mod easyhash; mod filesystem; mod globals; mod heartbeat; mod locks; mod modular; mod operation; use async_std; use std::{env, error, thread, time}; use std::process::exit; use std::sync::{mpsc}; // Types pub type BoxedError = Box<dyn error::Error + Send + Sync>; pub type BoxedErrorResult<T> = std::result::Result<T, BoxedError>; type ArgResult = (u16); // Functions fn main() -> BoxedErrorResult<()> { let port = parse_args_or_crash(); let (operation_sender, operation_receiver) = mpsc::channel(); async_std::task::block_on(component_manager::startup(port))?; component_manager::start_sender(Some(1000), operation_receiver); component_manager::start_receiver(Some(1000), operation_sender.clone()); component_manager::start_maintainer(Some(500), operation_sender.clone()); component_manager::start_file_server(Some(500), operation_sender.clone()); component_manager::start_console(None, operation_sender.clone()); loop { thread::sleep(time::Duration::from_millis(1000)); } } fn parse_args_or_crash() -> ArgResult { match try_parse_args() { Ok(args) => args, Err(e) => { println!("Error parsing arguments: {}", e); help(); exit(1); } } } fn try_parse_args() -> BoxedErrorResult<ArgResult> { let args: Vec<String> = env::args().collect(); match args.len() { 2 => { let port: u16 = args[1].parse()?; Ok(port) }, _ => Err(String::from("Incorrect number of arguments").into()) } } fn help() { println!("Usage: ./BIN PORT_NUM"); } #[cfg(test)] mod tests { use crate::modular::*; #[test] fn modular_tests() { let m1 = Modular::new(1, 7); assert_eq!(*m1, 1); let m2 = Modular::new(-1, 7); assert_eq!(*m2, 6); let m3 = Modular::new(1, 7); assert_eq!(*(m3 - 2), 6); let m4 = Modular::new(6, 7); assert_eq!(*(m4 + 2 as i32), 1); let m5 = Modular::new(-5435, 1); assert_eq!(*m5, 0); let m6 = Modular::new(5435, 1); assert_eq!(*m6, 0); } }
//! Utilities for window handling of game engine. use egui::CtxRef; use crate::app::DeltaTime; /// General event of game engine window. pub enum Event { /// Called when game window was created. Created, /// Called when game window was resized. Resized(Size), /// Called when game window needs updating. Update(DeltaTime), /// Called when game UI needs updating. UI(CtxRef), /// Called when game window will be destroyed. Destroyed, } /// Size of game engine window. #[derive(Default, Copy, Clone)] pub struct Size { pub width: u32, pub height: u32, } impl Size { /// Creates new size of window. pub const fn new(width: u32, height: u32) -> Self { Self { width, height } } } impl From<[u32; 2]> for Size { fn from(array: [u32; 2]) -> Self { Self::new(array[0], array[1]) } } impl From<Size> for [u32; 2] { fn from(size: Size) -> Self { [size.width, size.height] } } impl From<(u32, u32)> for Size { fn from(tuple: (u32, u32)) -> Self { Self::new(tuple.0, tuple.1) } } impl From<Size> for (u32, u32) { fn from(size: Size) -> Self { (size.width, size.height) } }
use crate::tokenizer::ExprToken; type Error = &'static str; #[derive(PartialEq, Debug, Clone)] pub enum ProcessedExprToken { VarName(String), Number(f64), String(String), Bool(bool), Null, //FnCall(&'a str, Vec<ProcessedToken<'a>>), //Dot VecAccess(String, Vec<Vec<ProcessedExprToken>>), Vector(Vec<ProcessedExprToken>), OpenSBrackets, CloseSBrackets, Parentheses(Vec<ProcessedExprToken>), Brackets(Vec<ProcessedExprToken>), OpenParentheses, CloseParentheses, Mul, Div, Rem, Add, Sub, Eq, NotEq, Gt, Lt, Gtoe, Ltoe, And, Or, Not(Option<Box<ProcessedExprToken>>), Comma, Neg(Box<ProcessedExprToken>), } fn find_matching_parentheses(i: usize, tokens: &[ExprToken]) -> Result<usize, Error> { let mut nested_parentheses = -1; for (index, token) in tokens.iter().enumerate().skip(i + 1) { match token { ExprToken::CloseParentheses => { nested_parentheses += 1; if nested_parentheses == 0 { return Ok(index); } } ExprToken::OpenParentheses => nested_parentheses -= 1, _ => {} } } Err("Unable to find matching parentheses") } fn find_matching_square_bracket(i: usize, tokens: &[ExprToken]) -> Result<usize, Error> { let mut nested_bracket = -1; for (index, token) in tokens.iter().enumerate().skip(i + 1) { match token { ExprToken::CloseSBrackets | ExprToken::VecAccessStart(_) => { nested_bracket += 1; if nested_bracket == 0 { return Ok(index); } } ExprToken::OpenSBrackets => nested_bracket -= 1, _ => {} } } Err("Unable to find matching square bracket") } fn process_vector(tokens: &[ExprToken], i: &mut usize) -> Result<ProcessedExprToken, Error> { let bracket_end = find_matching_square_bracket(*i, tokens)?; let parentheses_content = &tokens[*i + 1..bracket_end]; *i = bracket_end; Ok(ProcessedExprToken::Vector(process_expr_tokens( parentheses_content, )?)) } fn process_vector_access( tokens: &[ExprToken], i: &mut usize, capture: &str, ) -> Result<ProcessedExprToken, Error> { let bracket_end = find_matching_square_bracket(*i, tokens)?; let name = capture.trim_end_matches('[').to_string(); match tokens[bracket_end] { ExprToken::VecAccessStart(_) => { let mut v = Vec::with_capacity(5); //Do while loop while { let a = find_matching_square_bracket(*i, tokens)?; let brackets_content = &tokens[*i + 1..a]; v.push(process_expr_tokens(brackets_content)?); *i = a; a < tokens.len() - 1 } {} Ok(ProcessedExprToken::VecAccess(name, v)) } ExprToken::CloseSBrackets => { let brackets_content = &tokens[*i + 1..bracket_end]; *i = bracket_end; Ok(ProcessedExprToken::VecAccess( name, vec![process_expr_tokens(brackets_content)?], )) } _ => Err("Erro preprocessing vector access"), } } fn process_parentheses(tokens: &[ExprToken], i: &mut usize) -> Result<ProcessedExprToken, Error> { let parentheses_end = find_matching_parentheses(*i, tokens)?; let parentheses_content = &tokens[*i + 1..parentheses_end]; *i = parentheses_end; Ok(ProcessedExprToken::Parentheses(process_expr_tokens( parentheses_content, )?)) } fn process_not_and_negatives(tokens: &[ProcessedExprToken]) -> Vec<ProcessedExprToken> { let mut processed_tokens = Vec::with_capacity(tokens.len()); let mut i = 0; while i < tokens.len() { match &tokens[i] { ProcessedExprToken::Sub => { if i == 0 { processed_tokens.push(ProcessedExprToken::Neg(Box::new(tokens[i + 1].clone()))); i += 1; } else { match tokens[i - 1] { ProcessedExprToken::Number(_) | ProcessedExprToken::CloseParentheses | ProcessedExprToken::Neg(_) | ProcessedExprToken::VarName(_) => { processed_tokens.push(ProcessedExprToken::Sub) } _ => { processed_tokens .push(ProcessedExprToken::Neg(Box::new(tokens[i + 1].clone()))); i += 1; } } } } ProcessedExprToken::Not(_) => { processed_tokens.push(ProcessedExprToken::Not(Some(Box::new( tokens[i + 1].clone(), )))); i += 1; } a => processed_tokens.push(a.clone()), } i += 1; } processed_tokens } pub fn process_expr_tokens(tokens: &[ExprToken]) -> Result<Vec<ProcessedExprToken>, Error> { let mut processed_tokens = Vec::with_capacity(tokens.len()); let mut index = 0; while index < tokens.len() { match &tokens[index] { ExprToken::VarName(a) => processed_tokens.push(ProcessedExprToken::VarName(a.clone())), ExprToken::Number(a) => processed_tokens.push(ProcessedExprToken::Number(*a)), ExprToken::String(a) => processed_tokens.push(ProcessedExprToken::String( a.trim_matches('"').replace("\\n", "\n"), )), ExprToken::Bool(a) => processed_tokens.push(ProcessedExprToken::Bool(*a)), ExprToken::OpenParentheses => { processed_tokens.push(process_parentheses(tokens, &mut index)?) } ExprToken::CloseParentheses => return Err("Unmatched )"), ExprToken::Div => processed_tokens.push(ProcessedExprToken::Div), ExprToken::Mul => processed_tokens.push(ProcessedExprToken::Mul), ExprToken::Rem => processed_tokens.push(ProcessedExprToken::Rem), ExprToken::Add => processed_tokens.push(ProcessedExprToken::Add), ExprToken::Sub => processed_tokens.push(ProcessedExprToken::Sub), ExprToken::Eq => processed_tokens.push(ProcessedExprToken::Eq), ExprToken::NotEq => processed_tokens.push(ProcessedExprToken::NotEq), ExprToken::Gt => processed_tokens.push(ProcessedExprToken::Gt), ExprToken::Lt => processed_tokens.push(ProcessedExprToken::Lt), ExprToken::Gtoe => processed_tokens.push(ProcessedExprToken::Gtoe), ExprToken::Ltoe => processed_tokens.push(ProcessedExprToken::Ltoe), ExprToken::And => processed_tokens.push(ProcessedExprToken::And), ExprToken::Or => processed_tokens.push(ProcessedExprToken::Or), ExprToken::Not => processed_tokens.push(ProcessedExprToken::Not(None)), ExprToken::VecAccessStart(name) => { processed_tokens.push(process_vector_access(tokens, &mut index, name)?) } ExprToken::OpenSBrackets => processed_tokens.push(process_vector(tokens, &mut index)?), ExprToken::CloseSBrackets => return Err("Unmatched ]"), ExprToken::Comma => processed_tokens.push(ProcessedExprToken::Comma), ExprToken::Null => processed_tokens.push(ProcessedExprToken::Null), } index += 1; } Ok(process_not_and_negatives(&processed_tokens)) }
#[cfg(test)] mod tests; mod utils; /// If we list all the natural numbers below 10 that are multiples of 3 or 5, we /// get 3, 5, 6 and 9. The sum of these multiples is 23. /// /// Find the sum of all the multiples of 3 or 5 below 1000. #[allow(dead_code)] fn problem_001() -> i32 { let mut acc: i32 = 0; for i in 0..1000 { if i % 3 == 0 || i % 5 == 0 { acc += i; } } acc } /// Each new term in the Fibonacci sequence is generated by adding the previous /// two terms. By starting with 1 and 2, the first 10 terms will be: /// /// 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... /// /// By considering the terms in the Fibonacci sequence whose values do not /// exceed four million, find the sum of the even-valued terms. #[allow(dead_code)] fn problem_002() -> i64 { fn fib(acc: i64, a: i64, b: i64) -> i64 { if a < 4000000 { if a % 2 == 0 { fib(acc + a, b, a + b) } else { fib(acc, b, a + b) } } else { acc } }; fib(0, 1, 2) } /// The prime factors of 13195 are 5, 7, 13 and 29. /// /// What is the largest prime factor of the number 600851475143 ? #[allow(dead_code)] fn problem_003() -> i64 { let target = 600851475143; let mut f = (target as f64).sqrt() as i64 + 1; while f > 0 { if target % f == 0 && utils::is_prime(f) { return f; } f -= 1; } 0 } /// A palindromic number reads the same both ways. The largest palindrome made /// from the product of two 2-digit numbers is 9009 = 91 × 99. /// /// Find the largest palindrome made from the product of two 3-digit numbers. #[allow(dead_code)] fn problem_004() -> i64{ let mut max = 0; for i in (100..999).rev() { for j in (100..999).rev() { let p = i * j; if max < p && utils::is_palindrome(p) { max = p; } } } max } /// 2520 is the smallest number that can be divided by each of the numbers from /// 1 to 10 without any remainder. /// /// What is the smallest positive number that is evenly divisible by all of the /// numbers from 1 to 20? #[allow(dead_code)] fn problem_005() -> i64 { let mut n = 20; loop { let mut success = true; for i in 1..21 { if n % i != 0 { success = false; break; } } if success { return n; } n += 1; } } fn main() {}
#[doc = "Reader of register DDRPHYC_BISTMSKR1"] pub type R = crate::R<u32, super::DDRPHYC_BISTMSKR1>; #[doc = "Writer for register DDRPHYC_BISTMSKR1"] pub type W = crate::W<u32, super::DDRPHYC_BISTMSKR1>; #[doc = "Register DDRPHYC_BISTMSKR1 `reset()`'s with value 0"] impl crate::ResetValue for super::DDRPHYC_BISTMSKR1 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DQMSK`"] pub type DQMSK_R = crate::R<u16, u16>; #[doc = "Write proxy for field `DQMSK`"] pub struct DQMSK_W<'a> { w: &'a mut W, } impl<'a> DQMSK_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | ((value as u32) & 0xffff); self.w } } #[doc = "Reader of field `DMMSK`"] pub type DMMSK_R = crate::R<u8, u8>; #[doc = "Write proxy for field `DMMSK`"] pub struct DMMSK_W<'a> { w: &'a mut W, } impl<'a> DMMSK_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 16)) | (((value as u32) & 0x03) << 16); self.w } } #[doc = "Reader of field `RASMSK`"] pub type RASMSK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RASMSK`"] pub struct RASMSK_W<'a> { w: &'a mut W, } impl<'a> RASMSK_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 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `CASMSK`"] pub type CASMSK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `CASMSK`"] pub struct CASMSK_W<'a> { w: &'a mut W, } impl<'a> CASMSK_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 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `PARMSK`"] pub type PARMSK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PARMSK`"] pub struct PARMSK_W<'a> { w: &'a mut W, } impl<'a> PARMSK_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `TPDMASK`"] pub type TPDMASK_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TPDMASK`"] pub struct TPDMASK_W<'a> { w: &'a mut W, } impl<'a> TPDMASK_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:15 - DQMSK"] #[inline(always)] pub fn dqmsk(&self) -> DQMSK_R { DQMSK_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:17 - DMMSK"] #[inline(always)] pub fn dmmsk(&self) -> DMMSK_R { DMMSK_R::new(((self.bits >> 16) & 0x03) as u8) } #[doc = "Bit 18 - RASMSK"] #[inline(always)] pub fn rasmsk(&self) -> RASMSK_R { RASMSK_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - CASMSK"] #[inline(always)] pub fn casmsk(&self) -> CASMSK_R { CASMSK_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 30 - PARMSK"] #[inline(always)] pub fn parmsk(&self) -> PARMSK_R { PARMSK_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - TPDMASK"] #[inline(always)] pub fn tpdmask(&self) -> TPDMASK_R { TPDMASK_R::new(((self.bits >> 31) & 0x01) != 0) } } impl W { #[doc = "Bits 0:15 - DQMSK"] #[inline(always)] pub fn dqmsk(&mut self) -> DQMSK_W { DQMSK_W { w: self } } #[doc = "Bits 16:17 - DMMSK"] #[inline(always)] pub fn dmmsk(&mut self) -> DMMSK_W { DMMSK_W { w: self } } #[doc = "Bit 18 - RASMSK"] #[inline(always)] pub fn rasmsk(&mut self) -> RASMSK_W { RASMSK_W { w: self } } #[doc = "Bit 19 - CASMSK"] #[inline(always)] pub fn casmsk(&mut self) -> CASMSK_W { CASMSK_W { w: self } } #[doc = "Bit 30 - PARMSK"] #[inline(always)] pub fn parmsk(&mut self) -> PARMSK_W { PARMSK_W { w: self } } #[doc = "Bit 31 - TPDMASK"] #[inline(always)] pub fn tpdmask(&mut self) -> TPDMASK_W { TPDMASK_W { w: self } } }
extern crate rand; use rand::{thread_rng, Rng}; use std::fs::File; use std::io::BufReader; use std::io::prelude::*; #[derive(PartialEq, Eq, PartialOrd)] struct Group { size: usize, quantum_entanglement: u64, } // 3 groups, A B C // sum A == sum B == sum C // A has fewest # of packages (use product of items in A as tie-breaker) fn main() { let file = File::open("input.txt").expect("file not found"); let mut reader = BufReader::new(file); let mut contents = String::new(); reader.read_to_string(&mut contents).expect("could not read input file"); let mut rng = thread_rng(); let mut packages = Vec::new(); for line in contents.lines() { packages.push(line.parse::<u64>().unwrap()); } let group_size_a = packages.iter().sum::<u64>() / 3; let group_size_b = packages.iter().sum::<u64>() / 4; let mut best_a = Group { size: usize::max_value(), quantum_entanglement: u64::max_value() }; let mut best_b = Group { size: usize::max_value(), quantum_entanglement: u64::max_value() }; // Just randomly shuffle the input MANY times, checking with each iteration // if the vector starts with a group that sums to the desired total. If it // does, assume the remainder can be split evenly, and track the min total // and product to report the lowest. Not guaranteed to work every time, // but should work over time. for _ in 0..1e6 as usize { rng.shuffle(&mut packages); let mut i = 0; let mut sum: u64 = 0; let mut prod: u64 = 1; loop { sum += packages[i]; prod *= packages[i]; i += 1; if sum == group_size_a { let group = Group { size: i, quantum_entanglement: prod }; if group < best_a { best_a = group; } } else if sum == group_size_b { let group = Group { size: i, quantum_entanglement: prod }; if group < best_b { best_b = group; } } if sum >= group_size_a || i > 10 { break; } } } println!("A: {}", best_a.quantum_entanglement); println!("B: {}", best_b.quantum_entanglement); }
use core::ptr; pub unsafe fn init_bss() { extern { static mut __bss_start: u8; static mut __bss_end: u8; } let bss_start = &mut __bss_start as *mut u8; let bss_end = &mut __bss_end as *mut u8; let bss_length = bss_end as usize - bss_start as usize; ptr::write_bytes(bss_start, 0, bss_length); } pub unsafe fn init_data() { extern { static __data_rom: u8; static mut __data_start: u8; static mut __data_end: u8; } let data_rom = &__data_rom as *const u8; let data_start = &mut __data_start as *mut u8; let data_end = &mut __data_end as *mut u8; let data_length = data_end as usize - data_start as usize; ptr::copy_nonoverlapping(data_rom, data_start, data_length); } #[no_mangle] #[inline(always)] pub unsafe extern fn __start() -> ! { use core::ptr; extern { fn main(argc: isize, argv: *const *const u8) -> isize; } main(0, ptr::null()); panic!("execution returned from main"); }
#[doc = "Reader of register MMMS_ADVCH_NI_VALID"] pub type R = crate::R<u32, super::MMMS_ADVCH_NI_VALID>; #[doc = "Writer for register MMMS_ADVCH_NI_VALID"] pub type W = crate::W<u32, super::MMMS_ADVCH_NI_VALID>; #[doc = "Register MMMS_ADVCH_NI_VALID `reset()`'s with value 0"] impl crate::ResetValue for super::MMMS_ADVCH_NI_VALID { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ADV_NI_VALID`"] pub type ADV_NI_VALID_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ADV_NI_VALID`"] pub struct ADV_NI_VALID_W<'a> { w: &'a mut W, } impl<'a> ADV_NI_VALID_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `SCAN_NI_VALID`"] pub type SCAN_NI_VALID_R = crate::R<bool, bool>; #[doc = "Write proxy for field `SCAN_NI_VALID`"] pub struct SCAN_NI_VALID_W<'a> { w: &'a mut W, } impl<'a> SCAN_NI_VALID_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `INIT_NI_VALID`"] pub type INIT_NI_VALID_R = crate::R<bool, bool>; #[doc = "Write proxy for field `INIT_NI_VALID`"] pub struct INIT_NI_VALID_W<'a> { w: &'a mut W, } impl<'a> INIT_NI_VALID_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2); self.w } } impl R { #[doc = "Bit 0 - This bit indicates if the programmed advertisement NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the advertisment event 0 - ADV_NI timer is not valid 1 - ADV_NI timer is valid"] #[inline(always)] pub fn adv_ni_valid(&self) -> ADV_NI_VALID_R { ADV_NI_VALID_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - This bit indicates if the programmed scan NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the scanner event 0 - SCAN_NI timer is not valid 1 - SCAN_NI timer is valid"] #[inline(always)] pub fn scan_ni_valid(&self) -> SCAN_NI_VALID_R { SCAN_NI_VALID_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - This bit indicates if the programmed initiator NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the initiator event 0 - INIT_NI timer is not valid 1 - INIT_NI timer is valid"] #[inline(always)] pub fn init_ni_valid(&self) -> INIT_NI_VALID_R { INIT_NI_VALID_R::new(((self.bits >> 2) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - This bit indicates if the programmed advertisement NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the advertisment event 0 - ADV_NI timer is not valid 1 - ADV_NI timer is valid"] #[inline(always)] pub fn adv_ni_valid(&mut self) -> ADV_NI_VALID_W { ADV_NI_VALID_W { w: self } } #[doc = "Bit 1 - This bit indicates if the programmed scan NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the scanner event 0 - SCAN_NI timer is not valid 1 - SCAN_NI timer is valid"] #[inline(always)] pub fn scan_ni_valid(&mut self) -> SCAN_NI_VALID_W { SCAN_NI_VALID_W { w: self } } #[doc = "Bit 2 - This bit indicates if the programmed initiator NI_TIMER is valid. FW sets this bit to indicate that the NI_TIMER is programmed. HW clears this bit on servicing the initiator event 0 - INIT_NI timer is not valid 1 - INIT_NI timer is valid"] #[inline(always)] pub fn init_ni_valid(&mut self) -> INIT_NI_VALID_W { INIT_NI_VALID_W { w: self } } }
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use testcore::*; use consts::*; use wasmlib::*; mod testcore; mod consts; #[no_mangle] fn on_load() { let exports = ScExports::new(); exports.add_func(FUNC_CALL_ON_CHAIN, func_call_on_chain); exports.add_func(FUNC_CHECK_CONTEXT_FROM_FULL_EP, func_check_context_from_full_ep); exports.add_func(FUNC_DO_NOTHING, func_do_nothing); exports.add_func(FUNC_INIT, func_init); exports.add_func(FUNC_PASS_TYPES_FULL, func_pass_types_full); exports.add_func(FUNC_RUN_RECURSION, func_run_recursion); exports.add_func(FUNC_SEND_TO_ADDRESS, func_send_to_address); exports.add_func(FUNC_SET_INT, func_set_int); exports.add_func(FUNC_TEST_CALL_PANIC_FULL_EP, func_test_call_panic_full_ep); exports.add_func(FUNC_TEST_CALL_PANIC_VIEW_EPFROM_FULL, func_test_call_panic_view_epfrom_full); exports.add_func(FUNC_TEST_CHAIN_OWNER_IDFULL, func_test_chain_owner_idfull); exports.add_func(FUNC_TEST_CONTRACT_IDFULL, func_test_contract_idfull); exports.add_func(FUNC_TEST_EVENT_LOG_DEPLOY, func_test_event_log_deploy); exports.add_func(FUNC_TEST_EVENT_LOG_EVENT_DATA, func_test_event_log_event_data); exports.add_func(FUNC_TEST_EVENT_LOG_GENERIC_DATA, func_test_event_log_generic_data); exports.add_func(FUNC_TEST_PANIC_FULL_EP, func_test_panic_full_ep); exports.add_func(FUNC_WITHDRAW_TO_CHAIN, func_withdraw_to_chain); exports.add_view(VIEW_CHECK_CONTEXT_FROM_VIEW_EP, view_check_context_from_view_ep); exports.add_view(VIEW_FIBONACCI, view_fibonacci); exports.add_view(VIEW_GET_COUNTER, view_get_counter); exports.add_view(VIEW_GET_INT, view_get_int); exports.add_view(VIEW_JUST_VIEW, view_just_view); exports.add_view(VIEW_PASS_TYPES_VIEW, view_pass_types_view); exports.add_view(VIEW_TEST_CALL_PANIC_VIEW_EPFROM_VIEW, view_test_call_panic_view_epfrom_view); exports.add_view(VIEW_TEST_CHAIN_OWNER_IDVIEW, view_test_chain_owner_idview); exports.add_view(VIEW_TEST_CONTRACT_IDVIEW, view_test_contract_idview); exports.add_view(VIEW_TEST_PANIC_VIEW_EP, view_test_panic_view_ep); exports.add_view(VIEW_TEST_SANDBOX_CALL, view_test_sandbox_call); }
//! Main application class module //! Handles all platform-related, hardware-related stuff //! and command-line interface use crate::{ app::{ events::{Event, EventDevice, EventsSdl}, settings::{Settings, SoundBackend}, sound::{SoundDevice, DEFAULT_SAMPLE_RATE}, video::{Rect, TextureInfo, VideoDevice, VideoSdl}, }, host::{self, AppHost, AppHostContext, DetectedFileKind}, }; use anyhow::{anyhow, Context}; use rustzx_core::{ host::SnapshotRecorder, zx::constants::{ CANVAS_HEIGHT, CANVAS_WIDTH, CANVAS_X, CANVAS_Y, FPS, SCREEN_HEIGHT, SCREEN_WIDTH, }, Emulator, }; use rustzx_utils::io::FileAsset; use std::{ fs::{self, File}, path::{Path, PathBuf}, thread, time::{Duration, Instant}, }; /// max 100 ms interval in `max frames` speed mode const MAX_FRAME_TIME: Duration = Duration::from_millis(100); /// returns frame length from given `fps` fn frame_length(fps: usize) -> Duration { Duration::from_millis((1000_f64 / fps as f64) as u64) } /// Application instance type pub struct RustzxApp { /// main emulator object emulator: Emulator<AppHost>, /// Sound rendering in a separate thread snd: Option<Box<dyn SoundDevice>>, video: Box<dyn VideoDevice>, events: Box<dyn EventDevice>, tex_border: TextureInfo, tex_canvas: TextureInfo, scale: u32, settings: Settings, enable_frame_trace: bool, enable_joy_keyaboard_layer: bool, } impl RustzxApp { /// Starts application itself pub fn from_config(settings: Settings) -> anyhow::Result<RustzxApp> { let snd = if !settings.disable_sound { let backend = create_sound_backend(&settings).context( "Failed to initialize sound subsystem, try other sound backend or --nosound option", )?; Some(backend) } else { None }; let mut video = Box::new(VideoSdl::new(&settings)); let tex_border = video.gen_texture(SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32); let tex_canvas = video.gen_texture(CANVAS_WIDTH as u32, CANVAS_HEIGHT as u32); let scale = settings.scale as u32; let events = Box::new(EventsSdl::new(&settings)); let sample_rate = snd .as_ref() .map(|s| s.sample_rate()) .unwrap_or(DEFAULT_SAMPLE_RATE); let mut emulator = Emulator::new(settings.to_rustzx_settings(sample_rate), AppHostContext) .map_err(|e| anyhow!("Failed to construct emulator: {}", e))?; if let Some(rom) = settings.rom.as_ref() { emulator .load_rom(host::load_rom(rom, settings.machine)?) .map_err(|e| anyhow!("Emulator failed to load rom: {}", e))?; } if let Some(snapshot) = settings.snap.as_ref() { emulator .load_snapshot(host::load_snapshot(snapshot)?) .map_err(|e| anyhow!("Emulator failed to load snapshot: {}", e))?; } if let Some(tape) = settings.tape.as_ref() { emulator .load_tape(host::load_tape(tape)?) .map_err(|e| anyhow!("Emulator failed to load tape: {}", e))?; } if let Some(screen) = settings.screen.as_ref() { emulator .load_screen(host::load_screen(screen)?) .map_err(|e| anyhow!("Emulator failed to load screen: {}", e))?; } let file_autodetect = settings.file_autodetect.clone(); let mut app = RustzxApp { emulator, snd, video, events, tex_border, tex_canvas, scale, settings, enable_frame_trace: cfg!(debug_assertions), enable_joy_keyaboard_layer: false, }; if let Some(file) = file_autodetect.as_ref() { app.load_file_autodetect(file)?; } app.update_window_title(); Ok(app) } fn update_window_title(&mut self) { let mut title = format!("{} v{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION")); if self.enable_joy_keyaboard_layer { title.push_str(" [JOY]"); } if self.enable_frame_trace { title.push_str(" [FRAME_TRACE]"); } self.video.set_title(&title); } pub fn start(&mut self) -> anyhow::Result<()> { let scale = self.scale; 'emulator: loop { let frame_target_dt = frame_length(FPS); // absolute start time let frame_start = Instant::now(); // Emulate all requested frames let emulator_dt = self .emulator .emulate_frames(MAX_FRAME_TIME) .map_err(|e| anyhow!("Emulation step failed: {:#?}", e))?; // if sound enabled sound ganeration allowed then move samples to sound thread if let Some(ref mut snd) = self.snd { // if can be turned off even on speed change, so check it everytime if self.emulator.have_sound() { while let Some(sample) = self.emulator.next_audio_sample() { snd.send_sample(sample); } } } self.video .update_texture(self.tex_border, self.emulator.border_buffer().rgba_data()); self.video .update_texture(self.tex_canvas, self.emulator.screen_buffer().rgba_data()); self.video.begin(); self.video.draw_texture_2d( self.tex_border, Some(Rect::new( 0, 0, SCREEN_WIDTH as u32 * scale, SCREEN_HEIGHT as u32 * scale, )), ); self.video.draw_texture_2d( self.tex_canvas, Some(Rect::new( CANVAS_X as i32 * scale as i32, CANVAS_Y as i32 * scale as i32, CANVAS_WIDTH as u32 * scale, CANVAS_HEIGHT as u32 * scale, )), ); self.video.end(); // check all events while let Some(event) = self.events.pop_event() { match event { Event::Exit => { break 'emulator; } Event::ZXKey(key, state) => { self.emulator.send_key(key, state); } Event::SwitchFrameTrace => { self.enable_frame_trace = !self.enable_frame_trace; self.update_window_title(); } Event::ChangeJoyKeyboardLayer(value) => { self.enable_joy_keyaboard_layer = value; self.update_window_title(); } Event::ChangeSpeed(speed) => { self.emulator.set_speed(speed); } Event::Kempston(key, state) => { self.emulator.send_kempston_key(key, state); } Event::Sinclair(num, key, state) => { self.emulator.send_sinclair_key(num, key, state); } Event::CompoundKey(key, state) => { self.emulator.send_compound_key(key, state); } Event::MouseMove { x, y } => { self.emulator.send_mouse_pos_diff(x, y); } Event::MouseButton(buton, pressed) => { self.emulator.send_mouse_button(buton, pressed); } Event::MouseWheel(direction) => { self.emulator.send_mouse_wheel(direction); } Event::InsertTape => self.emulator.play_tape(), Event::StopTape => self.emulator.stop_tape(), Event::OpenFile(path) => self.load_file_autodetect(&path)?, Event::QuickSave => self.quick_save()?, Event::QuickLoad => self.quick_load()?, } } // how long emulation iteration was let emulation_dt = frame_start.elapsed(); if emulation_dt < frame_target_dt { let wait_koef = if self.emulator.have_sound() { 9 } else { 10 }; // sleep untill frame sync thread::sleep((frame_target_dt - emulation_dt) * wait_koef / 10); }; // get exceed clocks and use them on next iteration let frame_dt = frame_start.elapsed(); // change window header if self.enable_frame_trace { log::trace!( "EMUALTOR: {:7.3}ms; FRAME:{:7.3}ms", emulator_dt.as_millis(), frame_dt.as_millis() ); } } Ok(()) } fn load_file_autodetect(&mut self, path: &Path) -> anyhow::Result<()> { match host::detect_file_type(path)? { DetectedFileKind::Snapshot => { self.emulator .load_snapshot(host::load_snapshot(path)?) .map_err(|e| { anyhow!("Emulator failed to load auto-detected snapshot: {}", e) })?; } DetectedFileKind::Tape => { self.emulator .load_tape(host::load_tape(path)?) .map_err(|e| anyhow!("Emulator failed to load auto-detected tape: {}", e))?; } DetectedFileKind::Screen => self .emulator .load_screen(host::load_screen(path)?) .map_err(|e| anyhow!("Emulator failed load screen via auto-detect: {}", e))?, } Ok(()) } fn quick_save(&mut self) -> anyhow::Result<()> { let new_path = self.last_quick_snapshot_path(); let prev_path = self.prev_quick_snapshot_path(); if new_path.exists() { if prev_path.exists() { fs::remove_file(&prev_path)?; } fs::rename(&new_path, &prev_path)?; } let recorder = SnapshotRecorder::Sna(FileAsset::from(File::create(new_path)?)); self.emulator .save_snapshot(recorder) .map_err(|e| anyhow!("Failed to save qick snapshot: {}", e))?; Ok(()) } fn quick_load(&mut self) -> anyhow::Result<()> { let last_snapshot_path = self.last_quick_snapshot_path(); if !last_snapshot_path.exists() { log::warn!("Quick snapshot was not found"); return Ok(()); } self.emulator .load_snapshot(host::load_snapshot(&last_snapshot_path)?) .map_err(|e| anyhow!("Emulator failed to load quick snapshot: {}", e))?; Ok(()) } fn last_quick_snapshot_path(&self) -> PathBuf { if let Some(path) = self.settings.file_autodetect.as_ref() { return path.with_extension(".rustzx.last.sna"); } Path::new("default.rustzx.last.sna").to_owned() } fn prev_quick_snapshot_path(&self) -> PathBuf { if let Some(path) = self.settings.file_autodetect.as_ref() { return path.with_extension(".rustzx.prev.sna"); } Path::new("default.rustzx.prev.sna").to_owned() } } fn create_sound_backend(settings: &Settings) -> anyhow::Result<Box<dyn SoundDevice>> { use crate::app::sound; let backend: Box<dyn SoundDevice> = match settings.sound_backend { SoundBackend::Sdl => Box::new(sound::SoundSdl::new(settings)?), #[cfg(feature = "sound-cpal")] SoundBackend::Cpal => Box::new(sound::SoundCpal::new(settings)?), }; Ok(backend) }
mod helpers; use helpers as h; #[test] fn pipeline_helper() { let actual = h::pipeline( r#" open los_tres_amigos.txt | from-csv | get rusty_luck | str --to-int | sum | echo "$it" "#, ); assert_eq!( actual, r#"open los_tres_amigos.txt | from-csv | get rusty_luck | str --to-int | sum | echo "$it""# ); } #[test] fn external_num() { let actual = nu!( cwd: "tests/fixtures/formats", "open sgml_description.json | get glossary.GlossDiv.GlossList.GlossEntry.Height | echo $it" ); assert_eq!(actual, "10"); } #[test] fn external_has_correct_quotes() { let actual = nu!( cwd: ".", r#"echo "hello world""# ); assert_eq!(actual, r#"hello world"#); } #[test] fn add_plugin() { let actual = nu!( cwd: "tests/fixtures/formats", h::pipeline( r#" open cargo_sample.toml | add dev-dependencies.newdep "1" | get dev-dependencies.newdep | echo $it "# )); assert_eq!(actual, "1"); } #[test] fn edit_plugin() { let actual = nu!( cwd: "tests/fixtures/formats", h::pipeline( r#" open cargo_sample.toml | edit dev-dependencies.pretty_assertions "7" | get dev-dependencies.pretty_assertions | echo $it "# )); assert_eq!(actual, "7"); }
use crate::camera::{Camera, CameraConfig}; use crate::color::color; use crate::hittable::{ box3d::Box3D, bvh::BvhNode, flip_face::FlipFace, hittable_list::HittableList, rect::{XyRect, XzRect, YzRect}, rotate::RotateY, sphere::Sphere, translate::Translate, Hittables, }; use crate::material::{ dielectric::Dielectric, diffuse::Diffuse, lambertian::Lambertian, MaterialType, }; use crate::scenes::Scene; use crate::texture::solidcolor::SolidColor; use crate::vec::{vec3, Vec3}; use std::sync::Arc; #[allow(dead_code)] pub fn cornell_box(t0: f64, t1: f64, aspect_ratio: f64) -> Scene { let camera = Camera::new(CameraConfig { lookfrom: vec3(278.0, 278.0, -800.0), lookat: vec3(278.0, 278.0, 0.0), vup: vec3(0.0, 1.0, 0.0), vfov: 40.0, aspect_ratio: aspect_ratio, aperture: 0.0, focus_dist: 10.0, time0: t0, time1: t1, background: color(0.0, 0.0, 0.0), }); let red = Lambertian::new(SolidColor::new(0.65, 0.05, 0.05)); let white = Lambertian::new(SolidColor::new(0.73, 0.73, 0.73)); let green = Lambertian::new(SolidColor::new(0.12, 0.45, 0.15)); let light = Diffuse::new(SolidColor::new(15.0, 15.0, 15.0)); let wall1 = YzRect::new(0.0, 555.0, 0.0, 555.0, 555.0, green.clone()); let wall2 = YzRect::new(0.0, 555.0, 0.0, 555.0, 0.0, red.clone()); let wall3 = XzRect::new(0.0, 555.0, 0.0, 555.0, 0.0, white.clone()); let wall4 = XzRect::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()); let wall5 = XyRect::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()); let box1 = Box3D::new( vec3(0.0, 0.0, 0.0), vec3(165.0, 330.0, 165.0), white.clone(), ); let box1 = RotateY::new(Arc::new(box1), 15.0); let box1 = Translate::new(Arc::new(box1), vec3(265.0, 0.0, 295.0)); let box2 = Box3D::new( vec3(0.0, 0.0, 0.0), vec3(165.0, 165.0, 165.0), white.clone(), ); let box2 = RotateY::new(Arc::new(box2), -18.0); let box2 = Translate::new(Arc::new(box2), vec3(130.0, 0.0, 65.0)); let light = XzRect::new(213.0, 343.0, 227.0, 332.0, 554.0, light.clone()); let mut world = HittableList { hittables: Vec::new(), }; world.add(wall1); world.add(wall2); world.add(wall3); world.add(wall4); world.add(wall5); world.add(box1); world.add(box2); world.add(light); return Scene { camera: camera, hittables: Hittables::from(BvhNode::new(world, t0, t1)), lights: Hittables::from(HittableList { hittables: Vec::new(), }), }; } #[allow(dead_code)] pub fn cornell_box_sphere(t0: f64, t1: f64, aspect_ratio: f64) -> Scene { let camera = Camera::new(CameraConfig { lookfrom: vec3(278.0, 278.0, -800.0), lookat: vec3(278.0, 278.0, 0.0), vup: vec3(0.0, 1.0, 0.0), vfov: 40.0, aspect_ratio: aspect_ratio, aperture: 0.0, focus_dist: 10.0, time0: t0, time1: t1, background: color(0.0, 0.0, 0.0), }); let red = Lambertian::new(SolidColor::new(0.65, 0.05, 0.05)); let white = Lambertian::new(SolidColor::new(0.73, 0.73, 0.73)); let green = Lambertian::new(SolidColor::new(0.12, 0.45, 0.15)); let light = Diffuse::new(SolidColor::new(15.0, 15.0, 15.0)); let wall1 = YzRect::new(0.0, 555.0, 0.0, 555.0, 555.0, green.clone()); let wall2 = YzRect::new(0.0, 555.0, 0.0, 555.0, 0.0, red.clone()); let wall3 = XzRect::new(0.0, 555.0, 0.0, 555.0, 0.0, white.clone()); let wall4 = XzRect::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()); let wall5 = XyRect::new(0.0, 555.0, 0.0, 555.0, 555.0, white.clone()); let box1 = Box3D::new( vec3(0.0, 0.0, 0.0), vec3(165.0, 330.0, 165.0), white.clone(), ); let box1 = RotateY::new(Arc::new(box1), 15.0); let box1 = Translate::new(Arc::new(box1), vec3(265.0, 0.0, 295.0)); let glass = Dielectric::new(1.5); let sphere = Sphere::new(vec3(190.0, 90.0, 190.0), 90.0, glass.clone()); let light = FlipFace::new(XzRect::new( 213.0, 343.0, 227.0, 332.0, 554.0, light.clone(), )); let mut world = HittableList { hittables: Vec::new(), }; world.add(wall1); world.add(wall2); world.add(wall3); world.add(wall4); world.add(wall5); world.add(box1); world.add(sphere); world.add(light); let mut lights = HittableList { hittables: Vec::new(), }; lights.add(XzRect::new( 213.0, 343.0, 227.0, 332.0, 554.0, Arc::new(MaterialType::default()), )); lights.add(Sphere::new( Vec3::new(190.0, 90.0, 190.0), 90.0, Arc::new(MaterialType::default()), )); return Scene { camera: camera, hittables: Hittables::from(BvhNode::new(world, t0, t1)), lights: Hittables::from(lights), }; }
use crate::common::*; pub(crate) trait RangeExt<T> { fn range_contains(&self, i: &T) -> bool; } impl<T> RangeExt<T> for Range<T> where T: PartialOrd, { fn range_contains(&self, i: &T) -> bool { i >= &self.start && i < &self.end } } impl<T> RangeExt<T> for RangeInclusive<T> where T: PartialOrd, { fn range_contains(&self, i: &T) -> bool { i >= self.start() && i <= self.end() } } #[cfg(test)] mod tests { use super::*; #[test] fn exclusive() { assert!(!(0..0).range_contains(&0)); assert!(!(0..0).range_contains(&0)); assert!(!(1..10).range_contains(&0)); assert!(!(1..10).range_contains(&10)); assert!(!(1..10).range_contains(&0)); assert!(!(1..10).range_contains(&10)); assert!((0..1).range_contains(&0)); assert!((0..1).range_contains(&0)); assert!((10..20).range_contains(&15)); assert!((10..20).range_contains(&15)); } #[test] fn inclusive() { assert!(!(0..=10).range_contains(&11)); assert!(!(1..=10).range_contains(&0)); assert!(!(5..=10).range_contains(&4)); assert!((0..=0).range_contains(&0)); assert!((0..=1).range_contains(&0)); assert!((0..=10).range_contains(&0)); assert!((0..=10).range_contains(&10)); assert!((0..=10).range_contains(&7)); assert!((1..=10).range_contains(&10)); assert!((10..=20).range_contains(&15)); } }
use token; pub trait WithPrefix<U> { type Output; fn with_prefix(self, prefix: U) -> Self::Output; } impl<T, A, B, U> WithPrefix<U> for token::Token<T, (A, B)> where U: Clone, A: Clone, B: Clone { type Output = token::Token<T, (U, A, B)>; fn with_prefix(self, prefix: U) -> token::Token<T, (U, A, B)> { token::Token::new(self.inner, (prefix, self.pos.0, self.pos.1)) } }
#[doc = "Register `FLTCNVTIMR` reader"] pub type R = crate::R<FLTCNVTIMR_SPEC>; #[doc = "Field `CNVCNT` reader - 28-bit timer counting conversion time t = CNVCNT\\[27:0\\] / fDFSDMCLK The timer has an input clock from DFSDM clock (system clock fDFSDMCLK). Conversion time measurement is started on each conversion start and stopped when conversion finishes (interval between first and last serial sample). Only in case of filter bypass (FOSR\\[9:0\\] = 0) is the conversion time measurement stopped and CNVCNT\\[27:0\\] = 0. The counted time is: if FAST=0 (or first conversion in continuous mode if FAST=1): t = \\[FOSR * (IOSR-1 + FORD) + FORD\\] / fCKIN ..... for Sincx filters t = \\[FOSR * (IOSR-1 + 4) + 2\\] / fCKIN ..... for FastSinc filter if FAST=1 in continuous mode (except first conversion): t = \\[FOSR * IOSR\\] / fCKIN in case if FOSR = FOSR\\[9:0\\]+1 = 1 (filter bypassed, active only integrator): CNVCNT = 0 (counting is stopped, conversion time: t = IOSR / fCKIN) where: fCKIN is the channel input clock frequency (on given channel CKINy pin) or input data rate in case of parallel data input (from internal ADC or from CPU/DMA write) Note: When conversion is interrupted (e.g. by disable/enable selected channel) the timer counts also this interruption time."] pub type CNVCNT_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 4:31 - 28-bit timer counting conversion time t = CNVCNT\\[27:0\\] / fDFSDMCLK The timer has an input clock from DFSDM clock (system clock fDFSDMCLK). Conversion time measurement is started on each conversion start and stopped when conversion finishes (interval between first and last serial sample). Only in case of filter bypass (FOSR\\[9:0\\] = 0) is the conversion time measurement stopped and CNVCNT\\[27:0\\] = 0. The counted time is: if FAST=0 (or first conversion in continuous mode if FAST=1): t = \\[FOSR * (IOSR-1 + FORD) + FORD\\] / fCKIN ..... for Sincx filters t = \\[FOSR * (IOSR-1 + 4) + 2\\] / fCKIN ..... for FastSinc filter if FAST=1 in continuous mode (except first conversion): t = \\[FOSR * IOSR\\] / fCKIN in case if FOSR = FOSR\\[9:0\\]+1 = 1 (filter bypassed, active only integrator): CNVCNT = 0 (counting is stopped, conversion time: t = IOSR / fCKIN) where: fCKIN is the channel input clock frequency (on given channel CKINy pin) or input data rate in case of parallel data input (from internal ADC or from CPU/DMA write) Note: When conversion is interrupted (e.g. by disable/enable selected channel) the timer counts also this interruption time."] #[inline(always)] pub fn cnvcnt(&self) -> CNVCNT_R { CNVCNT_R::new((self.bits >> 4) & 0x0fff_ffff) } } #[doc = "\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fltcnvtimr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FLTCNVTIMR_SPEC; impl crate::RegisterSpec for FLTCNVTIMR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fltcnvtimr::R`](R) reader structure"] impl crate::Readable for FLTCNVTIMR_SPEC {} #[doc = "`reset()` method sets FLTCNVTIMR to value 0"] impl crate::Resettable for FLTCNVTIMR_SPEC { const RESET_VALUE: Self::Ux = 0; }
#[allow(unused_imports)] use log::{debug, error, info, warn}; use crate::{shader::ShaderInfo, Framebuffer}; use js_sys::Error; use regex::Regex; use std::collections::HashMap; use web_sys::{ WebGl2RenderingContext as Context, WebGlBuffer, WebGlProgram, WebGlShader, WebGlTexture, WebGlVertexArrayObject, }; #[derive(Clone, Copy, Debug)] pub enum BindingPoint { TextureUnit(u32), UniformBlock(u32), } #[derive(Debug)] pub struct Shader { gl: Context, invalidated: bool, handle: Option<WebGlProgram>, vertex: &'static ShaderInfo, fragment: &'static ShaderInfo, binds: HashMap<&'static str, BindingPoint>, headers: HashMap<&'static str, String>, defines: HashMap<&'static str, String>, } fn merge_sort_dedup(lhs: &[&'static str], rhs: &[&'static str]) -> Vec<&'static str> { let mut vec = Vec::with_capacity(lhs.len() + rhs.len()); vec.extend_from_slice(lhs); vec.extend_from_slice(rhs); vec.sort_unstable(); vec.dedup(); vec } impl Shader { pub fn new(gl: Context, vertex: &'static ShaderInfo, fragment: &'static ShaderInfo) -> Self { let mut headers = HashMap::new(); let mut defines = HashMap::new(); for key in merge_sort_dedup(vertex.defines, fragment.defines) { defines.insert(key, String::new()); } for key in merge_sort_dedup(vertex.headers, fragment.headers) { headers.insert(key, String::new()); } let mut binds = HashMap::new(); let uniform_blocks = merge_sort_dedup(vertex.uniform_blocks, fragment.uniform_blocks); let texture_units = merge_sort_dedup(vertex.texture_units, fragment.texture_units); for (index, &key) in uniform_blocks.iter().enumerate() { binds.insert(key, BindingPoint::UniformBlock(index as u32)); } for (index, &key) in texture_units.iter().enumerate() { binds.insert(key, BindingPoint::TextureUnit(index as u32)); } Self { gl, handle: None, vertex, fragment, binds, headers, defines, invalidated: true, } } pub fn set_header(&mut self, header: &'static str, value: impl ToString) { assert!(self.headers.contains_key(header)); if self.headers.get(header) != Some(&value.to_string()) { self.headers.insert(header, value.to_string()); self.invalidated = true; } } pub fn set_define(&mut self, define: &'static str, value: impl ToString) { assert!(self.defines.contains_key(define)); if self.defines.get(define) != Some(&value.to_string()) { self.defines.insert(define, value.to_string()); self.invalidated = true; } } pub fn begin_draw(&self) -> DrawCommand { DrawCommand::new(self) } pub fn invalidate(&mut self) { self.invalidated = true; self.handle = None; } /// Rebuilds the shader with the current source. pub fn rebuild(&mut self) -> Result<(), Error> { if !self.invalidated { return Ok(()); } if let Some(handle) = &self.handle { self.gl.delete_program(Some(handle)); } self.invalidated = false; let vert = self.compile_shader(Context::VERTEX_SHADER, self.vertex.code)?; let frag = self.compile_shader(Context::FRAGMENT_SHADER, self.fragment.code)?; if let (Some(vert), Some(frag)) = (&vert, &frag) { self.handle = self.link_program(vert, frag)?; self.configure_binds(); // initialize shader } else { self.handle = None; } Ok(()) } fn configure_binds(&self) { if let Some(program) = &self.handle { self.gl.use_program(Some(program)); for (&name, &binding_point) in &self.binds { match binding_point { BindingPoint::TextureUnit(slot) => { let location = self.gl.get_uniform_location(program, name); if let Some(location) = location { self.gl.uniform1i(Some(&location), slot as i32); } else { warn!("no such shader binding point: {}", name); } } BindingPoint::UniformBlock(slot) => { let index = self.gl.get_uniform_block_index(program, name); if index != Context::INVALID_INDEX { self.gl.uniform_block_binding(program, index, slot as u32); } else { warn!("no such shader binding point: {}", name); } } } } } } fn compile_shader(&self, kind: u32, source: &str) -> Result<Option<WebGlShader>, Error> { let shader = self.gl.create_shader(kind); if let Some(shader) = &shader { let glsl_source = Self::generate_source(source, &self.headers, &self.defines); self.gl.shader_source(shader, &glsl_source); self.gl.compile_shader(shader); if let Some(error) = self.get_shader_build_error(shader) { let pattern = Regex::new(r#"0:([0-9]+):"#).unwrap(); let error = pattern.replace_all(&error, |caps: &regex::Captures| { let line: u32 = caps.get(1).unwrap().as_str().parse().unwrap(); let (file, line) = Self::determine_real_position(&glsl_source, line); format!("{}:{}:", file, line) }); error!("{}", error); return Err(Error::new("failed to compile shader source")); } } Ok(shader) } fn link_program( &self, vert: &WebGlShader, frag: &WebGlShader, ) -> Result<Option<WebGlProgram>, Error> { let program = self.gl.create_program(); if let Some(program) = &program { self.gl.attach_shader(program, vert); self.gl.attach_shader(program, frag); self.gl.link_program(program); self.gl.delete_shader(Some(vert)); self.gl.delete_shader(Some(frag)); if let Some(error) = self.get_program_link_error(program) { error!("{}", error); return Err(Error::new("failed to link shader program")); } } Ok(program) } fn get_shader_build_error(&self, shader: &WebGlShader) -> Option<String> { if self.gl.is_context_lost() { return None; } let status = self .gl .get_shader_parameter(shader, Context::COMPILE_STATUS); if status.as_bool().unwrap_or(false) { return None; } if let Some(error) = self.gl.get_shader_info_log(shader) { Some(error) } else { Some(String::from("unknown shader building error")) } } fn get_program_link_error(&self, program: &WebGlProgram) -> Option<String> { if self.gl.is_context_lost() { return None; } let status = self.gl.get_program_parameter(program, Context::LINK_STATUS); if status.as_bool().unwrap_or(false) { return None; } if let Some(error) = self.gl.get_program_info_log(program) { Some(error) } else { Some(String::from("unknown program linking error")) } } fn generate_source( glsl_source: &str, headers: &HashMap<&'static str, String>, defines: &HashMap<&'static str, String>, ) -> String { let pattern = Regex::new(r#"^#include <([[:graph:]]*)>$"#).unwrap(); let mut source = String::from( r#"#version 300 es precision highp float; precision highp sampler2DArray; "#, ); source.reserve(glsl_source.len()); for (name, value) in defines { source += "#define "; source += name; source += " ("; source += value; source += ")\n"; } for line in glsl_source.lines() { if let Some(captures) = pattern.captures(line) { let header = captures.get(1).unwrap().as_str(); if let Some(code) = headers.get(header) { source += code; source += "\n"; continue; } } source += line; source += "\n"; } source } /// Finds the position of a GLSL source line through file/line markers. fn determine_real_position(source: &str, line: u32) -> (String, u32) { let pattern = Regex::new(r#"^// __POS__ ([^:]+):([0-9]+)$"#).unwrap(); let lines: Vec<&str> = source.lines().collect(); for index in (0..line).rev() { if let Some(captures) = pattern.captures(lines[index as usize]) { return ( captures.get(1).unwrap().as_str().to_owned(), captures.get(2).unwrap().as_str().parse::<u32>().unwrap() + line - index - 2, ); } } (String::from("<unknown>"), 0) } } #[derive(Debug)] pub struct DrawCommand<'a> { shader: &'a Shader, } #[derive(Debug)] pub enum BindTarget<'a> { UniformBuffer(Option<&'a WebGlBuffer>), Texture(Option<&'a WebGlTexture>, bool), } pub trait AsBindTarget { fn bind_target(&self) -> BindTarget; } pub trait AsVertexArray { fn vertex_array(&self) -> Option<&WebGlVertexArrayObject>; } impl<'a> DrawCommand<'a> { fn new(shader: &'a Shader) -> Self { shader.gl.use_program(shader.handle.as_ref()); shader.gl.disable(Context::BLEND); shader.gl.disable(Context::DEPTH_TEST); shader.gl.disable(Context::SCISSOR_TEST); shader.gl.disable(Context::STENCIL_TEST); shader.gl.viewport(0, 0, 0, 0); Self { shader } } pub fn bind(&self, target: &dyn AsBindTarget, slot: &str) { match target.bind_target() { BindTarget::UniformBuffer(handle) => self.bind_uniform_buffer(handle, slot), BindTarget::Texture(handle, array) => self.bind_texture(handle, slot, array), } } pub fn set_viewport(&self, x: i32, y: i32, w: i32, h: i32) { self.shader.gl.viewport(x, y, w, h); } pub fn set_scissor(&self, x: i32, y: i32, w: i32, h: i32) { self.shader.gl.enable(Context::SCISSOR_TEST); self.shader.gl.scissor(x, y, w, h); } pub fn unset_scissor(&self) { self.shader.gl.disable(Context::SCISSOR_TEST); } pub fn set_blend_mode(&self, mode: BlendMode) { self.shader.gl.enable(Context::BLEND); match mode { BlendMode::Accumulate { weight } => { self.shader.gl.blend_equation(Context::FUNC_ADD); self.shader .gl .blend_func(Context::CONSTANT_ALPHA, Context::ONE_MINUS_CONSTANT_ALPHA); self.shader.gl.blend_color(0.0, 0.0, 0.0, weight); } BlendMode::Add => { self.shader.gl.blend_equation(Context::FUNC_ADD); self.shader.gl.blend_func(Context::ONE, Context::ONE); } BlendMode::AlphaPredicatedAdd => { self.shader.gl.blend_equation(Context::FUNC_ADD); self.shader .gl .blend_func(Context::ONE, Context::ONE_MINUS_SRC_ALPHA); } } } pub fn unset_blend_mode(&self) { self.shader.gl.disable(Context::BLEND); } pub fn set_vertex_array(&self, target: &dyn AsVertexArray) { self.shader.gl.bind_vertex_array(target.vertex_array()); } pub fn unset_vertex_array(&self) { self.shader.gl.bind_vertex_array(None); } pub fn set_framebuffer(&self, target: &Framebuffer) { self.shader .gl .bind_framebuffer(Context::DRAW_FRAMEBUFFER, target.handle()); } pub fn set_canvas_framebuffer(&self) { self.shader .gl .bind_framebuffer(Context::DRAW_FRAMEBUFFER, None); } pub fn draw_triangles(&self, index: usize, triangles: usize) { self.shader .gl .draw_arrays(Context::TRIANGLES, 3 * index as i32, 3 * triangles as i32); } pub fn draw_points(&self, index: usize, points: usize) { self.shader .gl .draw_arrays(Context::POINTS, index as i32, points as i32); } pub fn set_uniform_ivec2(&self, name: &str, x: i32, y: i32) { if let Some(program) = &self.shader.handle { let location = self.shader.gl.get_uniform_location(program, name); self.shader.gl.uniform2i(location.as_ref(), x, y); } } fn bind_uniform_buffer(&self, handle: Option<&WebGlBuffer>, slot: &str) { if let Some(&BindingPoint::UniformBlock(slot)) = self.shader.binds.get(slot) { self.shader .gl .bind_buffer_base(Context::UNIFORM_BUFFER, slot, handle); } else { panic!("slot '{}' does not map to a binding point", slot); } } fn bind_texture(&self, handle: Option<&WebGlTexture>, slot: &str, array: bool) { if let Some(&BindingPoint::TextureUnit(slot)) = self.shader.binds.get(slot) { self.shader.gl.active_texture(Context::TEXTURE0 + slot); self.shader.gl.bind_texture( if array { Context::TEXTURE_2D_ARRAY } else { Context::TEXTURE_2D }, handle, ); } else { panic!("slot '{}' does not map to a binding point", slot); } } } pub enum BlendMode { Accumulate { weight: f32 }, Add, AlphaPredicatedAdd, }
use ast::Ast; #[allow(unused_imports)] use nom::*; use datatype::Datatype; use std::str::FromStr; use std::str; named!(number_raw<i32>, do_parse!( number: map_res!( map_res!( recognize!( digit ), str::from_utf8 ), FromStr::from_str ) >> (number) ) ); named!(pub number_literal<Ast>, do_parse!( num: ws!(number_raw) >> (Ast::Literal ( Datatype::Number(num))) ) ); #[test] fn parse_number_test() { let (_, value) = match number_raw(b"42") { IResult::Done(r, v) => (r, v), IResult::Error(e) => panic!("{:?}", e), _ => panic!(), }; assert_eq!(42, value) } #[test] fn parse_number_literal_test() { let (_, value) = match number_literal(b"42") { IResult::Done(r, v) => (r, v), IResult::Error(e) => panic!("{:?}", e), _ => panic!(), }; assert_eq!(Ast::Literal ( Datatype::Number(42)), value) }
use std::collections::VecDeque; use std::iter::FromIterator; use anyhow::Result; use itertools::Itertools; fn main() -> Result<()> { let input: Vec<u32> = INPUT.chars().map(|l| l.to_string().parse().unwrap()).collect(); let result = crab_cups(&input, 100); dbg!(result[1..].iter().join("")); let mut big_input = Vec::new(); big_input.push(0); big_input.extend((1..10).into_iter().map(|n| { let (i, _) = input.iter().enumerate().filter(|(_, &m)| m==n).next().unwrap(); if i == 8 { 10 as usize } else { input[i+1] as usize } })); big_input.extend(11..1_000_001); big_input.push(input[0] as usize); dbg!(big_input.len()); let big_result = indexed_crab_cups(input[0] as usize, &mut big_input, 10_000_000); dbg!(big_result); Ok(()) } fn indexed_crab_cups(start: usize, index: &mut[usize], rounds: usize) -> usize { let max = index.len()-1; let mut current = start; let mut selected = Vec::new(); for _ in 0..rounds { selected.push(index[current]); selected.push(index[index[current]]); selected.push(index[index[index[current]]]); let mut target = if current == 1 { max } else { current - 1 }; while selected.contains(&target) { target = if target == 1 { max } else { target - 1 }; } //Move the selected elements to after the target // Remove the selected elements from after the current element index[current] = index[selected[2]]; // splice the selected element in before the target's next index[selected[2]] = index[target]; // point the target at the beginning of the selection index[target] = selected[0]; selected.clear(); current = index[current]; } index[1] * index[index[1]] } fn crab_cups(seq: &[u32], rounds: usize) -> Vec<u32>{ let count = seq.len() as u32; let mut buf = VecDeque::from_iter(seq.iter().copied()); let mut selected = Vec::new(); for _ in 0..rounds { let current = buf.front().unwrap().to_owned(); buf.rotate_left(1); selected.push(buf.pop_front().unwrap().to_owned()); selected.push(buf.pop_front().unwrap().to_owned()); selected.push(buf.pop_front().unwrap().to_owned()); let mut target = if current == 1 { count } else { current - 1 }; while selected.contains(&target) { target = if target == 1 { count } else { target - 1 }; } while buf.front().unwrap() != &target { buf.rotate_right(1); } buf.rotate_left(1); buf.push_front(selected.pop().unwrap()); buf.push_front(selected.pop().unwrap()); buf.push_front(selected.pop().unwrap()); while buf.back().unwrap() != &current { buf.rotate_right(1); } } while buf.front().unwrap().to_owned() != 1 { buf.rotate_left(1); } buf.into() } const INPUT: &str = r#"198753462"#; const TEST: &str = r#"389125467"#;
#[doc = "Register `ISR` reader"] pub type R = crate::R<ISR_SPEC>; #[doc = "Register `ISR` writer"] pub type W = crate::W<ISR_SPEC>; #[doc = "Field `ALRAWF` reader - Alarm A write flag This bit is set by hardware when Alarm A values can be changed, after the ALRAE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."] pub type ALRAWF_R = crate::BitReader<ALRAWFR_A>; #[doc = "Alarm A write flag This bit is set by hardware when Alarm A values can be changed, after the ALRAE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode.\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRAWFR_A { #[doc = "0: Alarm update not allowed"] UpdateNotAllowed = 0, #[doc = "1: Alarm update allowed"] UpdateAllowed = 1, } impl From<ALRAWFR_A> for bool { #[inline(always)] fn from(variant: ALRAWFR_A) -> Self { variant as u8 != 0 } } impl ALRAWF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ALRAWFR_A { match self.bits { false => ALRAWFR_A::UpdateNotAllowed, true => ALRAWFR_A::UpdateAllowed, } } #[doc = "Alarm update not allowed"] #[inline(always)] pub fn is_update_not_allowed(&self) -> bool { *self == ALRAWFR_A::UpdateNotAllowed } #[doc = "Alarm update allowed"] #[inline(always)] pub fn is_update_allowed(&self) -> bool { *self == ALRAWFR_A::UpdateAllowed } } #[doc = "Field `ALRBWF` reader - Alarm B write flag This bit is set by hardware when Alarm B values can be changed, after the ALRBE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."] pub use ALRAWF_R as ALRBWF_R; #[doc = "Field `WUTWF` reader - Wakeup timer write flag This bit is set by hardware up to 2 RTCCLK cycles after the WUTE bit has been set to 0 in RTC_CR, and is cleared up to 2 RTCCLK cycles after the WUTE bit has been set to 1. The wakeup timer values can be changed when WUTE bit is cleared and WUTWF is set."] pub type WUTWF_R = crate::BitReader<WUTWFR_A>; #[doc = "Wakeup timer write flag This bit is set by hardware up to 2 RTCCLK cycles after the WUTE bit has been set to 0 in RTC_CR, and is cleared up to 2 RTCCLK cycles after the WUTE bit has been set to 1. The wakeup timer values can be changed when WUTE bit is cleared and WUTWF is set.\n\nValue on reset: 1"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WUTWFR_A { #[doc = "0: Wakeup timer configuration update not allowed"] UpdateNotAllowed = 0, #[doc = "1: Wakeup timer configuration update allowed"] UpdateAllowed = 1, } impl From<WUTWFR_A> for bool { #[inline(always)] fn from(variant: WUTWFR_A) -> Self { variant as u8 != 0 } } impl WUTWF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> WUTWFR_A { match self.bits { false => WUTWFR_A::UpdateNotAllowed, true => WUTWFR_A::UpdateAllowed, } } #[doc = "Wakeup timer configuration update not allowed"] #[inline(always)] pub fn is_update_not_allowed(&self) -> bool { *self == WUTWFR_A::UpdateNotAllowed } #[doc = "Wakeup timer configuration update allowed"] #[inline(always)] pub fn is_update_allowed(&self) -> bool { *self == WUTWFR_A::UpdateAllowed } } #[doc = "Field `SHPF` reader - Shift operation pending This flag is set by hardware as soon as a shift operation is initiated by a write to the RTC_SHIFTR register. It is cleared by hardware when the corresponding shift operation has been executed. Writing to the SHPF bit has no effect."] pub type SHPF_R = crate::BitReader<SHPFR_A>; #[doc = "Shift operation pending This flag is set by hardware as soon as a shift operation is initiated by a write to the RTC_SHIFTR register. It is cleared by hardware when the corresponding shift operation has been executed. Writing to the SHPF bit has no effect.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SHPFR_A { #[doc = "0: No shift operation is pending"] NoShiftPending = 0, #[doc = "1: A shift operation is pending"] ShiftPending = 1, } impl From<SHPFR_A> for bool { #[inline(always)] fn from(variant: SHPFR_A) -> Self { variant as u8 != 0 } } impl SHPF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SHPFR_A { match self.bits { false => SHPFR_A::NoShiftPending, true => SHPFR_A::ShiftPending, } } #[doc = "No shift operation is pending"] #[inline(always)] pub fn is_no_shift_pending(&self) -> bool { *self == SHPFR_A::NoShiftPending } #[doc = "A shift operation is pending"] #[inline(always)] pub fn is_shift_pending(&self) -> bool { *self == SHPFR_A::ShiftPending } } #[doc = "Field `INITS` reader - Initialization status flag This bit is set by hardware when the calendar year field is different from 0 (Backup domain reset state)."] pub type INITS_R = crate::BitReader<INITSR_A>; #[doc = "Initialization status flag This bit is set by hardware when the calendar year field is different from 0 (Backup domain reset state).\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum INITSR_A { #[doc = "0: Calendar has not been initialized"] NotInitalized = 0, #[doc = "1: Calendar has been initialized"] Initalized = 1, } impl From<INITSR_A> for bool { #[inline(always)] fn from(variant: INITSR_A) -> Self { variant as u8 != 0 } } impl INITS_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> INITSR_A { match self.bits { false => INITSR_A::NotInitalized, true => INITSR_A::Initalized, } } #[doc = "Calendar has not been initialized"] #[inline(always)] pub fn is_not_initalized(&self) -> bool { *self == INITSR_A::NotInitalized } #[doc = "Calendar has been initialized"] #[inline(always)] pub fn is_initalized(&self) -> bool { *self == INITSR_A::Initalized } } #[doc = "Field `RSF` reader - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."] pub type RSF_R = crate::BitReader<RSFR_A>; #[doc = "Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RSFR_A { #[doc = "0: Calendar shadow registers not yet synchronized"] NotSynced = 0, #[doc = "1: Calendar shadow registers synchronized"] Synced = 1, } impl From<RSFR_A> for bool { #[inline(always)] fn from(variant: RSFR_A) -> Self { variant as u8 != 0 } } impl RSF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RSFR_A { match self.bits { false => RSFR_A::NotSynced, true => RSFR_A::Synced, } } #[doc = "Calendar shadow registers not yet synchronized"] #[inline(always)] pub fn is_not_synced(&self) -> bool { *self == RSFR_A::NotSynced } #[doc = "Calendar shadow registers synchronized"] #[inline(always)] pub fn is_synced(&self) -> bool { *self == RSFR_A::Synced } } #[doc = "Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RSFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<RSFW_AW> for bool { #[inline(always)] fn from(variant: RSFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `RSF` writer - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."] pub type RSF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, RSFW_AW>; impl<'a, REG, const O: u8> RSF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(RSFW_AW::Clear) } } #[doc = "Field `INITF` reader - Initialization flag When this bit is set to 1, the RTC is in initialization state, and the time, date and prescaler registers can be updated."] pub type INITF_R = crate::BitReader<INITFR_A>; #[doc = "Initialization flag When this bit is set to 1, the RTC is in initialization state, and the time, date and prescaler registers can be updated.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum INITFR_A { #[doc = "0: Calendar registers update is not allowed"] NotAllowed = 0, #[doc = "1: Calendar registers update is allowed"] Allowed = 1, } impl From<INITFR_A> for bool { #[inline(always)] fn from(variant: INITFR_A) -> Self { variant as u8 != 0 } } impl INITF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> INITFR_A { match self.bits { false => INITFR_A::NotAllowed, true => INITFR_A::Allowed, } } #[doc = "Calendar registers update is not allowed"] #[inline(always)] pub fn is_not_allowed(&self) -> bool { *self == INITFR_A::NotAllowed } #[doc = "Calendar registers update is allowed"] #[inline(always)] pub fn is_allowed(&self) -> bool { *self == INITFR_A::Allowed } } #[doc = "Field `INIT` reader - Initialization mode"] pub type INIT_R = crate::BitReader<INIT_A>; #[doc = "Initialization mode\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum INIT_A { #[doc = "0: Free running mode"] FreeRunningMode = 0, #[doc = "1: Initialization mode used to program time and date register (RTC_TR and RTC_DR), and prescaler register (RTC_PRER). Counters are stopped and start counting from the new value when INIT is reset."] InitMode = 1, } impl From<INIT_A> for bool { #[inline(always)] fn from(variant: INIT_A) -> Self { variant as u8 != 0 } } impl INIT_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> INIT_A { match self.bits { false => INIT_A::FreeRunningMode, true => INIT_A::InitMode, } } #[doc = "Free running mode"] #[inline(always)] pub fn is_free_running_mode(&self) -> bool { *self == INIT_A::FreeRunningMode } #[doc = "Initialization mode used to program time and date register (RTC_TR and RTC_DR), and prescaler register (RTC_PRER). Counters are stopped and start counting from the new value when INIT is reset."] #[inline(always)] pub fn is_init_mode(&self) -> bool { *self == INIT_A::InitMode } } #[doc = "Field `INIT` writer - Initialization mode"] pub type INIT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, INIT_A>; impl<'a, REG, const O: u8> INIT_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Free running mode"] #[inline(always)] pub fn free_running_mode(self) -> &'a mut crate::W<REG> { self.variant(INIT_A::FreeRunningMode) } #[doc = "Initialization mode used to program time and date register (RTC_TR and RTC_DR), and prescaler register (RTC_PRER). Counters are stopped and start counting from the new value when INIT is reset."] #[inline(always)] pub fn init_mode(self) -> &'a mut crate::W<REG> { self.variant(INIT_A::InitMode) } } #[doc = "Field `ALRAF` reader - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."] pub type ALRAF_R = crate::BitReader<ALRAFR_A>; #[doc = "Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRAFR_A { #[doc = "1: This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR)"] Match = 1, } impl From<ALRAFR_A> for bool { #[inline(always)] fn from(variant: ALRAFR_A) -> Self { variant as u8 != 0 } } impl ALRAF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<ALRAFR_A> { match self.bits { true => Some(ALRAFR_A::Match), _ => None, } } #[doc = "This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR)"] #[inline(always)] pub fn is_match(&self) -> bool { *self == ALRAFR_A::Match } } #[doc = "Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRAFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<ALRAFW_AW> for bool { #[inline(always)] fn from(variant: ALRAFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `ALRAF` writer - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."] pub type ALRAF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, ALRAFW_AW>; impl<'a, REG, const O: u8> ALRAF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(ALRAFW_AW::Clear) } } #[doc = "Field `ALRBF` reader - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."] pub type ALRBF_R = crate::BitReader<ALRBFR_A>; #[doc = "Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRBFR_A { #[doc = "1: This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR)"] Match = 1, } impl From<ALRBFR_A> for bool { #[inline(always)] fn from(variant: ALRBFR_A) -> Self { variant as u8 != 0 } } impl ALRBF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<ALRBFR_A> { match self.bits { true => Some(ALRBFR_A::Match), _ => None, } } #[doc = "This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR)"] #[inline(always)] pub fn is_match(&self) -> bool { *self == ALRBFR_A::Match } } #[doc = "Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ALRBFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<ALRBFW_AW> for bool { #[inline(always)] fn from(variant: ALRBFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `ALRBF` writer - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."] pub type ALRBF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, ALRBFW_AW>; impl<'a, REG, const O: u8> ALRBF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(ALRBFW_AW::Clear) } } #[doc = "Field `WUTF` reader - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] pub type WUTF_R = crate::BitReader<WUTFR_A>; #[doc = "Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WUTFR_A { #[doc = "1: This flag is set by hardware when the wakeup auto-reload counter reaches 0"] Zero = 1, } impl From<WUTFR_A> for bool { #[inline(always)] fn from(variant: WUTFR_A) -> Self { variant as u8 != 0 } } impl WUTF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<WUTFR_A> { match self.bits { true => Some(WUTFR_A::Zero), _ => None, } } #[doc = "This flag is set by hardware when the wakeup auto-reload counter reaches 0"] #[inline(always)] pub fn is_zero(&self) -> bool { *self == WUTFR_A::Zero } } #[doc = "Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WUTFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<WUTFW_AW> for bool { #[inline(always)] fn from(variant: WUTFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `WUTF` writer - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] pub type WUTF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, WUTFW_AW>; impl<'a, REG, const O: u8> WUTF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(WUTFW_AW::Clear) } } #[doc = "Field `TSF` reader - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."] pub type TSF_R = crate::BitReader<TSFR_A>; #[doc = "Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TSFR_A { #[doc = "1: This flag is set by hardware when a time-stamp event occurs"] TimestampEvent = 1, } impl From<TSFR_A> for bool { #[inline(always)] fn from(variant: TSFR_A) -> Self { variant as u8 != 0 } } impl TSF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<TSFR_A> { match self.bits { true => Some(TSFR_A::TimestampEvent), _ => None, } } #[doc = "This flag is set by hardware when a time-stamp event occurs"] #[inline(always)] pub fn is_timestamp_event(&self) -> bool { *self == TSFR_A::TimestampEvent } } #[doc = "Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TSFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<TSFW_AW> for bool { #[inline(always)] fn from(variant: TSFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `TSF` writer - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."] pub type TSF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, TSFW_AW>; impl<'a, REG, const O: u8> TSF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(TSFW_AW::Clear) } } #[doc = "Field `TSOVF` reader - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."] pub type TSOVF_R = crate::BitReader<TSOVFR_A>; #[doc = "Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TSOVFR_A { #[doc = "1: This flag is set by hardware when a time-stamp event occurs while TSF is already set"] Overflow = 1, } impl From<TSOVFR_A> for bool { #[inline(always)] fn from(variant: TSOVFR_A) -> Self { variant as u8 != 0 } } impl TSOVF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<TSOVFR_A> { match self.bits { true => Some(TSOVFR_A::Overflow), _ => None, } } #[doc = "This flag is set by hardware when a time-stamp event occurs while TSF is already set"] #[inline(always)] pub fn is_overflow(&self) -> bool { *self == TSOVFR_A::Overflow } } #[doc = "Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TSOVFW_AW { #[doc = "0: This flag is cleared by software by writing 0"] Clear = 0, } impl From<TSOVFW_AW> for bool { #[inline(always)] fn from(variant: TSOVFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `TSOVF` writer - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."] pub type TSOVF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, TSOVFW_AW>; impl<'a, REG, const O: u8> TSOVF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(TSOVFW_AW::Clear) } } #[doc = "Field `TAMP1F` reader - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"] pub type TAMP1F_R = crate::BitReader<TAMP1FR_A>; #[doc = "RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TAMP1FR_A { #[doc = "1: This flag is set by hardware when a tamper detection event is detected on the RTC_TAMPx input"] Tampered = 1, } impl From<TAMP1FR_A> for bool { #[inline(always)] fn from(variant: TAMP1FR_A) -> Self { variant as u8 != 0 } } impl TAMP1F_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<TAMP1FR_A> { match self.bits { true => Some(TAMP1FR_A::Tampered), _ => None, } } #[doc = "This flag is set by hardware when a tamper detection event is detected on the RTC_TAMPx input"] #[inline(always)] pub fn is_tampered(&self) -> bool { *self == TAMP1FR_A::Tampered } } #[doc = "RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TAMP1FW_AW { #[doc = "0: Flag cleared by software writing 0"] Clear = 0, } impl From<TAMP1FW_AW> for bool { #[inline(always)] fn from(variant: TAMP1FW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `TAMP1F` writer - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"] pub type TAMP1F_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, TAMP1FW_AW>; impl<'a, REG, const O: u8> TAMP1F_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Flag cleared by software writing 0"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(TAMP1FW_AW::Clear) } } #[doc = "Field `TAMP2F` reader - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"] pub use TAMP1F_R as TAMP2F_R; #[doc = "Field `TAMP3F` reader - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"] pub use TAMP1F_R as TAMP3F_R; #[doc = "Field `TAMP2F` writer - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"] pub use TAMP1F_W as TAMP2F_W; #[doc = "Field `TAMP3F` writer - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"] pub use TAMP1F_W as TAMP3F_W; #[doc = "Field `RECALPF` reader - Recalibration pending Flag The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0. Refer to Re-calibration on-the-fly."] pub type RECALPF_R = crate::BitReader<RECALPFR_A>; #[doc = "Recalibration pending Flag The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0. Refer to Re-calibration on-the-fly.\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RECALPFR_A { #[doc = "1: The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0"] Pending = 1, } impl From<RECALPFR_A> for bool { #[inline(always)] fn from(variant: RECALPFR_A) -> Self { variant as u8 != 0 } } impl RECALPF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<RECALPFR_A> { match self.bits { true => Some(RECALPFR_A::Pending), _ => None, } } #[doc = "The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0"] #[inline(always)] pub fn is_pending(&self) -> bool { *self == RECALPFR_A::Pending } } #[doc = "Field `ITSF` reader - Internal tTime-stamp flag"] pub type ITSF_R = crate::BitReader<ITSFR_A>; #[doc = "Internal tTime-stamp flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ITSFR_A { #[doc = "1: This flag is set by hardware when a time-stamp on the internal event occurs"] Match = 1, } impl From<ITSFR_A> for bool { #[inline(always)] fn from(variant: ITSFR_A) -> Self { variant as u8 != 0 } } impl ITSF_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<ITSFR_A> { match self.bits { true => Some(ITSFR_A::Match), _ => None, } } #[doc = "This flag is set by hardware when a time-stamp on the internal event occurs"] #[inline(always)] pub fn is_match(&self) -> bool { *self == ITSFR_A::Match } } #[doc = "Internal tTime-stamp flag\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ITSFW_AW { #[doc = "0: This flag is cleared by software by writing 0, and must be cleared together with TSF bit by writing 0 in both bits"] Clear = 0, } impl From<ITSFW_AW> for bool { #[inline(always)] fn from(variant: ITSFW_AW) -> Self { variant as u8 != 0 } } #[doc = "Field `ITSF` writer - Internal tTime-stamp flag"] pub type ITSF_W<'a, REG, const O: u8> = crate::BitWriter0C<'a, REG, O, ITSFW_AW>; impl<'a, REG, const O: u8> ITSF_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "This flag is cleared by software by writing 0, and must be cleared together with TSF bit by writing 0 in both bits"] #[inline(always)] pub fn clear(self) -> &'a mut crate::W<REG> { self.variant(ITSFW_AW::Clear) } } impl R { #[doc = "Bit 0 - Alarm A write flag This bit is set by hardware when Alarm A values can be changed, after the ALRAE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."] #[inline(always)] pub fn alrawf(&self) -> ALRAWF_R { ALRAWF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Alarm B write flag This bit is set by hardware when Alarm B values can be changed, after the ALRBE bit has been set to 0 in RTC_CR. It is cleared by hardware in initialization mode."] #[inline(always)] pub fn alrbwf(&self) -> ALRBWF_R { ALRBWF_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Wakeup timer write flag This bit is set by hardware up to 2 RTCCLK cycles after the WUTE bit has been set to 0 in RTC_CR, and is cleared up to 2 RTCCLK cycles after the WUTE bit has been set to 1. The wakeup timer values can be changed when WUTE bit is cleared and WUTWF is set."] #[inline(always)] pub fn wutwf(&self) -> WUTWF_R { WUTWF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Shift operation pending This flag is set by hardware as soon as a shift operation is initiated by a write to the RTC_SHIFTR register. It is cleared by hardware when the corresponding shift operation has been executed. Writing to the SHPF bit has no effect."] #[inline(always)] pub fn shpf(&self) -> SHPF_R { SHPF_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Initialization status flag This bit is set by hardware when the calendar year field is different from 0 (Backup domain reset state)."] #[inline(always)] pub fn inits(&self) -> INITS_R { INITS_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."] #[inline(always)] pub fn rsf(&self) -> RSF_R { RSF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Initialization flag When this bit is set to 1, the RTC is in initialization state, and the time, date and prescaler registers can be updated."] #[inline(always)] pub fn initf(&self) -> INITF_R { INITF_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Initialization mode"] #[inline(always)] pub fn init(&self) -> INIT_R { INIT_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."] #[inline(always)] pub fn alraf(&self) -> ALRAF_R { ALRAF_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."] #[inline(always)] pub fn alrbf(&self) -> ALRBF_R { ALRBF_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] #[inline(always)] pub fn wutf(&self) -> WUTF_R { WUTF_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."] #[inline(always)] pub fn tsf(&self) -> TSF_R { TSF_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."] #[inline(always)] pub fn tsovf(&self) -> TSOVF_R { TSOVF_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"] #[inline(always)] pub fn tamp1f(&self) -> TAMP1F_R { TAMP1F_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"] #[inline(always)] pub fn tamp2f(&self) -> TAMP2F_R { TAMP2F_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"] #[inline(always)] pub fn tamp3f(&self) -> TAMP3F_R { TAMP3F_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - Recalibration pending Flag The RECALPF status flag is automatically set to 1 when software writes to the RTC_CALR register, indicating that the RTC_CALR register is blocked. When the new calibration settings are taken into account, this bit returns to 0. Refer to Re-calibration on-the-fly."] #[inline(always)] pub fn recalpf(&self) -> RECALPF_R { RECALPF_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Internal tTime-stamp flag"] #[inline(always)] pub fn itsf(&self) -> ITSF_R { ITSF_R::new(((self.bits >> 17) & 1) != 0) } } impl W { #[doc = "Bit 5 - Registers synchronization flag This bit is set by hardware each time the calendar registers are copied into the shadow registers (RTC_SSRx, RTC_TRx and RTC_DRx). This bit is cleared by hardware in initialization mode, while a shift operation is pending (SHPF=1), or when in bypass shadow register mode (BYPSHAD=1). This bit can also be cleared by software. It is cleared either by software or by hardware in initialization mode."] #[inline(always)] #[must_use] pub fn rsf(&mut self) -> RSF_W<ISR_SPEC, 5> { RSF_W::new(self) } #[doc = "Bit 7 - Initialization mode"] #[inline(always)] #[must_use] pub fn init(&mut self) -> INIT_W<ISR_SPEC, 7> { INIT_W::new(self) } #[doc = "Bit 8 - Alarm A flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm A register (RTC_ALRMAR). This flag is cleared by software by writing 0."] #[inline(always)] #[must_use] pub fn alraf(&mut self) -> ALRAF_W<ISR_SPEC, 8> { ALRAF_W::new(self) } #[doc = "Bit 9 - Alarm B flag This flag is set by hardware when the time/date registers (RTC_TR and RTC_DR) match the Alarm B register (RTC_ALRMBR). This flag is cleared by software by writing 0."] #[inline(always)] #[must_use] pub fn alrbf(&mut self) -> ALRBF_W<ISR_SPEC, 9> { ALRBF_W::new(self) } #[doc = "Bit 10 - Wakeup timer flag This flag is set by hardware when the wakeup auto-reload counter reaches 0. This flag is cleared by software by writing 0. This flag must be cleared by software at least 1.5 RTCCLK periods before WUTF is set to 1 again."] #[inline(always)] #[must_use] pub fn wutf(&mut self) -> WUTF_W<ISR_SPEC, 10> { WUTF_W::new(self) } #[doc = "Bit 11 - Time-stamp flag This flag is set by hardware when a time-stamp event occurs. This flag is cleared by software by writing 0."] #[inline(always)] #[must_use] pub fn tsf(&mut self) -> TSF_W<ISR_SPEC, 11> { TSF_W::new(self) } #[doc = "Bit 12 - Time-stamp overflow flag This flag is set by hardware when a time-stamp event occurs while TSF is already set. This flag is cleared by software by writing 0. It is recommended to check and then clear TSOVF only after clearing the TSF bit. Otherwise, an overflow might not be noticed if a time-stamp event occurs immediately before the TSF bit is cleared."] #[inline(always)] #[must_use] pub fn tsovf(&mut self) -> TSOVF_W<ISR_SPEC, 12> { TSOVF_W::new(self) } #[doc = "Bit 13 - RTC_TAMP1 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP1 input. It is cleared by software writing 0"] #[inline(always)] #[must_use] pub fn tamp1f(&mut self) -> TAMP1F_W<ISR_SPEC, 13> { TAMP1F_W::new(self) } #[doc = "Bit 14 - RTC_TAMP2 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP2 input. It is cleared by software writing 0"] #[inline(always)] #[must_use] pub fn tamp2f(&mut self) -> TAMP2F_W<ISR_SPEC, 14> { TAMP2F_W::new(self) } #[doc = "Bit 15 - RTC_TAMP3 detection flag This flag is set by hardware when a tamper detection event is detected on the RTC_TAMP3 input. It is cleared by software writing 0"] #[inline(always)] #[must_use] pub fn tamp3f(&mut self) -> TAMP3F_W<ISR_SPEC, 15> { TAMP3F_W::new(self) } #[doc = "Bit 17 - Internal tTime-stamp flag"] #[inline(always)] #[must_use] pub fn itsf(&mut self) -> ITSF_W<ISR_SPEC, 17> { ITSF_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 = "This register is write protected (except for RTC_ISR\\[13:8\\] bits). The write access procedure is described in RTC register write protection on page9.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::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 [`isr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ISR_SPEC; impl crate::RegisterSpec for ISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`isr::R`](R) reader structure"] impl crate::Readable for ISR_SPEC {} #[doc = "`write(|w| ..)` method takes [`isr::W`](W) writer structure"] impl crate::Writable for ISR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0x0002_ff20; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ISR to value 0x07"] impl crate::Resettable for ISR_SPEC { const RESET_VALUE: Self::Ux = 0x07; }
use crate::Num; #[derive(Copy, Clone)] pub struct Image { pub aspect_ratio: Num, pub width: usize, pub height: usize, } impl Image { pub(crate) fn from_width(aspect_ratio: Num, width: usize) -> Self { Self { aspect_ratio, width, height: (width as Num / aspect_ratio) as usize, } } }
fn main() { // ----------Primitive Types---------- println!("==========Primitive Types=========="); // ----------Booleans---------- println!("----------Booleans----------"); let a = true; let b: bool = false; println!("a is: {}", a); println!("b is: {}", b); // ----------Char---------- println!("----------Char----------"); let c = 'x'; let two_hearts = '💕'; println!("c is: {}", c); println!("two_hearts is: {}", two_hearts); // ----------Numeric types---------- println!("----------Numeric types----------"); let d = 42; // `x` has type `i32`. let e = 1.0; // `y` has type `f64`. println!("d is: {}", d); println!("e is: {}", e); /* Different Numberic Types i8 -> https://doc.rust-lang.org/std/primitive.i8.html i16 -> https://doc.rust-lang.org/std/primitive.i16.html i32 -> https://doc.rust-lang.org/std/primitive.i32.html i64 -> https://doc.rust-lang.org/std/primitive.i64.html u8 -> https://doc.rust-lang.org/std/primitive.u8.html u16 -> https://doc.rust-lang.org/std/primitive.u16.html u32 -> https://doc.rust-lang.org/std/primitive.u32.html u64 -> https://doc.rust-lang.org/std/primitive.u64.html isize -> https://doc.rust-lang.org/std/primitive.isize.html usize -> https://doc.rust-lang.org/std/primitive.usize.html f32 -> https://doc.rust-lang.org/std/primitive.f32.html f64 -> https://doc.rust-lang.org/std/primitive.f64.html */ // ----------Signed and Unsigned---------- // u -> Unsigned // i -> Signed // u8 is an eight-bit unsigned number // i8 is an eight-bit signed number // ----------Fixed-size types---------- // Fixed-size types have a specific number of bits in their representation // Valid bit sizes are 8, 16, 32, and 64 // u32 is an unsigned, 32-bit integer // i64 is a signed, 64-bit integer // ----------Variable-size types---------- // Rust also provides types whose particular size depends on the underlying machine architecture // signed and unsigned -> isize and usize // ----------Floating-point types---------- // f32 -> single precision numbers // f64 -> double precision numbers //----------Arrays---------- // Arrays are immutable // Type of an array -> [T; N] // T -> generic data type, N -> compile-time constant, for the length of the array println!("----------Arrays----------"); let f = [1, 2, 3]; // f: [i32; 3] let mut g = [1, 2, 3]; println!("f[0] is: {}", f[0]); println!("g[1] is: {}", g[1]); // Initializing each element of an array to the same value let h = [0; 20]; println!("h[0] is: {}", h[0]); println!("h[19] is: {}", h[19]); // Length of an array let i = [1, 2, 3, 4, 5]; println!("i has {} elements", i.len()); // Access elements of an array let names = ["Graydon", "Brian", "Niko"]; println!("The second name is: {}", names[1]); // ----------Slices---------- // View of another data structure // Useful for allowing safe, efficient access to a portion of an array without copying // Slices have a defined length, and can be mutable or immutable // Slices are represented as a pointer to the beginning of the data and a length // Type of a Slices -> &[T] println!("----------Slices----------"); let j = [0, 1, 2, 3, 4]; let complete = &j[..]; let middle = &j[1..4]; println!("j has {} elements", j.len()); println!("complete has {} elements", complete.len()); println!("middle has {} elements", middle.len()); // ----------Tuples---------- // Ordered list of fixed size println!("----------Tuples----------"); let k = (1, "hello"); println!("Tuple k : {:?}", k); let l: (i32, &str) = (1, "hello"); println!("Tuple l : {:?}", l); // Assign one tupe to another let mut m = (1, 2); let n = (2, 3); m = n; println!("Tuple m : {:?}", m); println!("Tuple n : {:?}", n); // Access the fields in a tuple through a destructuring let let (n, o, p) = (1, 2, 3); println!("n is {}", n); // Disambiguate a single-element tuple from a value in parentheses with a comma (0,); // A single-element tuple (0); // A zero in parentheses // Tuple Indexing let tuple = (1, 2, 3); let q = tuple.0; let r = tuple.1; let s = tuple.2; println!("q is {}", q); println!("r is {}", r); println!("s is {}", s); // Functions // Functions also have a type // x is a 'function pointer' to a function that takes an i32 and returns an i32. fn foo(x: i32) -> i32 { x } let x: fn(i32) -> i32 = foo; }